typescriptServices-amd.js 7.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519
  1. //
  2. // **NOTE**: Do not edit directly! This file is generated using `npm run import-typescript`
  3. //
  4. /*! *****************************************************************************
  5. Copyright (c) Microsoft Corporation. All rights reserved.
  6. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  7. this file except in compliance with the License. You may obtain a copy of the
  8. License at http://www.apache.org/licenses/LICENSE-2.0
  9. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  11. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  12. MERCHANTABLITY OR NON-INFRINGEMENT.
  13. See the Apache Version 2.0 License for specific language governing permissions
  14. and limitations under the License.
  15. ***************************************************************************** */
  16. "use strict";
  17. var __spreadArrays = (this && this.__spreadArrays) || function () {
  18. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  19. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  20. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  21. r[k] = a[j];
  22. return r;
  23. };
  24. var __assign = (this && this.__assign) || function () {
  25. __assign = Object.assign || function(t) {
  26. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27. s = arguments[i];
  28. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29. t[p] = s[p];
  30. }
  31. return t;
  32. };
  33. return __assign.apply(this, arguments);
  34. };
  35. var __generator = (this && this.__generator) || function (thisArg, body) {
  36. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  37. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  38. function verb(n) { return function (v) { return step([n, v]); }; }
  39. function step(op) {
  40. if (f) throw new TypeError("Generator is already executing.");
  41. while (_) try {
  42. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  43. if (y = 0, t) op = [op[0] & 2, t.value];
  44. switch (op[0]) {
  45. case 0: case 1: t = op; break;
  46. case 4: _.label++; return { value: op[1], done: false };
  47. case 5: _.label++; y = op[1]; op = [0]; continue;
  48. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  49. default:
  50. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  51. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  52. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  53. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  54. if (t[2]) _.ops.pop();
  55. _.trys.pop(); continue;
  56. }
  57. op = body.call(thisArg, _);
  58. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  59. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  60. }
  61. };
  62. var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
  63. if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
  64. return cooked;
  65. };
  66. var __rest = (this && this.__rest) || function (s, e) {
  67. var t = {};
  68. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  69. t[p] = s[p];
  70. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  71. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  72. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  73. t[p[i]] = s[p[i]];
  74. }
  75. return t;
  76. };
  77. var __extends = (this && this.__extends) || (function () {
  78. var extendStatics = function (d, b) {
  79. extendStatics = Object.setPrototypeOf ||
  80. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  81. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  82. return extendStatics(d, b);
  83. };
  84. return function (d, b) {
  85. extendStatics(d, b);
  86. function __() { this.constructor = d; }
  87. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  88. };
  89. })();
  90. /* @internal */
  91. var ts;
  92. (function (ts) {
  93. function createMapShim() {
  94. /** Create a MapLike with good performance. */
  95. function createDictionaryObject() {
  96. var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
  97. // Using 'delete' on an object causes V8 to put the object in dictionary mode.
  98. // This disables creation of hidden classes, which are expensive when an object is
  99. // constantly changing shape.
  100. map.__ = undefined;
  101. delete map.__;
  102. return map;
  103. }
  104. var MapIterator = /** @class */ (function () {
  105. function MapIterator(currentEntry, selector) {
  106. this.currentEntry = currentEntry;
  107. this.selector = selector;
  108. }
  109. MapIterator.prototype.next = function () {
  110. // Navigate to the next entry.
  111. while (this.currentEntry) {
  112. var skipNext = !!this.currentEntry.skipNext;
  113. this.currentEntry = this.currentEntry.nextEntry;
  114. if (!skipNext) {
  115. break;
  116. }
  117. }
  118. if (this.currentEntry) {
  119. return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
  120. }
  121. else {
  122. return { value: undefined, done: true };
  123. }
  124. };
  125. return MapIterator;
  126. }());
  127. return /** @class */ (function () {
  128. function class_1() {
  129. this.data = createDictionaryObject();
  130. this.size = 0;
  131. // Create a first (stub) map entry that will not contain a key
  132. // and value but serves as starting point for iterators.
  133. this.firstEntry = {};
  134. // When the map is empty, the last entry is the same as the
  135. // first one.
  136. this.lastEntry = this.firstEntry;
  137. }
  138. class_1.prototype.get = function (key) {
  139. var entry = this.data[key];
  140. return entry && entry.value;
  141. };
  142. class_1.prototype.set = function (key, value) {
  143. if (!this.has(key)) {
  144. this.size++;
  145. // Create a new entry that will be appended at the
  146. // end of the linked list.
  147. var newEntry = {
  148. key: key,
  149. value: value
  150. };
  151. this.data[key] = newEntry;
  152. // Adjust the references.
  153. var previousLastEntry = this.lastEntry;
  154. previousLastEntry.nextEntry = newEntry;
  155. newEntry.previousEntry = previousLastEntry;
  156. this.lastEntry = newEntry;
  157. }
  158. else {
  159. this.data[key].value = value;
  160. }
  161. return this;
  162. };
  163. class_1.prototype.has = function (key) {
  164. // eslint-disable-next-line no-in-operator
  165. return key in this.data;
  166. };
  167. class_1.prototype.delete = function (key) {
  168. if (this.has(key)) {
  169. this.size--;
  170. var entry = this.data[key];
  171. delete this.data[key];
  172. // Adjust the linked list references of the neighbor entries.
  173. var previousEntry = entry.previousEntry;
  174. previousEntry.nextEntry = entry.nextEntry;
  175. if (entry.nextEntry) {
  176. entry.nextEntry.previousEntry = previousEntry;
  177. }
  178. // When the deleted entry was the last one, we need to
  179. // adjust the lastEntry reference.
  180. if (this.lastEntry === entry) {
  181. this.lastEntry = previousEntry;
  182. }
  183. // Adjust the forward reference of the deleted entry
  184. // in case an iterator still references it. This allows us
  185. // to throw away the entry, but when an active iterator
  186. // (which points to the current entry) continues, it will
  187. // navigate to the entry that originally came before the
  188. // current one and skip it.
  189. entry.previousEntry = undefined;
  190. entry.nextEntry = previousEntry;
  191. entry.skipNext = true;
  192. return true;
  193. }
  194. return false;
  195. };
  196. class_1.prototype.clear = function () {
  197. this.data = createDictionaryObject();
  198. this.size = 0;
  199. // Reset the linked list. Note that we must adjust the forward
  200. // references of the deleted entries to ensure iterators stuck
  201. // in the middle of the list don't continue with deleted entries,
  202. // but can continue with new entries added after the clear()
  203. // operation.
  204. var firstEntry = this.firstEntry;
  205. var currentEntry = firstEntry.nextEntry;
  206. while (currentEntry) {
  207. var nextEntry = currentEntry.nextEntry;
  208. currentEntry.previousEntry = undefined;
  209. currentEntry.nextEntry = firstEntry;
  210. currentEntry.skipNext = true;
  211. currentEntry = nextEntry;
  212. }
  213. firstEntry.nextEntry = undefined;
  214. this.lastEntry = firstEntry;
  215. };
  216. class_1.prototype.keys = function () {
  217. return new MapIterator(this.firstEntry, function (key) { return key; });
  218. };
  219. class_1.prototype.values = function () {
  220. return new MapIterator(this.firstEntry, function (_key, value) { return value; });
  221. };
  222. class_1.prototype.entries = function () {
  223. return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
  224. };
  225. class_1.prototype.forEach = function (action) {
  226. var iterator = this.entries();
  227. while (true) {
  228. var iterResult = iterator.next();
  229. if (iterResult.done) {
  230. break;
  231. }
  232. var _a = iterResult.value, key = _a[0], value = _a[1];
  233. action(value, key);
  234. }
  235. };
  236. return class_1;
  237. }());
  238. }
  239. ts.createMapShim = createMapShim;
  240. })(ts || (ts = {}));
  241. var ts;
  242. (function (ts) {
  243. // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
  244. // If changing the text in this section, be sure to test `configurePrerelease` too.
  245. ts.versionMajorMinor = "3.8";
  246. /** The version of the TypeScript compiler release */
  247. ts.version = "3.8.3";
  248. /**
  249. * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
  250. */
  251. /* @internal */
  252. function tryGetNativeMap() {
  253. // eslint-disable-next-line no-in-operator
  254. return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
  255. }
  256. ts.tryGetNativeMap = tryGetNativeMap;
  257. /* @internal */
  258. ts.Map = tryGetNativeMap() || (function () {
  259. // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
  260. if (typeof ts.createMapShim === "function") {
  261. return ts.createMapShim();
  262. }
  263. throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
  264. })();
  265. /* @internal */
  266. var Comparison;
  267. (function (Comparison) {
  268. Comparison[Comparison["LessThan"] = -1] = "LessThan";
  269. Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
  270. Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
  271. })(Comparison = ts.Comparison || (ts.Comparison = {}));
  272. })(ts || (ts = {}));
  273. /* @internal */
  274. var ts;
  275. (function (ts) {
  276. ts.emptyArray = [];
  277. /** Create a new map. */
  278. function createMap() {
  279. return new ts.Map();
  280. }
  281. ts.createMap = createMap;
  282. /** Create a new map from an array of entries. */
  283. function createMapFromEntries(entries) {
  284. var map = createMap();
  285. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  286. var _a = entries_1[_i], key = _a[0], value = _a[1];
  287. map.set(key, value);
  288. }
  289. return map;
  290. }
  291. ts.createMapFromEntries = createMapFromEntries;
  292. /** Create a new map from a template object is provided, the map will copy entries from it. */
  293. function createMapFromTemplate(template) {
  294. var map = new ts.Map();
  295. // Copies keys/values from template. Note that for..in will not throw if
  296. // template is undefined, and instead will just exit the loop.
  297. for (var key in template) {
  298. if (hasOwnProperty.call(template, key)) {
  299. map.set(key, template[key]);
  300. }
  301. }
  302. return map;
  303. }
  304. ts.createMapFromTemplate = createMapFromTemplate;
  305. function length(array) {
  306. return array ? array.length : 0;
  307. }
  308. ts.length = length;
  309. /**
  310. * Iterates through 'array' by index and performs the callback on each element of array until the callback
  311. * returns a truthy value, then returns that value.
  312. * If no such value is found, the callback is applied to each element of array and undefined is returned.
  313. */
  314. function forEach(array, callback) {
  315. if (array) {
  316. for (var i = 0; i < array.length; i++) {
  317. var result = callback(array[i], i);
  318. if (result) {
  319. return result;
  320. }
  321. }
  322. }
  323. return undefined;
  324. }
  325. ts.forEach = forEach;
  326. /**
  327. * Like `forEach`, but iterates in reverse order.
  328. */
  329. function forEachRight(array, callback) {
  330. if (array) {
  331. for (var i = array.length - 1; i >= 0; i--) {
  332. var result = callback(array[i], i);
  333. if (result) {
  334. return result;
  335. }
  336. }
  337. }
  338. return undefined;
  339. }
  340. ts.forEachRight = forEachRight;
  341. /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
  342. function firstDefined(array, callback) {
  343. if (array === undefined) {
  344. return undefined;
  345. }
  346. for (var i = 0; i < array.length; i++) {
  347. var result = callback(array[i], i);
  348. if (result !== undefined) {
  349. return result;
  350. }
  351. }
  352. return undefined;
  353. }
  354. ts.firstDefined = firstDefined;
  355. function firstDefinedIterator(iter, callback) {
  356. while (true) {
  357. var iterResult = iter.next();
  358. if (iterResult.done) {
  359. return undefined;
  360. }
  361. var result = callback(iterResult.value);
  362. if (result !== undefined) {
  363. return result;
  364. }
  365. }
  366. }
  367. ts.firstDefinedIterator = firstDefinedIterator;
  368. function zipWith(arrayA, arrayB, callback) {
  369. var result = [];
  370. ts.Debug.assertEqual(arrayA.length, arrayB.length);
  371. for (var i = 0; i < arrayA.length; i++) {
  372. result.push(callback(arrayA[i], arrayB[i], i));
  373. }
  374. return result;
  375. }
  376. ts.zipWith = zipWith;
  377. function zipToIterator(arrayA, arrayB) {
  378. ts.Debug.assertEqual(arrayA.length, arrayB.length);
  379. var i = 0;
  380. return {
  381. next: function () {
  382. if (i === arrayA.length) {
  383. return { value: undefined, done: true };
  384. }
  385. i++;
  386. return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
  387. }
  388. };
  389. }
  390. ts.zipToIterator = zipToIterator;
  391. function zipToMap(keys, values) {
  392. ts.Debug.assert(keys.length === values.length);
  393. var map = createMap();
  394. for (var i = 0; i < keys.length; ++i) {
  395. map.set(keys[i], values[i]);
  396. }
  397. return map;
  398. }
  399. ts.zipToMap = zipToMap;
  400. /**
  401. * Iterates through `array` by index and performs the callback on each element of array until the callback
  402. * returns a falsey value, then returns false.
  403. * If no such value is found, the callback is applied to each element of array and `true` is returned.
  404. */
  405. function every(array, callback) {
  406. if (array) {
  407. for (var i = 0; i < array.length; i++) {
  408. if (!callback(array[i], i)) {
  409. return false;
  410. }
  411. }
  412. }
  413. return true;
  414. }
  415. ts.every = every;
  416. function find(array, predicate) {
  417. for (var i = 0; i < array.length; i++) {
  418. var value = array[i];
  419. if (predicate(value, i)) {
  420. return value;
  421. }
  422. }
  423. return undefined;
  424. }
  425. ts.find = find;
  426. function findLast(array, predicate) {
  427. for (var i = array.length - 1; i >= 0; i--) {
  428. var value = array[i];
  429. if (predicate(value, i)) {
  430. return value;
  431. }
  432. }
  433. return undefined;
  434. }
  435. ts.findLast = findLast;
  436. /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
  437. function findIndex(array, predicate, startIndex) {
  438. for (var i = startIndex || 0; i < array.length; i++) {
  439. if (predicate(array[i], i)) {
  440. return i;
  441. }
  442. }
  443. return -1;
  444. }
  445. ts.findIndex = findIndex;
  446. function findLastIndex(array, predicate, startIndex) {
  447. for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
  448. if (predicate(array[i], i)) {
  449. return i;
  450. }
  451. }
  452. return -1;
  453. }
  454. ts.findLastIndex = findLastIndex;
  455. /**
  456. * Returns the first truthy result of `callback`, or else fails.
  457. * This is like `forEach`, but never returns undefined.
  458. */
  459. function findMap(array, callback) {
  460. for (var i = 0; i < array.length; i++) {
  461. var result = callback(array[i], i);
  462. if (result) {
  463. return result;
  464. }
  465. }
  466. return ts.Debug.fail();
  467. }
  468. ts.findMap = findMap;
  469. function contains(array, value, equalityComparer) {
  470. if (equalityComparer === void 0) { equalityComparer = equateValues; }
  471. if (array) {
  472. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  473. var v = array_1[_i];
  474. if (equalityComparer(v, value)) {
  475. return true;
  476. }
  477. }
  478. }
  479. return false;
  480. }
  481. ts.contains = contains;
  482. function arraysEqual(a, b, equalityComparer) {
  483. if (equalityComparer === void 0) { equalityComparer = equateValues; }
  484. return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
  485. }
  486. ts.arraysEqual = arraysEqual;
  487. function indexOfAnyCharCode(text, charCodes, start) {
  488. for (var i = start || 0; i < text.length; i++) {
  489. if (contains(charCodes, text.charCodeAt(i))) {
  490. return i;
  491. }
  492. }
  493. return -1;
  494. }
  495. ts.indexOfAnyCharCode = indexOfAnyCharCode;
  496. function countWhere(array, predicate) {
  497. var count = 0;
  498. if (array) {
  499. for (var i = 0; i < array.length; i++) {
  500. var v = array[i];
  501. if (predicate(v, i)) {
  502. count++;
  503. }
  504. }
  505. }
  506. return count;
  507. }
  508. ts.countWhere = countWhere;
  509. function filter(array, f) {
  510. if (array) {
  511. var len = array.length;
  512. var i = 0;
  513. while (i < len && f(array[i]))
  514. i++;
  515. if (i < len) {
  516. var result = array.slice(0, i);
  517. i++;
  518. while (i < len) {
  519. var item = array[i];
  520. if (f(item)) {
  521. result.push(item);
  522. }
  523. i++;
  524. }
  525. return result;
  526. }
  527. }
  528. return array;
  529. }
  530. ts.filter = filter;
  531. function filterMutate(array, f) {
  532. var outIndex = 0;
  533. for (var i = 0; i < array.length; i++) {
  534. if (f(array[i], i, array)) {
  535. array[outIndex] = array[i];
  536. outIndex++;
  537. }
  538. }
  539. array.length = outIndex;
  540. }
  541. ts.filterMutate = filterMutate;
  542. function clear(array) {
  543. array.length = 0;
  544. }
  545. ts.clear = clear;
  546. function map(array, f) {
  547. var result;
  548. if (array) {
  549. result = [];
  550. for (var i = 0; i < array.length; i++) {
  551. result.push(f(array[i], i));
  552. }
  553. }
  554. return result;
  555. }
  556. ts.map = map;
  557. function mapIterator(iter, mapFn) {
  558. return {
  559. next: function () {
  560. var iterRes = iter.next();
  561. return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
  562. }
  563. };
  564. }
  565. ts.mapIterator = mapIterator;
  566. function sameMap(array, f) {
  567. if (array) {
  568. for (var i = 0; i < array.length; i++) {
  569. var item = array[i];
  570. var mapped = f(item, i);
  571. if (item !== mapped) {
  572. var result = array.slice(0, i);
  573. result.push(mapped);
  574. for (i++; i < array.length; i++) {
  575. result.push(f(array[i], i));
  576. }
  577. return result;
  578. }
  579. }
  580. }
  581. return array;
  582. }
  583. ts.sameMap = sameMap;
  584. /**
  585. * Flattens an array containing a mix of array or non-array elements.
  586. *
  587. * @param array The array to flatten.
  588. */
  589. function flatten(array) {
  590. var result = [];
  591. for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
  592. var v = array_2[_i];
  593. if (v) {
  594. if (isArray(v)) {
  595. addRange(result, v);
  596. }
  597. else {
  598. result.push(v);
  599. }
  600. }
  601. }
  602. return result;
  603. }
  604. ts.flatten = flatten;
  605. /**
  606. * Maps an array. If the mapped value is an array, it is spread into the result.
  607. *
  608. * @param array The array to map.
  609. * @param mapfn The callback used to map the result into one or more values.
  610. */
  611. function flatMap(array, mapfn) {
  612. var result;
  613. if (array) {
  614. for (var i = 0; i < array.length; i++) {
  615. var v = mapfn(array[i], i);
  616. if (v) {
  617. if (isArray(v)) {
  618. result = addRange(result, v);
  619. }
  620. else {
  621. result = append(result, v);
  622. }
  623. }
  624. }
  625. }
  626. return result || ts.emptyArray;
  627. }
  628. ts.flatMap = flatMap;
  629. function flatMapToMutable(array, mapfn) {
  630. var result = [];
  631. if (array) {
  632. for (var i = 0; i < array.length; i++) {
  633. var v = mapfn(array[i], i);
  634. if (v) {
  635. if (isArray(v)) {
  636. addRange(result, v);
  637. }
  638. else {
  639. result.push(v);
  640. }
  641. }
  642. }
  643. }
  644. return result;
  645. }
  646. ts.flatMapToMutable = flatMapToMutable;
  647. function flatMapIterator(iter, mapfn) {
  648. var first = iter.next();
  649. if (first.done) {
  650. return ts.emptyIterator;
  651. }
  652. var currentIter = getIterator(first.value);
  653. return {
  654. next: function () {
  655. while (true) {
  656. var currentRes = currentIter.next();
  657. if (!currentRes.done) {
  658. return currentRes;
  659. }
  660. var iterRes = iter.next();
  661. if (iterRes.done) {
  662. return iterRes;
  663. }
  664. currentIter = getIterator(iterRes.value);
  665. }
  666. },
  667. };
  668. function getIterator(x) {
  669. var res = mapfn(x);
  670. return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
  671. }
  672. }
  673. ts.flatMapIterator = flatMapIterator;
  674. function sameFlatMap(array, mapfn) {
  675. var result;
  676. if (array) {
  677. for (var i = 0; i < array.length; i++) {
  678. var item = array[i];
  679. var mapped = mapfn(item, i);
  680. if (result || item !== mapped || isArray(mapped)) {
  681. if (!result) {
  682. result = array.slice(0, i);
  683. }
  684. if (isArray(mapped)) {
  685. addRange(result, mapped);
  686. }
  687. else {
  688. result.push(mapped);
  689. }
  690. }
  691. }
  692. }
  693. return result || array;
  694. }
  695. ts.sameFlatMap = sameFlatMap;
  696. function mapAllOrFail(array, mapFn) {
  697. var result = [];
  698. for (var i = 0; i < array.length; i++) {
  699. var mapped = mapFn(array[i], i);
  700. if (mapped === undefined) {
  701. return undefined;
  702. }
  703. result.push(mapped);
  704. }
  705. return result;
  706. }
  707. ts.mapAllOrFail = mapAllOrFail;
  708. function mapDefined(array, mapFn) {
  709. var result = [];
  710. if (array) {
  711. for (var i = 0; i < array.length; i++) {
  712. var mapped = mapFn(array[i], i);
  713. if (mapped !== undefined) {
  714. result.push(mapped);
  715. }
  716. }
  717. }
  718. return result;
  719. }
  720. ts.mapDefined = mapDefined;
  721. function mapDefinedIterator(iter, mapFn) {
  722. return {
  723. next: function () {
  724. while (true) {
  725. var res = iter.next();
  726. if (res.done) {
  727. return res;
  728. }
  729. var value = mapFn(res.value);
  730. if (value !== undefined) {
  731. return { value: value, done: false };
  732. }
  733. }
  734. }
  735. };
  736. }
  737. ts.mapDefinedIterator = mapDefinedIterator;
  738. function mapDefinedMap(map, mapValue, mapKey) {
  739. if (mapKey === void 0) { mapKey = identity; }
  740. var result = createMap();
  741. map.forEach(function (value, key) {
  742. var mapped = mapValue(value, key);
  743. if (mapped !== undefined) {
  744. result.set(mapKey(key), mapped);
  745. }
  746. });
  747. return result;
  748. }
  749. ts.mapDefinedMap = mapDefinedMap;
  750. ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
  751. function singleIterator(value) {
  752. var done = false;
  753. return {
  754. next: function () {
  755. var wasDone = done;
  756. done = true;
  757. return wasDone ? { value: undefined, done: true } : { value: value, done: false };
  758. }
  759. };
  760. }
  761. ts.singleIterator = singleIterator;
  762. function spanMap(array, keyfn, mapfn) {
  763. var result;
  764. if (array) {
  765. result = [];
  766. var len = array.length;
  767. var previousKey = void 0;
  768. var key = void 0;
  769. var start = 0;
  770. var pos = 0;
  771. while (start < len) {
  772. while (pos < len) {
  773. var value = array[pos];
  774. key = keyfn(value, pos);
  775. if (pos === 0) {
  776. previousKey = key;
  777. }
  778. else if (key !== previousKey) {
  779. break;
  780. }
  781. pos++;
  782. }
  783. if (start < pos) {
  784. var v = mapfn(array.slice(start, pos), previousKey, start, pos);
  785. if (v) {
  786. result.push(v);
  787. }
  788. start = pos;
  789. }
  790. previousKey = key;
  791. pos++;
  792. }
  793. }
  794. return result;
  795. }
  796. ts.spanMap = spanMap;
  797. function mapEntries(map, f) {
  798. if (!map) {
  799. return undefined;
  800. }
  801. var result = createMap();
  802. map.forEach(function (value, key) {
  803. var _a = f(key, value), newKey = _a[0], newValue = _a[1];
  804. result.set(newKey, newValue);
  805. });
  806. return result;
  807. }
  808. ts.mapEntries = mapEntries;
  809. function some(array, predicate) {
  810. if (array) {
  811. if (predicate) {
  812. for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
  813. var v = array_3[_i];
  814. if (predicate(v)) {
  815. return true;
  816. }
  817. }
  818. }
  819. else {
  820. return array.length > 0;
  821. }
  822. }
  823. return false;
  824. }
  825. ts.some = some;
  826. /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
  827. function getRangesWhere(arr, pred, cb) {
  828. var start;
  829. for (var i = 0; i < arr.length; i++) {
  830. if (pred(arr[i])) {
  831. start = start === undefined ? i : start;
  832. }
  833. else {
  834. if (start !== undefined) {
  835. cb(start, i);
  836. start = undefined;
  837. }
  838. }
  839. }
  840. if (start !== undefined)
  841. cb(start, arr.length);
  842. }
  843. ts.getRangesWhere = getRangesWhere;
  844. function concatenate(array1, array2) {
  845. if (!some(array2))
  846. return array1;
  847. if (!some(array1))
  848. return array2;
  849. return __spreadArrays(array1, array2);
  850. }
  851. ts.concatenate = concatenate;
  852. function selectIndex(_, i) {
  853. return i;
  854. }
  855. function indicesOf(array) {
  856. return array.map(selectIndex);
  857. }
  858. ts.indicesOf = indicesOf;
  859. function deduplicateRelational(array, equalityComparer, comparer) {
  860. // Perform a stable sort of the array. This ensures the first entry in a list of
  861. // duplicates remains the first entry in the result.
  862. var indices = indicesOf(array);
  863. stableSortIndices(array, indices, comparer);
  864. var last = array[indices[0]];
  865. var deduplicated = [indices[0]];
  866. for (var i = 1; i < indices.length; i++) {
  867. var index = indices[i];
  868. var item = array[index];
  869. if (!equalityComparer(last, item)) {
  870. deduplicated.push(index);
  871. last = item;
  872. }
  873. }
  874. // restore original order
  875. deduplicated.sort();
  876. return deduplicated.map(function (i) { return array[i]; });
  877. }
  878. function deduplicateEquality(array, equalityComparer) {
  879. var result = [];
  880. for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
  881. var item = array_4[_i];
  882. pushIfUnique(result, item, equalityComparer);
  883. }
  884. return result;
  885. }
  886. /**
  887. * Deduplicates an unsorted array.
  888. * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
  889. * @param comparer An optional `Comparer` used to sort entries before comparison, though the
  890. * result will remain in the original order in `array`.
  891. */
  892. function deduplicate(array, equalityComparer, comparer) {
  893. return array.length === 0 ? [] :
  894. array.length === 1 ? array.slice() :
  895. comparer ? deduplicateRelational(array, equalityComparer, comparer) :
  896. deduplicateEquality(array, equalityComparer);
  897. }
  898. ts.deduplicate = deduplicate;
  899. /**
  900. * Deduplicates an array that has already been sorted.
  901. */
  902. function deduplicateSorted(array, comparer) {
  903. if (array.length === 0)
  904. return ts.emptyArray;
  905. var last = array[0];
  906. var deduplicated = [last];
  907. for (var i = 1; i < array.length; i++) {
  908. var next = array[i];
  909. switch (comparer(next, last)) {
  910. // equality comparison
  911. case true:
  912. // relational comparison
  913. // falls through
  914. case 0 /* EqualTo */:
  915. continue;
  916. case -1 /* LessThan */:
  917. // If `array` is sorted, `next` should **never** be less than `last`.
  918. return ts.Debug.fail("Array is unsorted.");
  919. }
  920. deduplicated.push(last = next);
  921. }
  922. return deduplicated;
  923. }
  924. function insertSorted(array, insert, compare) {
  925. if (array.length === 0) {
  926. array.push(insert);
  927. return;
  928. }
  929. var insertIndex = binarySearch(array, insert, identity, compare);
  930. if (insertIndex < 0) {
  931. array.splice(~insertIndex, 0, insert);
  932. }
  933. }
  934. ts.insertSorted = insertSorted;
  935. function sortAndDeduplicate(array, comparer, equalityComparer) {
  936. return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
  937. }
  938. ts.sortAndDeduplicate = sortAndDeduplicate;
  939. function arrayIsEqualTo(array1, array2, equalityComparer) {
  940. if (equalityComparer === void 0) { equalityComparer = equateValues; }
  941. if (!array1 || !array2) {
  942. return array1 === array2;
  943. }
  944. if (array1.length !== array2.length) {
  945. return false;
  946. }
  947. for (var i = 0; i < array1.length; i++) {
  948. if (!equalityComparer(array1[i], array2[i], i)) {
  949. return false;
  950. }
  951. }
  952. return true;
  953. }
  954. ts.arrayIsEqualTo = arrayIsEqualTo;
  955. function compact(array) {
  956. var result;
  957. if (array) {
  958. for (var i = 0; i < array.length; i++) {
  959. var v = array[i];
  960. if (result || !v) {
  961. if (!result) {
  962. result = array.slice(0, i);
  963. }
  964. if (v) {
  965. result.push(v);
  966. }
  967. }
  968. }
  969. }
  970. return result || array;
  971. }
  972. ts.compact = compact;
  973. /**
  974. * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
  975. * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
  976. * based on the provided comparer.
  977. */
  978. function relativeComplement(arrayA, arrayB, comparer) {
  979. if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
  980. return arrayB;
  981. var result = [];
  982. loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
  983. if (offsetB > 0) {
  984. // Ensure `arrayB` is properly sorted.
  985. ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
  986. }
  987. loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
  988. if (offsetA > startA) {
  989. // Ensure `arrayA` is properly sorted. We only need to perform this check if
  990. // `offsetA` has changed since we entered the loop.
  991. ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
  992. }
  993. switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
  994. case -1 /* LessThan */:
  995. // If B is less than A, B does not exist in arrayA. Add B to the result and
  996. // move to the next element in arrayB without changing the current position
  997. // in arrayA.
  998. result.push(arrayB[offsetB]);
  999. continue loopB;
  1000. case 0 /* EqualTo */:
  1001. // If B is equal to A, B exists in arrayA. Move to the next element in
  1002. // arrayB without adding B to the result or changing the current position
  1003. // in arrayA.
  1004. continue loopB;
  1005. case 1 /* GreaterThan */:
  1006. // If B is greater than A, we need to keep looking for B in arrayA. Move to
  1007. // the next element in arrayA and recheck.
  1008. continue loopA;
  1009. }
  1010. }
  1011. }
  1012. return result;
  1013. }
  1014. ts.relativeComplement = relativeComplement;
  1015. function sum(array, prop) {
  1016. var result = 0;
  1017. for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
  1018. var v = array_5[_i];
  1019. result += v[prop];
  1020. }
  1021. return result;
  1022. }
  1023. ts.sum = sum;
  1024. function append(to, value) {
  1025. if (value === undefined)
  1026. return to;
  1027. if (to === undefined)
  1028. return [value];
  1029. to.push(value);
  1030. return to;
  1031. }
  1032. ts.append = append;
  1033. /**
  1034. * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
  1035. * position offset from the end of the array.
  1036. */
  1037. function toOffset(array, offset) {
  1038. return offset < 0 ? array.length + offset : offset;
  1039. }
  1040. function addRange(to, from, start, end) {
  1041. if (from === undefined || from.length === 0)
  1042. return to;
  1043. if (to === undefined)
  1044. return from.slice(start, end);
  1045. start = start === undefined ? 0 : toOffset(from, start);
  1046. end = end === undefined ? from.length : toOffset(from, end);
  1047. for (var i = start; i < end && i < from.length; i++) {
  1048. if (from[i] !== undefined) {
  1049. to.push(from[i]);
  1050. }
  1051. }
  1052. return to;
  1053. }
  1054. ts.addRange = addRange;
  1055. /**
  1056. * @return Whether the value was added.
  1057. */
  1058. function pushIfUnique(array, toAdd, equalityComparer) {
  1059. if (contains(array, toAdd, equalityComparer)) {
  1060. return false;
  1061. }
  1062. else {
  1063. array.push(toAdd);
  1064. return true;
  1065. }
  1066. }
  1067. ts.pushIfUnique = pushIfUnique;
  1068. /**
  1069. * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
  1070. */
  1071. function appendIfUnique(array, toAdd, equalityComparer) {
  1072. if (array) {
  1073. pushIfUnique(array, toAdd, equalityComparer);
  1074. return array;
  1075. }
  1076. else {
  1077. return [toAdd];
  1078. }
  1079. }
  1080. ts.appendIfUnique = appendIfUnique;
  1081. function stableSortIndices(array, indices, comparer) {
  1082. // sort indices by value then position
  1083. indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
  1084. }
  1085. /**
  1086. * Returns a new sorted array.
  1087. */
  1088. function sort(array, comparer) {
  1089. return (array.length === 0 ? array : array.slice().sort(comparer));
  1090. }
  1091. ts.sort = sort;
  1092. function arrayIterator(array) {
  1093. var i = 0;
  1094. return { next: function () {
  1095. if (i === array.length) {
  1096. return { value: undefined, done: true };
  1097. }
  1098. else {
  1099. i++;
  1100. return { value: array[i - 1], done: false };
  1101. }
  1102. } };
  1103. }
  1104. ts.arrayIterator = arrayIterator;
  1105. function arrayReverseIterator(array) {
  1106. var i = array.length;
  1107. return {
  1108. next: function () {
  1109. if (i === 0) {
  1110. return { value: undefined, done: true };
  1111. }
  1112. else {
  1113. i--;
  1114. return { value: array[i], done: false };
  1115. }
  1116. }
  1117. };
  1118. }
  1119. ts.arrayReverseIterator = arrayReverseIterator;
  1120. /**
  1121. * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
  1122. */
  1123. function stableSort(array, comparer) {
  1124. var indices = indicesOf(array);
  1125. stableSortIndices(array, indices, comparer);
  1126. return indices.map(function (i) { return array[i]; });
  1127. }
  1128. ts.stableSort = stableSort;
  1129. function rangeEquals(array1, array2, pos, end) {
  1130. while (pos < end) {
  1131. if (array1[pos] !== array2[pos]) {
  1132. return false;
  1133. }
  1134. pos++;
  1135. }
  1136. return true;
  1137. }
  1138. ts.rangeEquals = rangeEquals;
  1139. /**
  1140. * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
  1141. * A negative offset indicates the element should be retrieved from the end of the array.
  1142. */
  1143. function elementAt(array, offset) {
  1144. if (array) {
  1145. offset = toOffset(array, offset);
  1146. if (offset < array.length) {
  1147. return array[offset];
  1148. }
  1149. }
  1150. return undefined;
  1151. }
  1152. ts.elementAt = elementAt;
  1153. /**
  1154. * Returns the first element of an array if non-empty, `undefined` otherwise.
  1155. */
  1156. function firstOrUndefined(array) {
  1157. return array.length === 0 ? undefined : array[0];
  1158. }
  1159. ts.firstOrUndefined = firstOrUndefined;
  1160. function first(array) {
  1161. ts.Debug.assert(array.length !== 0);
  1162. return array[0];
  1163. }
  1164. ts.first = first;
  1165. /**
  1166. * Returns the last element of an array if non-empty, `undefined` otherwise.
  1167. */
  1168. function lastOrUndefined(array) {
  1169. return array.length === 0 ? undefined : array[array.length - 1];
  1170. }
  1171. ts.lastOrUndefined = lastOrUndefined;
  1172. function last(array) {
  1173. ts.Debug.assert(array.length !== 0);
  1174. return array[array.length - 1];
  1175. }
  1176. ts.last = last;
  1177. /**
  1178. * Returns the only element of an array if it contains only one element, `undefined` otherwise.
  1179. */
  1180. function singleOrUndefined(array) {
  1181. return array && array.length === 1
  1182. ? array[0]
  1183. : undefined;
  1184. }
  1185. ts.singleOrUndefined = singleOrUndefined;
  1186. function singleOrMany(array) {
  1187. return array && array.length === 1
  1188. ? array[0]
  1189. : array;
  1190. }
  1191. ts.singleOrMany = singleOrMany;
  1192. function replaceElement(array, index, value) {
  1193. var result = array.slice(0);
  1194. result[index] = value;
  1195. return result;
  1196. }
  1197. ts.replaceElement = replaceElement;
  1198. /**
  1199. * Performs a binary search, finding the index at which `value` occurs in `array`.
  1200. * If no such index is found, returns the 2's-complement of first index at which
  1201. * `array[index]` exceeds `value`.
  1202. * @param array A sorted array whose first element must be no larger than number
  1203. * @param value The value to be searched for in the array.
  1204. * @param keySelector A callback used to select the search key from `value` and each element of
  1205. * `array`.
  1206. * @param keyComparer A callback used to compare two keys in a sorted array.
  1207. * @param offset An offset into `array` at which to start the search.
  1208. */
  1209. function binarySearch(array, value, keySelector, keyComparer, offset) {
  1210. return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
  1211. }
  1212. ts.binarySearch = binarySearch;
  1213. /**
  1214. * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
  1215. * If no such index is found, returns the 2's-complement of first index at which
  1216. * `array[index]` exceeds `key`.
  1217. * @param array A sorted array whose first element must be no larger than number
  1218. * @param key The key to be searched for in the array.
  1219. * @param keySelector A callback used to select the search key from each element of `array`.
  1220. * @param keyComparer A callback used to compare two keys in a sorted array.
  1221. * @param offset An offset into `array` at which to start the search.
  1222. */
  1223. function binarySearchKey(array, key, keySelector, keyComparer, offset) {
  1224. if (!some(array)) {
  1225. return -1;
  1226. }
  1227. var low = offset || 0;
  1228. var high = array.length - 1;
  1229. while (low <= high) {
  1230. var middle = low + ((high - low) >> 1);
  1231. var midKey = keySelector(array[middle]);
  1232. switch (keyComparer(midKey, key)) {
  1233. case -1 /* LessThan */:
  1234. low = middle + 1;
  1235. break;
  1236. case 0 /* EqualTo */:
  1237. return middle;
  1238. case 1 /* GreaterThan */:
  1239. high = middle - 1;
  1240. break;
  1241. }
  1242. }
  1243. return ~low;
  1244. }
  1245. ts.binarySearchKey = binarySearchKey;
  1246. function reduceLeft(array, f, initial, start, count) {
  1247. if (array && array.length > 0) {
  1248. var size = array.length;
  1249. if (size > 0) {
  1250. var pos = start === undefined || start < 0 ? 0 : start;
  1251. var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
  1252. var result = void 0;
  1253. if (arguments.length <= 2) {
  1254. result = array[pos];
  1255. pos++;
  1256. }
  1257. else {
  1258. result = initial;
  1259. }
  1260. while (pos <= end) {
  1261. result = f(result, array[pos], pos);
  1262. pos++;
  1263. }
  1264. return result;
  1265. }
  1266. }
  1267. return initial;
  1268. }
  1269. ts.reduceLeft = reduceLeft;
  1270. var hasOwnProperty = Object.prototype.hasOwnProperty;
  1271. /**
  1272. * Indicates whether a map-like contains an own property with the specified key.
  1273. *
  1274. * @param map A map-like.
  1275. * @param key A property key.
  1276. */
  1277. function hasProperty(map, key) {
  1278. return hasOwnProperty.call(map, key);
  1279. }
  1280. ts.hasProperty = hasProperty;
  1281. /**
  1282. * Gets the value of an owned property in a map-like.
  1283. *
  1284. * @param map A map-like.
  1285. * @param key A property key.
  1286. */
  1287. function getProperty(map, key) {
  1288. return hasOwnProperty.call(map, key) ? map[key] : undefined;
  1289. }
  1290. ts.getProperty = getProperty;
  1291. /**
  1292. * Gets the owned, enumerable property keys of a map-like.
  1293. */
  1294. function getOwnKeys(map) {
  1295. var keys = [];
  1296. for (var key in map) {
  1297. if (hasOwnProperty.call(map, key)) {
  1298. keys.push(key);
  1299. }
  1300. }
  1301. return keys;
  1302. }
  1303. ts.getOwnKeys = getOwnKeys;
  1304. function getAllKeys(obj) {
  1305. var result = [];
  1306. do {
  1307. var names = Object.getOwnPropertyNames(obj);
  1308. for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
  1309. var name = names_1[_i];
  1310. pushIfUnique(result, name);
  1311. }
  1312. } while (obj = Object.getPrototypeOf(obj));
  1313. return result;
  1314. }
  1315. ts.getAllKeys = getAllKeys;
  1316. function getOwnValues(sparseArray) {
  1317. var values = [];
  1318. for (var key in sparseArray) {
  1319. if (hasOwnProperty.call(sparseArray, key)) {
  1320. values.push(sparseArray[key]);
  1321. }
  1322. }
  1323. return values;
  1324. }
  1325. ts.getOwnValues = getOwnValues;
  1326. function arrayFrom(iterator, map) {
  1327. var result = [];
  1328. for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
  1329. result.push(map ? map(iterResult.value) : iterResult.value);
  1330. }
  1331. return result;
  1332. }
  1333. ts.arrayFrom = arrayFrom;
  1334. function assign(t) {
  1335. var args = [];
  1336. for (var _i = 1; _i < arguments.length; _i++) {
  1337. args[_i - 1] = arguments[_i];
  1338. }
  1339. for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
  1340. var arg = args_1[_a];
  1341. if (arg === undefined)
  1342. continue;
  1343. for (var p in arg) {
  1344. if (hasProperty(arg, p)) {
  1345. t[p] = arg[p];
  1346. }
  1347. }
  1348. }
  1349. return t;
  1350. }
  1351. ts.assign = assign;
  1352. /**
  1353. * Performs a shallow equality comparison of the contents of two map-likes.
  1354. *
  1355. * @param left A map-like whose properties should be compared.
  1356. * @param right A map-like whose properties should be compared.
  1357. */
  1358. function equalOwnProperties(left, right, equalityComparer) {
  1359. if (equalityComparer === void 0) { equalityComparer = equateValues; }
  1360. if (left === right)
  1361. return true;
  1362. if (!left || !right)
  1363. return false;
  1364. for (var key in left) {
  1365. if (hasOwnProperty.call(left, key)) {
  1366. if (!hasOwnProperty.call(right, key))
  1367. return false;
  1368. if (!equalityComparer(left[key], right[key]))
  1369. return false;
  1370. }
  1371. }
  1372. for (var key in right) {
  1373. if (hasOwnProperty.call(right, key)) {
  1374. if (!hasOwnProperty.call(left, key))
  1375. return false;
  1376. }
  1377. }
  1378. return true;
  1379. }
  1380. ts.equalOwnProperties = equalOwnProperties;
  1381. function arrayToMap(array, makeKey, makeValue) {
  1382. if (makeValue === void 0) { makeValue = identity; }
  1383. var result = createMap();
  1384. for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
  1385. var value = array_6[_i];
  1386. var key = makeKey(value);
  1387. if (key !== undefined)
  1388. result.set(key, makeValue(value));
  1389. }
  1390. return result;
  1391. }
  1392. ts.arrayToMap = arrayToMap;
  1393. function arrayToNumericMap(array, makeKey, makeValue) {
  1394. if (makeValue === void 0) { makeValue = identity; }
  1395. var result = [];
  1396. for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
  1397. var value = array_7[_i];
  1398. result[makeKey(value)] = makeValue(value);
  1399. }
  1400. return result;
  1401. }
  1402. ts.arrayToNumericMap = arrayToNumericMap;
  1403. function arrayToMultiMap(values, makeKey, makeValue) {
  1404. if (makeValue === void 0) { makeValue = identity; }
  1405. var result = createMultiMap();
  1406. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  1407. var value = values_1[_i];
  1408. result.add(makeKey(value), makeValue(value));
  1409. }
  1410. return result;
  1411. }
  1412. ts.arrayToMultiMap = arrayToMultiMap;
  1413. function group(values, getGroupId, resultSelector) {
  1414. if (resultSelector === void 0) { resultSelector = identity; }
  1415. return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
  1416. }
  1417. ts.group = group;
  1418. function clone(object) {
  1419. var result = {};
  1420. for (var id in object) {
  1421. if (hasOwnProperty.call(object, id)) {
  1422. result[id] = object[id];
  1423. }
  1424. }
  1425. return result;
  1426. }
  1427. ts.clone = clone;
  1428. /**
  1429. * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
  1430. *
  1431. * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
  1432. */
  1433. function extend(first, second) {
  1434. var result = {};
  1435. for (var id in second) {
  1436. if (hasOwnProperty.call(second, id)) {
  1437. result[id] = second[id];
  1438. }
  1439. }
  1440. for (var id in first) {
  1441. if (hasOwnProperty.call(first, id)) {
  1442. result[id] = first[id];
  1443. }
  1444. }
  1445. return result;
  1446. }
  1447. ts.extend = extend;
  1448. function copyProperties(first, second) {
  1449. for (var id in second) {
  1450. if (hasOwnProperty.call(second, id)) {
  1451. first[id] = second[id];
  1452. }
  1453. }
  1454. }
  1455. ts.copyProperties = copyProperties;
  1456. function maybeBind(obj, fn) {
  1457. return fn ? fn.bind(obj) : undefined;
  1458. }
  1459. ts.maybeBind = maybeBind;
  1460. function mapMap(map, f) {
  1461. var result = createMap();
  1462. map.forEach(function (t, key) { return result.set.apply(result, (f(t, key))); });
  1463. return result;
  1464. }
  1465. ts.mapMap = mapMap;
  1466. function createMultiMap() {
  1467. var map = createMap();
  1468. map.add = multiMapAdd;
  1469. map.remove = multiMapRemove;
  1470. return map;
  1471. }
  1472. ts.createMultiMap = createMultiMap;
  1473. function multiMapAdd(key, value) {
  1474. var values = this.get(key);
  1475. if (values) {
  1476. values.push(value);
  1477. }
  1478. else {
  1479. this.set(key, values = [value]);
  1480. }
  1481. return values;
  1482. }
  1483. function multiMapRemove(key, value) {
  1484. var values = this.get(key);
  1485. if (values) {
  1486. unorderedRemoveItem(values, value);
  1487. if (!values.length) {
  1488. this.delete(key);
  1489. }
  1490. }
  1491. }
  1492. /**
  1493. * Tests whether a value is an array.
  1494. */
  1495. function isArray(value) {
  1496. return Array.isArray ? Array.isArray(value) : value instanceof Array;
  1497. }
  1498. ts.isArray = isArray;
  1499. function toArray(value) {
  1500. return isArray(value) ? value : [value];
  1501. }
  1502. ts.toArray = toArray;
  1503. /**
  1504. * Tests whether a value is string
  1505. */
  1506. function isString(text) {
  1507. return typeof text === "string";
  1508. }
  1509. ts.isString = isString;
  1510. function isNumber(x) {
  1511. return typeof x === "number";
  1512. }
  1513. ts.isNumber = isNumber;
  1514. function tryCast(value, test) {
  1515. return value !== undefined && test(value) ? value : undefined;
  1516. }
  1517. ts.tryCast = tryCast;
  1518. function cast(value, test) {
  1519. if (value !== undefined && test(value))
  1520. return value;
  1521. return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
  1522. }
  1523. ts.cast = cast;
  1524. /** Does nothing. */
  1525. function noop(_) { }
  1526. ts.noop = noop;
  1527. /** Do nothing and return false */
  1528. function returnFalse() { return false; }
  1529. ts.returnFalse = returnFalse;
  1530. /** Do nothing and return true */
  1531. function returnTrue() { return true; }
  1532. ts.returnTrue = returnTrue;
  1533. /** Do nothing and return undefined */
  1534. function returnUndefined() { return undefined; }
  1535. ts.returnUndefined = returnUndefined;
  1536. /** Returns its argument. */
  1537. function identity(x) { return x; }
  1538. ts.identity = identity;
  1539. /** Returns lower case string */
  1540. function toLowerCase(x) { return x.toLowerCase(); }
  1541. ts.toLowerCase = toLowerCase;
  1542. // We convert the file names to lower case as key for file name on case insensitive file system
  1543. // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
  1544. // it to lower case, fileName with its lowercase form can exist along side it.
  1545. // Handle special characters and make those case sensitive instead
  1546. //
  1547. // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
  1548. // | 1. | i | 105 | Ascii i |
  1549. // | 2. | I | 73 | Ascii I |
  1550. // |-------- Special characters ------------------------------------------------------------------------|
  1551. // | 3. | \u0130 | 304 | Uppper case I with dot above |
  1552. // | 4. | i,\u0307 | 105,775 | i, followed by 775: Lower case of (3rd item) |
  1553. // | 5. | I,\u0307 | 73,775 | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
  1554. // | 6. | \u0131 | 305 | Lower case i without dot, upper case is I (2nd item) |
  1555. // | 7. | \u00DF | 223 | Lower case sharp s |
  1556. //
  1557. // Because item 3 is special where in its lowercase character has its own
  1558. // upper case form we cant convert its case.
  1559. // Rest special characters are either already in lower case format or
  1560. // they have corresponding upper case character so they dont need special handling
  1561. //
  1562. // But to avoid having to do string building for most common cases, also ignore
  1563. // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
  1564. var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  1565. /**
  1566. * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
  1567. * This function is used in places where we want to make file name as a key on these systems
  1568. * It is possible on mac to be able to refer to file name with I with dot on top as a fileName with its lower case form
  1569. * But on windows we cannot. Windows can have fileName with I with dot on top next to its lower case and they can not each be referred with the lowercase forms
  1570. * Technically we would want this function to be platform sepcific as well but
  1571. * our api has till now only taken caseSensitive as the only input and just for some characters we dont want to update API and ensure all customers use those api
  1572. * We could use upper case and we would still need to deal with the descripencies but
  1573. * we want to continue using lower case since in most cases filenames are lowercasewe and wont need any case changes and avoid having to store another string for the key
  1574. * So for this function purpose, we go ahead and assume character I with dot on top it as case sensitive since its very unlikely to use lower case form of that special character
  1575. */
  1576. function toFileNameLowerCase(x) {
  1577. return fileNameLowerCaseRegExp.test(x) ?
  1578. x.replace(fileNameLowerCaseRegExp, toLowerCase) :
  1579. x;
  1580. }
  1581. ts.toFileNameLowerCase = toFileNameLowerCase;
  1582. /** Throws an error because a function is not implemented. */
  1583. function notImplemented() {
  1584. throw new Error("Not implemented");
  1585. }
  1586. ts.notImplemented = notImplemented;
  1587. function memoize(callback) {
  1588. var value;
  1589. return function () {
  1590. if (callback) {
  1591. value = callback();
  1592. callback = undefined;
  1593. }
  1594. return value;
  1595. };
  1596. }
  1597. ts.memoize = memoize;
  1598. function compose(a, b, c, d, e) {
  1599. if (!!e) {
  1600. var args_2 = [];
  1601. for (var i = 0; i < arguments.length; i++) {
  1602. args_2[i] = arguments[i];
  1603. }
  1604. return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
  1605. }
  1606. else if (d) {
  1607. return function (t) { return d(c(b(a(t)))); };
  1608. }
  1609. else if (c) {
  1610. return function (t) { return c(b(a(t))); };
  1611. }
  1612. else if (b) {
  1613. return function (t) { return b(a(t)); };
  1614. }
  1615. else if (a) {
  1616. return function (t) { return a(t); };
  1617. }
  1618. else {
  1619. return function (t) { return t; };
  1620. }
  1621. }
  1622. ts.compose = compose;
  1623. var AssertionLevel;
  1624. (function (AssertionLevel) {
  1625. AssertionLevel[AssertionLevel["None"] = 0] = "None";
  1626. AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
  1627. AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
  1628. AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
  1629. })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
  1630. function equateValues(a, b) {
  1631. return a === b;
  1632. }
  1633. ts.equateValues = equateValues;
  1634. /**
  1635. * Compare the equality of two strings using a case-sensitive ordinal comparison.
  1636. *
  1637. * Case-sensitive comparisons compare both strings one code-point at a time using the integer
  1638. * value of each code-point after applying `toUpperCase` to each string. We always map both
  1639. * strings to their upper-case form as some unicode characters do not properly round-trip to
  1640. * lowercase (such as `ẞ` (German sharp capital s)).
  1641. */
  1642. function equateStringsCaseInsensitive(a, b) {
  1643. return a === b
  1644. || a !== undefined
  1645. && b !== undefined
  1646. && a.toUpperCase() === b.toUpperCase();
  1647. }
  1648. ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
  1649. /**
  1650. * Compare the equality of two strings using a case-sensitive ordinal comparison.
  1651. *
  1652. * Case-sensitive comparisons compare both strings one code-point at a time using the
  1653. * integer value of each code-point.
  1654. */
  1655. function equateStringsCaseSensitive(a, b) {
  1656. return equateValues(a, b);
  1657. }
  1658. ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
  1659. function compareComparableValues(a, b) {
  1660. return a === b ? 0 /* EqualTo */ :
  1661. a === undefined ? -1 /* LessThan */ :
  1662. b === undefined ? 1 /* GreaterThan */ :
  1663. a < b ? -1 /* LessThan */ :
  1664. 1 /* GreaterThan */;
  1665. }
  1666. /**
  1667. * Compare two numeric values for their order relative to each other.
  1668. * To compare strings, use any of the `compareStrings` functions.
  1669. */
  1670. function compareValues(a, b) {
  1671. return compareComparableValues(a, b);
  1672. }
  1673. ts.compareValues = compareValues;
  1674. /**
  1675. * Compare two TextSpans, first by `start`, then by `length`.
  1676. */
  1677. function compareTextSpans(a, b) {
  1678. return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length);
  1679. }
  1680. ts.compareTextSpans = compareTextSpans;
  1681. function min(a, b, compare) {
  1682. return compare(a, b) === -1 /* LessThan */ ? a : b;
  1683. }
  1684. ts.min = min;
  1685. /**
  1686. * Compare two strings using a case-insensitive ordinal comparison.
  1687. *
  1688. * Ordinal comparisons are based on the difference between the unicode code points of both
  1689. * strings. Characters with multiple unicode representations are considered unequal. Ordinal
  1690. * comparisons provide predictable ordering, but place "a" after "B".
  1691. *
  1692. * Case-insensitive comparisons compare both strings one code-point at a time using the integer
  1693. * value of each code-point after applying `toUpperCase` to each string. We always map both
  1694. * strings to their upper-case form as some unicode characters do not properly round-trip to
  1695. * lowercase (such as `ẞ` (German sharp capital s)).
  1696. */
  1697. function compareStringsCaseInsensitive(a, b) {
  1698. if (a === b)
  1699. return 0 /* EqualTo */;
  1700. if (a === undefined)
  1701. return -1 /* LessThan */;
  1702. if (b === undefined)
  1703. return 1 /* GreaterThan */;
  1704. a = a.toUpperCase();
  1705. b = b.toUpperCase();
  1706. return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
  1707. }
  1708. ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
  1709. /**
  1710. * Compare two strings using a case-sensitive ordinal comparison.
  1711. *
  1712. * Ordinal comparisons are based on the difference between the unicode code points of both
  1713. * strings. Characters with multiple unicode representations are considered unequal. Ordinal
  1714. * comparisons provide predictable ordering, but place "a" after "B".
  1715. *
  1716. * Case-sensitive comparisons compare both strings one code-point at a time using the integer
  1717. * value of each code-point.
  1718. */
  1719. function compareStringsCaseSensitive(a, b) {
  1720. return compareComparableValues(a, b);
  1721. }
  1722. ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
  1723. function getStringComparer(ignoreCase) {
  1724. return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
  1725. }
  1726. ts.getStringComparer = getStringComparer;
  1727. /**
  1728. * Creates a string comparer for use with string collation in the UI.
  1729. */
  1730. var createUIStringComparer = (function () {
  1731. var defaultComparer;
  1732. var enUSComparer;
  1733. var stringComparerFactory = getStringComparerFactory();
  1734. return createStringComparer;
  1735. function compareWithCallback(a, b, comparer) {
  1736. if (a === b)
  1737. return 0 /* EqualTo */;
  1738. if (a === undefined)
  1739. return -1 /* LessThan */;
  1740. if (b === undefined)
  1741. return 1 /* GreaterThan */;
  1742. var value = comparer(a, b);
  1743. return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
  1744. }
  1745. function createIntlCollatorStringComparer(locale) {
  1746. // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
  1747. // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
  1748. var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
  1749. return function (a, b) { return compareWithCallback(a, b, comparer); };
  1750. }
  1751. function createLocaleCompareStringComparer(locale) {
  1752. // if the locale is not the default locale (`undefined`), use the fallback comparer.
  1753. if (locale !== undefined)
  1754. return createFallbackStringComparer();
  1755. return function (a, b) { return compareWithCallback(a, b, compareStrings); };
  1756. function compareStrings(a, b) {
  1757. return a.localeCompare(b);
  1758. }
  1759. }
  1760. function createFallbackStringComparer() {
  1761. // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
  1762. // We first sort case insensitively. So "Aaa" will come before "baa".
  1763. // Then we sort case sensitively, so "aaa" will come before "Aaa".
  1764. //
  1765. // For case insensitive comparisons we always map both strings to their
  1766. // upper-case form as some unicode characters do not properly round-trip to
  1767. // lowercase (such as `ẞ` (German sharp capital s)).
  1768. return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
  1769. function compareDictionaryOrder(a, b) {
  1770. return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
  1771. }
  1772. function compareStrings(a, b) {
  1773. return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
  1774. }
  1775. }
  1776. function getStringComparerFactory() {
  1777. // If the host supports Intl, we use it for comparisons using the default locale.
  1778. if (typeof Intl === "object" && typeof Intl.Collator === "function") {
  1779. return createIntlCollatorStringComparer;
  1780. }
  1781. // If the host does not support Intl, we fall back to localeCompare.
  1782. // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
  1783. if (typeof String.prototype.localeCompare === "function" &&
  1784. typeof String.prototype.toLocaleUpperCase === "function" &&
  1785. "a".localeCompare("B") < 0) {
  1786. return createLocaleCompareStringComparer;
  1787. }
  1788. // Otherwise, fall back to ordinal comparison:
  1789. return createFallbackStringComparer;
  1790. }
  1791. function createStringComparer(locale) {
  1792. // Hold onto common string comparers. This avoids constantly reallocating comparers during
  1793. // tests.
  1794. if (locale === undefined) {
  1795. return defaultComparer || (defaultComparer = stringComparerFactory(locale));
  1796. }
  1797. else if (locale === "en-US") {
  1798. return enUSComparer || (enUSComparer = stringComparerFactory(locale));
  1799. }
  1800. else {
  1801. return stringComparerFactory(locale);
  1802. }
  1803. }
  1804. })();
  1805. var uiComparerCaseSensitive;
  1806. var uiLocale;
  1807. function getUILocale() {
  1808. return uiLocale;
  1809. }
  1810. ts.getUILocale = getUILocale;
  1811. function setUILocale(value) {
  1812. if (uiLocale !== value) {
  1813. uiLocale = value;
  1814. uiComparerCaseSensitive = undefined;
  1815. }
  1816. }
  1817. ts.setUILocale = setUILocale;
  1818. /**
  1819. * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
  1820. *
  1821. * Ordering is not predictable between different host locales, but is best for displaying
  1822. * ordered data for UI presentation. Characters with multiple unicode representations may
  1823. * be considered equal.
  1824. *
  1825. * Case-sensitive comparisons compare strings that differ in base characters, or
  1826. * accents/diacritic marks, or case as unequal.
  1827. */
  1828. function compareStringsCaseSensitiveUI(a, b) {
  1829. var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
  1830. return comparer(a, b);
  1831. }
  1832. ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
  1833. function compareProperties(a, b, key, comparer) {
  1834. return a === b ? 0 /* EqualTo */ :
  1835. a === undefined ? -1 /* LessThan */ :
  1836. b === undefined ? 1 /* GreaterThan */ :
  1837. comparer(a[key], b[key]);
  1838. }
  1839. ts.compareProperties = compareProperties;
  1840. /** True is greater than false. */
  1841. function compareBooleans(a, b) {
  1842. return compareValues(a ? 1 : 0, b ? 1 : 0);
  1843. }
  1844. ts.compareBooleans = compareBooleans;
  1845. /**
  1846. * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
  1847. * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
  1848. *
  1849. * If there is a candidate that's the same except for case, return that.
  1850. * If there is a candidate that's within one edit of the name, return that.
  1851. * Otherwise, return the candidate with the smallest Levenshtein distance,
  1852. * except for candidates:
  1853. * * With no name
  1854. * * Whose length differs from the target name by more than 0.34 of the length of the name.
  1855. * * Whose levenshtein distance is more than 0.4 of the length of the name
  1856. * (0.4 allows 1 substitution/transposition for every 5 characters,
  1857. * and 1 insertion/deletion at 3 characters)
  1858. */
  1859. function getSpellingSuggestion(name, candidates, getName) {
  1860. var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
  1861. var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
  1862. var bestCandidate;
  1863. var justCheckExactMatches = false;
  1864. var nameLowerCase = name.toLowerCase();
  1865. for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
  1866. var candidate = candidates_1[_i];
  1867. var candidateName = getName(candidate);
  1868. if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
  1869. var candidateNameLowerCase = candidateName.toLowerCase();
  1870. if (candidateNameLowerCase === nameLowerCase) {
  1871. if (candidateName === name) {
  1872. continue;
  1873. }
  1874. return candidate;
  1875. }
  1876. if (justCheckExactMatches) {
  1877. continue;
  1878. }
  1879. if (candidateName.length < 3) {
  1880. // Don't bother, user would have noticed a 2-character name having an extra character
  1881. continue;
  1882. }
  1883. // Only care about a result better than the best so far.
  1884. var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
  1885. if (distance === undefined) {
  1886. continue;
  1887. }
  1888. if (distance < 3) {
  1889. justCheckExactMatches = true;
  1890. bestCandidate = candidate;
  1891. }
  1892. else {
  1893. ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
  1894. bestDistance = distance;
  1895. bestCandidate = candidate;
  1896. }
  1897. }
  1898. }
  1899. return bestCandidate;
  1900. }
  1901. ts.getSpellingSuggestion = getSpellingSuggestion;
  1902. function levenshteinWithMax(s1, s2, max) {
  1903. var previous = new Array(s2.length + 1);
  1904. var current = new Array(s2.length + 1);
  1905. /** Represents any value > max. We don't care about the particular value. */
  1906. var big = max + 1;
  1907. for (var i = 0; i <= s2.length; i++) {
  1908. previous[i] = i;
  1909. }
  1910. for (var i = 1; i <= s1.length; i++) {
  1911. var c1 = s1.charCodeAt(i - 1);
  1912. var minJ = i > max ? i - max : 1;
  1913. var maxJ = s2.length > max + i ? max + i : s2.length;
  1914. current[0] = i;
  1915. /** Smallest value of the matrix in the ith column. */
  1916. var colMin = i;
  1917. for (var j = 1; j < minJ; j++) {
  1918. current[j] = big;
  1919. }
  1920. for (var j = minJ; j <= maxJ; j++) {
  1921. var dist = c1 === s2.charCodeAt(j - 1)
  1922. ? previous[j - 1]
  1923. : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
  1924. current[j] = dist;
  1925. colMin = Math.min(colMin, dist);
  1926. }
  1927. for (var j = maxJ + 1; j <= s2.length; j++) {
  1928. current[j] = big;
  1929. }
  1930. if (colMin > max) {
  1931. // Give up -- everything in this column is > max and it can't get better in future columns.
  1932. return undefined;
  1933. }
  1934. var temp = previous;
  1935. previous = current;
  1936. current = temp;
  1937. }
  1938. var res = previous[s2.length];
  1939. return res > max ? undefined : res;
  1940. }
  1941. function endsWith(str, suffix) {
  1942. var expectedPos = str.length - suffix.length;
  1943. return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
  1944. }
  1945. ts.endsWith = endsWith;
  1946. function removeSuffix(str, suffix) {
  1947. return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
  1948. }
  1949. ts.removeSuffix = removeSuffix;
  1950. function tryRemoveSuffix(str, suffix) {
  1951. return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
  1952. }
  1953. ts.tryRemoveSuffix = tryRemoveSuffix;
  1954. function stringContains(str, substring) {
  1955. return str.indexOf(substring) !== -1;
  1956. }
  1957. ts.stringContains = stringContains;
  1958. /**
  1959. * Takes a string like "jquery-min.4.2.3" and returns "jquery"
  1960. */
  1961. function removeMinAndVersionNumbers(fileName) {
  1962. // Match a "." or "-" followed by a version number or 'min' at the end of the name
  1963. var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
  1964. // The "min" or version may both be present, in either order, so try applying the above twice.
  1965. return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
  1966. }
  1967. ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
  1968. /** Remove an item from an array, moving everything to its right one space left. */
  1969. function orderedRemoveItem(array, item) {
  1970. for (var i = 0; i < array.length; i++) {
  1971. if (array[i] === item) {
  1972. orderedRemoveItemAt(array, i);
  1973. return true;
  1974. }
  1975. }
  1976. return false;
  1977. }
  1978. ts.orderedRemoveItem = orderedRemoveItem;
  1979. /** Remove an item by index from an array, moving everything to its right one space left. */
  1980. function orderedRemoveItemAt(array, index) {
  1981. // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
  1982. for (var i = index; i < array.length - 1; i++) {
  1983. array[i] = array[i + 1];
  1984. }
  1985. array.pop();
  1986. }
  1987. ts.orderedRemoveItemAt = orderedRemoveItemAt;
  1988. function unorderedRemoveItemAt(array, index) {
  1989. // Fill in the "hole" left at `index`.
  1990. array[index] = array[array.length - 1];
  1991. array.pop();
  1992. }
  1993. ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
  1994. /** Remove the *first* occurrence of `item` from the array. */
  1995. function unorderedRemoveItem(array, item) {
  1996. return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
  1997. }
  1998. ts.unorderedRemoveItem = unorderedRemoveItem;
  1999. /** Remove the *first* element satisfying `predicate`. */
  2000. function unorderedRemoveFirstItemWhere(array, predicate) {
  2001. for (var i = 0; i < array.length; i++) {
  2002. if (predicate(array[i])) {
  2003. unorderedRemoveItemAt(array, i);
  2004. return true;
  2005. }
  2006. }
  2007. return false;
  2008. }
  2009. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  2010. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  2011. }
  2012. ts.createGetCanonicalFileName = createGetCanonicalFileName;
  2013. function patternText(_a) {
  2014. var prefix = _a.prefix, suffix = _a.suffix;
  2015. return prefix + "*" + suffix;
  2016. }
  2017. ts.patternText = patternText;
  2018. /**
  2019. * Given that candidate matches pattern, returns the text matching the '*'.
  2020. * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
  2021. */
  2022. function matchedText(pattern, candidate) {
  2023. ts.Debug.assert(isPatternMatch(pattern, candidate));
  2024. return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
  2025. }
  2026. ts.matchedText = matchedText;
  2027. /** Return the object corresponding to the best pattern to match `candidate`. */
  2028. function findBestPatternMatch(values, getPattern, candidate) {
  2029. var matchedValue;
  2030. // use length of prefix as betterness criteria
  2031. var longestMatchPrefixLength = -1;
  2032. for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
  2033. var v = values_2[_i];
  2034. var pattern = getPattern(v);
  2035. if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
  2036. longestMatchPrefixLength = pattern.prefix.length;
  2037. matchedValue = v;
  2038. }
  2039. }
  2040. return matchedValue;
  2041. }
  2042. ts.findBestPatternMatch = findBestPatternMatch;
  2043. function startsWith(str, prefix) {
  2044. return str.lastIndexOf(prefix, 0) === 0;
  2045. }
  2046. ts.startsWith = startsWith;
  2047. function removePrefix(str, prefix) {
  2048. return startsWith(str, prefix) ? str.substr(prefix.length) : str;
  2049. }
  2050. ts.removePrefix = removePrefix;
  2051. function tryRemovePrefix(str, prefix, getCanonicalFileName) {
  2052. if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
  2053. return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
  2054. }
  2055. ts.tryRemovePrefix = tryRemovePrefix;
  2056. function isPatternMatch(_a, candidate) {
  2057. var prefix = _a.prefix, suffix = _a.suffix;
  2058. return candidate.length >= prefix.length + suffix.length &&
  2059. startsWith(candidate, prefix) &&
  2060. endsWith(candidate, suffix);
  2061. }
  2062. function and(f, g) {
  2063. return function (arg) { return f(arg) && g(arg); };
  2064. }
  2065. ts.and = and;
  2066. function or() {
  2067. var fs = [];
  2068. for (var _i = 0; _i < arguments.length; _i++) {
  2069. fs[_i] = arguments[_i];
  2070. }
  2071. return function () {
  2072. var args = [];
  2073. for (var _i = 0; _i < arguments.length; _i++) {
  2074. args[_i] = arguments[_i];
  2075. }
  2076. for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
  2077. var f = fs_1[_a];
  2078. if (f.apply(void 0, args)) {
  2079. return true;
  2080. }
  2081. }
  2082. return false;
  2083. };
  2084. }
  2085. ts.or = or;
  2086. function not(fn) {
  2087. return function () {
  2088. var args = [];
  2089. for (var _i = 0; _i < arguments.length; _i++) {
  2090. args[_i] = arguments[_i];
  2091. }
  2092. return !fn.apply(void 0, args);
  2093. };
  2094. }
  2095. ts.not = not;
  2096. function assertType(_) { }
  2097. ts.assertType = assertType;
  2098. function singleElementArray(t) {
  2099. return t === undefined ? undefined : [t];
  2100. }
  2101. ts.singleElementArray = singleElementArray;
  2102. function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
  2103. unchanged = unchanged || noop;
  2104. var newIndex = 0;
  2105. var oldIndex = 0;
  2106. var newLen = newItems.length;
  2107. var oldLen = oldItems.length;
  2108. while (newIndex < newLen && oldIndex < oldLen) {
  2109. var newItem = newItems[newIndex];
  2110. var oldItem = oldItems[oldIndex];
  2111. var compareResult = comparer(newItem, oldItem);
  2112. if (compareResult === -1 /* LessThan */) {
  2113. inserted(newItem);
  2114. newIndex++;
  2115. }
  2116. else if (compareResult === 1 /* GreaterThan */) {
  2117. deleted(oldItem);
  2118. oldIndex++;
  2119. }
  2120. else {
  2121. unchanged(oldItem, newItem);
  2122. newIndex++;
  2123. oldIndex++;
  2124. }
  2125. }
  2126. while (newIndex < newLen) {
  2127. inserted(newItems[newIndex++]);
  2128. }
  2129. while (oldIndex < oldLen) {
  2130. deleted(oldItems[oldIndex++]);
  2131. }
  2132. }
  2133. ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
  2134. function fill(length, cb) {
  2135. var result = Array(length);
  2136. for (var i = 0; i < length; i++) {
  2137. result[i] = cb(i);
  2138. }
  2139. return result;
  2140. }
  2141. ts.fill = fill;
  2142. function cartesianProduct(arrays) {
  2143. var result = [];
  2144. cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
  2145. return result;
  2146. }
  2147. ts.cartesianProduct = cartesianProduct;
  2148. function cartesianProductWorker(arrays, result, outer, index) {
  2149. for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
  2150. var element = _a[_i];
  2151. var inner = void 0;
  2152. if (outer) {
  2153. inner = outer.slice();
  2154. inner.push(element);
  2155. }
  2156. else {
  2157. inner = [element];
  2158. }
  2159. if (index === arrays.length - 1) {
  2160. result.push(inner);
  2161. }
  2162. else {
  2163. cartesianProductWorker(arrays, result, inner, index + 1);
  2164. }
  2165. }
  2166. }
  2167. })(ts || (ts = {}));
  2168. /* @internal */
  2169. var ts;
  2170. (function (ts) {
  2171. var Debug;
  2172. (function (Debug) {
  2173. /* eslint-disable prefer-const */
  2174. Debug.currentAssertionLevel = 0 /* None */;
  2175. Debug.isDebugging = false;
  2176. /* eslint-enable prefer-const */
  2177. function shouldAssert(level) {
  2178. return Debug.currentAssertionLevel >= level;
  2179. }
  2180. Debug.shouldAssert = shouldAssert;
  2181. function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
  2182. if (!expression) {
  2183. if (verboseDebugInfo) {
  2184. message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
  2185. }
  2186. fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
  2187. }
  2188. }
  2189. Debug.assert = assert;
  2190. function assertEqual(a, b, msg, msg2) {
  2191. if (a !== b) {
  2192. var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
  2193. fail("Expected " + a + " === " + b + ". " + message);
  2194. }
  2195. }
  2196. Debug.assertEqual = assertEqual;
  2197. function assertLessThan(a, b, msg) {
  2198. if (a >= b) {
  2199. fail("Expected " + a + " < " + b + ". " + (msg || ""));
  2200. }
  2201. }
  2202. Debug.assertLessThan = assertLessThan;
  2203. function assertLessThanOrEqual(a, b) {
  2204. if (a > b) {
  2205. fail("Expected " + a + " <= " + b);
  2206. }
  2207. }
  2208. Debug.assertLessThanOrEqual = assertLessThanOrEqual;
  2209. function assertGreaterThanOrEqual(a, b) {
  2210. if (a < b) {
  2211. fail("Expected " + a + " >= " + b);
  2212. }
  2213. }
  2214. Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
  2215. function fail(message, stackCrawlMark) {
  2216. debugger;
  2217. var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
  2218. if (Error.captureStackTrace) {
  2219. Error.captureStackTrace(e, stackCrawlMark || fail);
  2220. }
  2221. throw e;
  2222. }
  2223. Debug.fail = fail;
  2224. function assertDefined(value, message) {
  2225. // eslint-disable-next-line no-null/no-null
  2226. if (value === undefined || value === null)
  2227. return fail(message);
  2228. return value;
  2229. }
  2230. Debug.assertDefined = assertDefined;
  2231. function assertEachDefined(value, message) {
  2232. for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
  2233. var v = value_1[_i];
  2234. assertDefined(v, message);
  2235. }
  2236. return value;
  2237. }
  2238. Debug.assertEachDefined = assertEachDefined;
  2239. function assertNever(member, message, stackCrawlMark) {
  2240. if (message === void 0) { message = "Illegal value:"; }
  2241. var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
  2242. return fail(message + " " + detail, stackCrawlMark || assertNever);
  2243. }
  2244. Debug.assertNever = assertNever;
  2245. function getFunctionName(func) {
  2246. if (typeof func !== "function") {
  2247. return "";
  2248. }
  2249. else if (func.hasOwnProperty("name")) {
  2250. return func.name;
  2251. }
  2252. else {
  2253. var text = Function.prototype.toString.call(func);
  2254. var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
  2255. return match ? match[1] : "";
  2256. }
  2257. }
  2258. Debug.getFunctionName = getFunctionName;
  2259. function formatSymbol(symbol) {
  2260. return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
  2261. }
  2262. Debug.formatSymbol = formatSymbol;
  2263. /**
  2264. * Formats an enum value as a string for debugging and debug assertions.
  2265. */
  2266. function formatEnum(value, enumObject, isFlags) {
  2267. if (value === void 0) { value = 0; }
  2268. var members = getEnumMembers(enumObject);
  2269. if (value === 0) {
  2270. return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
  2271. }
  2272. if (isFlags) {
  2273. var result = "";
  2274. var remainingFlags = value;
  2275. for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
  2276. var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
  2277. if (enumValue > value) {
  2278. break;
  2279. }
  2280. if (enumValue !== 0 && enumValue & value) {
  2281. result = "" + result + (result ? "|" : "") + enumName;
  2282. remainingFlags &= ~enumValue;
  2283. }
  2284. }
  2285. if (remainingFlags === 0) {
  2286. return result;
  2287. }
  2288. }
  2289. else {
  2290. for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
  2291. var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
  2292. if (enumValue === value) {
  2293. return enumName;
  2294. }
  2295. }
  2296. }
  2297. return value.toString();
  2298. }
  2299. Debug.formatEnum = formatEnum;
  2300. function getEnumMembers(enumObject) {
  2301. var result = [];
  2302. for (var name in enumObject) {
  2303. var value = enumObject[name];
  2304. if (typeof value === "number") {
  2305. result.push([value, name]);
  2306. }
  2307. }
  2308. return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
  2309. }
  2310. function formatSyntaxKind(kind) {
  2311. return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
  2312. }
  2313. Debug.formatSyntaxKind = formatSyntaxKind;
  2314. function formatNodeFlags(flags) {
  2315. return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
  2316. }
  2317. Debug.formatNodeFlags = formatNodeFlags;
  2318. function formatModifierFlags(flags) {
  2319. return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
  2320. }
  2321. Debug.formatModifierFlags = formatModifierFlags;
  2322. function formatTransformFlags(flags) {
  2323. return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
  2324. }
  2325. Debug.formatTransformFlags = formatTransformFlags;
  2326. function formatEmitFlags(flags) {
  2327. return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
  2328. }
  2329. Debug.formatEmitFlags = formatEmitFlags;
  2330. function formatSymbolFlags(flags) {
  2331. return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
  2332. }
  2333. Debug.formatSymbolFlags = formatSymbolFlags;
  2334. function formatTypeFlags(flags) {
  2335. return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
  2336. }
  2337. Debug.formatTypeFlags = formatTypeFlags;
  2338. function formatObjectFlags(flags) {
  2339. return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
  2340. }
  2341. Debug.formatObjectFlags = formatObjectFlags;
  2342. function failBadSyntaxKind(node, message) {
  2343. return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind);
  2344. }
  2345. Debug.failBadSyntaxKind = failBadSyntaxKind;
  2346. Debug.assertEachNode = shouldAssert(1 /* Normal */)
  2347. ? function (nodes, test, message) { return assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, Debug.assertEachNode); }
  2348. : ts.noop;
  2349. Debug.assertNode = shouldAssert(1 /* Normal */)
  2350. ? function (node, test, message) { return assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, Debug.assertNode); }
  2351. : ts.noop;
  2352. Debug.assertNotNode = shouldAssert(1 /* Normal */)
  2353. ? function (node, test, message) { return assert(test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, Debug.assertNode); }
  2354. : ts.noop;
  2355. Debug.assertOptionalNode = shouldAssert(1 /* Normal */)
  2356. ? function (node, test, message) { return assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, Debug.assertOptionalNode); }
  2357. : ts.noop;
  2358. Debug.assertOptionalToken = shouldAssert(1 /* Normal */)
  2359. ? function (node, kind, message) { return assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); }
  2360. : ts.noop;
  2361. Debug.assertMissingNode = shouldAssert(1 /* Normal */)
  2362. ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); }
  2363. : ts.noop;
  2364. var isDebugInfoEnabled = false;
  2365. var extendedDebugModule;
  2366. function extendedDebug() {
  2367. enableDebugInfo();
  2368. if (!extendedDebugModule) {
  2369. throw new Error("Debugging helpers could not be loaded.");
  2370. }
  2371. return extendedDebugModule;
  2372. }
  2373. function printControlFlowGraph(flowNode) {
  2374. return console.log(formatControlFlowGraph(flowNode));
  2375. }
  2376. Debug.printControlFlowGraph = printControlFlowGraph;
  2377. function formatControlFlowGraph(flowNode) {
  2378. return extendedDebug().formatControlFlowGraph(flowNode);
  2379. }
  2380. Debug.formatControlFlowGraph = formatControlFlowGraph;
  2381. function attachFlowNodeDebugInfo(flowNode) {
  2382. if (isDebugInfoEnabled) {
  2383. if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
  2384. Object.defineProperties(flowNode, {
  2385. __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
  2386. __debugToString: { value: function () { return formatControlFlowGraph(this); } }
  2387. });
  2388. }
  2389. }
  2390. }
  2391. Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
  2392. /**
  2393. * Injects debug information into frequently used types.
  2394. */
  2395. function enableDebugInfo() {
  2396. if (isDebugInfoEnabled)
  2397. return;
  2398. // Add additional properties in debug mode to assist with debugging.
  2399. Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
  2400. __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
  2401. });
  2402. Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
  2403. __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
  2404. __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
  2405. __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
  2406. });
  2407. var nodeConstructors = [
  2408. ts.objectAllocator.getNodeConstructor(),
  2409. ts.objectAllocator.getIdentifierConstructor(),
  2410. ts.objectAllocator.getTokenConstructor(),
  2411. ts.objectAllocator.getSourceFileConstructor()
  2412. ];
  2413. for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
  2414. var ctor = nodeConstructors_1[_i];
  2415. if (!ctor.prototype.hasOwnProperty("__debugKind")) {
  2416. Object.defineProperties(ctor.prototype, {
  2417. __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
  2418. __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
  2419. __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
  2420. __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
  2421. __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
  2422. __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
  2423. __debugGetText: {
  2424. value: function (includeTrivia) {
  2425. if (ts.nodeIsSynthesized(this))
  2426. return "";
  2427. var parseNode = ts.getParseTreeNode(this);
  2428. var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
  2429. return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
  2430. }
  2431. }
  2432. });
  2433. }
  2434. }
  2435. // attempt to load extended debugging information
  2436. try {
  2437. if (ts.sys && ts.sys.require) {
  2438. var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
  2439. // MONACOCHANGE
  2440. var result = undefined;
  2441. // END MONACOCHANGE
  2442. if (!result.error) {
  2443. result.module.init(ts);
  2444. extendedDebugModule = result.module;
  2445. }
  2446. }
  2447. }
  2448. catch (_a) {
  2449. // do nothing
  2450. }
  2451. isDebugInfoEnabled = true;
  2452. }
  2453. Debug.enableDebugInfo = enableDebugInfo;
  2454. })(Debug = ts.Debug || (ts.Debug = {}));
  2455. })(ts || (ts = {}));
  2456. /*@internal*/
  2457. var ts;
  2458. (function (ts) {
  2459. /** Gets a timestamp with (at least) ms resolution */
  2460. ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
  2461. })(ts || (ts = {}));
  2462. /*@internal*/
  2463. /** Performance measurements for the compiler. */
  2464. var ts;
  2465. (function (ts) {
  2466. var performance;
  2467. (function (performance) {
  2468. // NOTE: cannot use ts.noop as core.ts loads after this
  2469. var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
  2470. var enabled = false;
  2471. var profilerStart = 0;
  2472. var counts;
  2473. var marks;
  2474. var measures;
  2475. function createTimerIf(condition, measureName, startMarkName, endMarkName) {
  2476. return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
  2477. }
  2478. performance.createTimerIf = createTimerIf;
  2479. function createTimer(measureName, startMarkName, endMarkName) {
  2480. var enterCount = 0;
  2481. return {
  2482. enter: enter,
  2483. exit: exit
  2484. };
  2485. function enter() {
  2486. if (++enterCount === 1) {
  2487. mark(startMarkName);
  2488. }
  2489. }
  2490. function exit() {
  2491. if (--enterCount === 0) {
  2492. mark(endMarkName);
  2493. measure(measureName, startMarkName, endMarkName);
  2494. }
  2495. else if (enterCount < 0) {
  2496. ts.Debug.fail("enter/exit count does not match.");
  2497. }
  2498. }
  2499. }
  2500. performance.createTimer = createTimer;
  2501. performance.nullTimer = { enter: ts.noop, exit: ts.noop };
  2502. /**
  2503. * Marks a performance event.
  2504. *
  2505. * @param markName The name of the mark.
  2506. */
  2507. function mark(markName) {
  2508. if (enabled) {
  2509. marks.set(markName, ts.timestamp());
  2510. counts.set(markName, (counts.get(markName) || 0) + 1);
  2511. profilerEvent(markName);
  2512. }
  2513. }
  2514. performance.mark = mark;
  2515. /**
  2516. * Adds a performance measurement with the specified name.
  2517. *
  2518. * @param measureName The name of the performance measurement.
  2519. * @param startMarkName The name of the starting mark. If not supplied, the point at which the
  2520. * profiler was enabled is used.
  2521. * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
  2522. * used.
  2523. */
  2524. function measure(measureName, startMarkName, endMarkName) {
  2525. if (enabled) {
  2526. var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
  2527. var start = startMarkName && marks.get(startMarkName) || profilerStart;
  2528. measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
  2529. }
  2530. }
  2531. performance.measure = measure;
  2532. /**
  2533. * Gets the number of times a marker was encountered.
  2534. *
  2535. * @param markName The name of the mark.
  2536. */
  2537. function getCount(markName) {
  2538. return counts && counts.get(markName) || 0;
  2539. }
  2540. performance.getCount = getCount;
  2541. /**
  2542. * Gets the total duration of all measurements with the supplied name.
  2543. *
  2544. * @param measureName The name of the measure whose durations should be accumulated.
  2545. */
  2546. function getDuration(measureName) {
  2547. return measures && measures.get(measureName) || 0;
  2548. }
  2549. performance.getDuration = getDuration;
  2550. /**
  2551. * Iterate over each measure, performing some action
  2552. *
  2553. * @param cb The action to perform for each measure
  2554. */
  2555. function forEachMeasure(cb) {
  2556. measures.forEach(function (measure, key) {
  2557. cb(key, measure);
  2558. });
  2559. }
  2560. performance.forEachMeasure = forEachMeasure;
  2561. /** Enables (and resets) performance measurements for the compiler. */
  2562. function enable() {
  2563. counts = ts.createMap();
  2564. marks = ts.createMap();
  2565. measures = ts.createMap();
  2566. enabled = true;
  2567. profilerStart = ts.timestamp();
  2568. }
  2569. performance.enable = enable;
  2570. /** Disables performance measurements for the compiler. */
  2571. function disable() {
  2572. enabled = false;
  2573. }
  2574. performance.disable = disable;
  2575. })(performance = ts.performance || (ts.performance = {}));
  2576. })(ts || (ts = {}));
  2577. /* @internal */
  2578. var ts;
  2579. (function (ts) {
  2580. var nullLogger = {
  2581. logEvent: ts.noop,
  2582. logErrEvent: ts.noop,
  2583. logPerfEvent: ts.noop,
  2584. logInfoEvent: ts.noop,
  2585. logStartCommand: ts.noop,
  2586. logStopCommand: ts.noop,
  2587. logStartUpdateProgram: ts.noop,
  2588. logStopUpdateProgram: ts.noop,
  2589. logStartUpdateGraph: ts.noop,
  2590. logStopUpdateGraph: ts.noop,
  2591. logStartResolveModule: ts.noop,
  2592. logStopResolveModule: ts.noop,
  2593. logStartParseSourceFile: ts.noop,
  2594. logStopParseSourceFile: ts.noop,
  2595. logStartReadFile: ts.noop,
  2596. logStopReadFile: ts.noop,
  2597. logStartBindFile: ts.noop,
  2598. logStopBindFile: ts.noop,
  2599. logStartScheduledOperation: ts.noop,
  2600. logStopScheduledOperation: ts.noop,
  2601. };
  2602. // Load optional module to enable Event Tracing for Windows
  2603. // See https://github.com/microsoft/typescript-etw for more information
  2604. var etwModule;
  2605. try {
  2606. // require() will throw an exception if the module is not installed
  2607. // It may also return undefined if not installed properly
  2608. // MONACOCHANGE
  2609. etwModule = undefined;
  2610. // END MONACOCHANGE
  2611. }
  2612. catch (e) {
  2613. etwModule = undefined;
  2614. }
  2615. /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
  2616. ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
  2617. })(ts || (ts = {}));
  2618. /* @internal */
  2619. var ts;
  2620. (function (ts) {
  2621. // https://semver.org/#spec-item-2
  2622. // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
  2623. // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
  2624. // > version, and Z is the patch version. Each element MUST increase numerically.
  2625. //
  2626. // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
  2627. // value of `0`.
  2628. var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
  2629. // https://semver.org/#spec-item-9
  2630. // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
  2631. // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
  2632. // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
  2633. // > MUST NOT include leading zeroes.
  2634. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
  2635. // https://semver.org/#spec-item-10
  2636. // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
  2637. // > identifiers immediately following the patch or pre-release version. Identifiers MUST
  2638. // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
  2639. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
  2640. // https://semver.org/#spec-item-9
  2641. // > Numeric identifiers MUST NOT include leading zeroes.
  2642. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
  2643. /**
  2644. * Describes a precise semantic version number, https://semver.org
  2645. */
  2646. var Version = /** @class */ (function () {
  2647. function Version(major, minor, patch, prerelease, build) {
  2648. if (minor === void 0) { minor = 0; }
  2649. if (patch === void 0) { patch = 0; }
  2650. if (prerelease === void 0) { prerelease = ""; }
  2651. if (build === void 0) { build = ""; }
  2652. if (typeof major === "string") {
  2653. var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version");
  2654. (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
  2655. }
  2656. ts.Debug.assert(major >= 0, "Invalid argument: major");
  2657. ts.Debug.assert(minor >= 0, "Invalid argument: minor");
  2658. ts.Debug.assert(patch >= 0, "Invalid argument: patch");
  2659. ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
  2660. ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
  2661. this.major = major;
  2662. this.minor = minor;
  2663. this.patch = patch;
  2664. this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
  2665. this.build = build ? build.split(".") : ts.emptyArray;
  2666. }
  2667. Version.tryParse = function (text) {
  2668. var result = tryParseComponents(text);
  2669. if (!result)
  2670. return undefined;
  2671. var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
  2672. return new Version(major, minor, patch, prerelease, build);
  2673. };
  2674. Version.prototype.compareTo = function (other) {
  2675. // https://semver.org/#spec-item-11
  2676. // > Precedence is determined by the first difference when comparing each of these
  2677. // > identifiers from left to right as follows: Major, minor, and patch versions are
  2678. // > always compared numerically.
  2679. //
  2680. // https://semver.org/#spec-item-11
  2681. // > Precedence for two pre-release versions with the same major, minor, and patch version
  2682. // > MUST be determined by comparing each dot separated identifier from left to right until
  2683. // > a difference is found [...]
  2684. //
  2685. // https://semver.org/#spec-item-11
  2686. // > Build metadata does not figure into precedence
  2687. if (this === other)
  2688. return 0 /* EqualTo */;
  2689. if (other === undefined)
  2690. return 1 /* GreaterThan */;
  2691. return ts.compareValues(this.major, other.major)
  2692. || ts.compareValues(this.minor, other.minor)
  2693. || ts.compareValues(this.patch, other.patch)
  2694. || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
  2695. };
  2696. Version.prototype.increment = function (field) {
  2697. switch (field) {
  2698. case "major": return new Version(this.major + 1, 0, 0);
  2699. case "minor": return new Version(this.major, this.minor + 1, 0);
  2700. case "patch": return new Version(this.major, this.minor, this.patch + 1);
  2701. default: return ts.Debug.assertNever(field);
  2702. }
  2703. };
  2704. Version.prototype.toString = function () {
  2705. var result = this.major + "." + this.minor + "." + this.patch;
  2706. if (ts.some(this.prerelease))
  2707. result += "-" + this.prerelease.join(".");
  2708. if (ts.some(this.build))
  2709. result += "+" + this.build.join(".");
  2710. return result;
  2711. };
  2712. Version.zero = new Version(0, 0, 0);
  2713. return Version;
  2714. }());
  2715. ts.Version = Version;
  2716. function tryParseComponents(text) {
  2717. var match = versionRegExp.exec(text);
  2718. if (!match)
  2719. return undefined;
  2720. var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d;
  2721. if (prerelease && !prereleaseRegExp.test(prerelease))
  2722. return undefined;
  2723. if (build && !buildRegExp.test(build))
  2724. return undefined;
  2725. return {
  2726. major: parseInt(major, 10),
  2727. minor: parseInt(minor, 10),
  2728. patch: parseInt(patch, 10),
  2729. prerelease: prerelease,
  2730. build: build
  2731. };
  2732. }
  2733. function comparePrerelaseIdentifiers(left, right) {
  2734. // https://semver.org/#spec-item-11
  2735. // > When major, minor, and patch are equal, a pre-release version has lower precedence
  2736. // > than a normal version.
  2737. if (left === right)
  2738. return 0 /* EqualTo */;
  2739. if (left.length === 0)
  2740. return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
  2741. if (right.length === 0)
  2742. return -1 /* LessThan */;
  2743. // https://semver.org/#spec-item-11
  2744. // > Precedence for two pre-release versions with the same major, minor, and patch version
  2745. // > MUST be determined by comparing each dot separated identifier from left to right until
  2746. // > a difference is found [...]
  2747. var length = Math.min(left.length, right.length);
  2748. for (var i = 0; i < length; i++) {
  2749. var leftIdentifier = left[i];
  2750. var rightIdentifier = right[i];
  2751. if (leftIdentifier === rightIdentifier)
  2752. continue;
  2753. var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
  2754. var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
  2755. if (leftIsNumeric || rightIsNumeric) {
  2756. // https://semver.org/#spec-item-11
  2757. // > Numeric identifiers always have lower precedence than non-numeric identifiers.
  2758. if (leftIsNumeric !== rightIsNumeric)
  2759. return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
  2760. // https://semver.org/#spec-item-11
  2761. // > identifiers consisting of only digits are compared numerically
  2762. var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
  2763. if (result)
  2764. return result;
  2765. }
  2766. else {
  2767. // https://semver.org/#spec-item-11
  2768. // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
  2769. var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
  2770. if (result)
  2771. return result;
  2772. }
  2773. }
  2774. // https://semver.org/#spec-item-11
  2775. // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
  2776. // > of the preceding identifiers are equal.
  2777. return ts.compareValues(left.length, right.length);
  2778. }
  2779. /**
  2780. * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
  2781. */
  2782. var VersionRange = /** @class */ (function () {
  2783. function VersionRange(spec) {
  2784. this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
  2785. }
  2786. VersionRange.tryParse = function (text) {
  2787. var sets = parseRange(text);
  2788. if (sets) {
  2789. var range = new VersionRange("");
  2790. range._alternatives = sets;
  2791. return range;
  2792. }
  2793. return undefined;
  2794. };
  2795. VersionRange.prototype.test = function (version) {
  2796. if (typeof version === "string")
  2797. version = new Version(version);
  2798. return testDisjunction(version, this._alternatives);
  2799. };
  2800. VersionRange.prototype.toString = function () {
  2801. return formatDisjunction(this._alternatives);
  2802. };
  2803. return VersionRange;
  2804. }());
  2805. ts.VersionRange = VersionRange;
  2806. // https://github.com/npm/node-semver#range-grammar
  2807. //
  2808. // range-set ::= range ( logical-or range ) *
  2809. // range ::= hyphen | simple ( ' ' simple ) * | ''
  2810. // logical-or ::= ( ' ' ) * '||' ( ' ' ) *
  2811. var logicalOrRegExp = /\s*\|\|\s*/g;
  2812. var whitespaceRegExp = /\s+/g;
  2813. // https://github.com/npm/node-semver#range-grammar
  2814. //
  2815. // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
  2816. // xr ::= 'x' | 'X' | '*' | nr
  2817. // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
  2818. // qualifier ::= ( '-' pre )? ( '+' build )?
  2819. // pre ::= parts
  2820. // build ::= parts
  2821. // parts ::= part ( '.' part ) *
  2822. // part ::= nr | [-0-9A-Za-z]+
  2823. var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
  2824. // https://github.com/npm/node-semver#range-grammar
  2825. //
  2826. // hyphen ::= partial ' - ' partial
  2827. var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
  2828. // https://github.com/npm/node-semver#range-grammar
  2829. //
  2830. // simple ::= primitive | partial | tilde | caret
  2831. // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
  2832. // tilde ::= '~' partial
  2833. // caret ::= '^' partial
  2834. var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
  2835. function parseRange(text) {
  2836. var alternatives = [];
  2837. for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
  2838. var range = _a[_i];
  2839. if (!range)
  2840. continue;
  2841. var comparators = [];
  2842. var match = hyphenRegExp.exec(range);
  2843. if (match) {
  2844. if (!parseHyphen(match[1], match[2], comparators))
  2845. return undefined;
  2846. }
  2847. else {
  2848. for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
  2849. var simple = _c[_b];
  2850. var match_1 = rangeRegExp.exec(simple);
  2851. if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
  2852. return undefined;
  2853. }
  2854. }
  2855. alternatives.push(comparators);
  2856. }
  2857. return alternatives;
  2858. }
  2859. function parsePartial(text) {
  2860. var match = partialRegExp.exec(text);
  2861. if (!match)
  2862. return undefined;
  2863. var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5];
  2864. var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build);
  2865. return { version: version, major: major, minor: minor, patch: patch };
  2866. }
  2867. function parseHyphen(left, right, comparators) {
  2868. var leftResult = parsePartial(left);
  2869. if (!leftResult)
  2870. return false;
  2871. var rightResult = parsePartial(right);
  2872. if (!rightResult)
  2873. return false;
  2874. if (!isWildcard(leftResult.major)) {
  2875. comparators.push(createComparator(">=", leftResult.version));
  2876. }
  2877. if (!isWildcard(rightResult.major)) {
  2878. comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
  2879. isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
  2880. createComparator("<=", rightResult.version));
  2881. }
  2882. return true;
  2883. }
  2884. function parseComparator(operator, text, comparators) {
  2885. var result = parsePartial(text);
  2886. if (!result)
  2887. return false;
  2888. var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
  2889. if (!isWildcard(major)) {
  2890. switch (operator) {
  2891. case "~":
  2892. comparators.push(createComparator(">=", version));
  2893. comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
  2894. "minor")));
  2895. break;
  2896. case "^":
  2897. comparators.push(createComparator(">=", version));
  2898. comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
  2899. version.minor > 0 || isWildcard(patch) ? "minor" :
  2900. "patch")));
  2901. break;
  2902. case "<":
  2903. case ">=":
  2904. comparators.push(createComparator(operator, version));
  2905. break;
  2906. case "<=":
  2907. case ">":
  2908. comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
  2909. isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
  2910. createComparator(operator, version));
  2911. break;
  2912. case "=":
  2913. case undefined:
  2914. if (isWildcard(minor) || isWildcard(patch)) {
  2915. comparators.push(createComparator(">=", version));
  2916. comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
  2917. }
  2918. else {
  2919. comparators.push(createComparator("=", version));
  2920. }
  2921. break;
  2922. default:
  2923. // unrecognized
  2924. return false;
  2925. }
  2926. }
  2927. else if (operator === "<" || operator === ">") {
  2928. comparators.push(createComparator("<", Version.zero));
  2929. }
  2930. return true;
  2931. }
  2932. function isWildcard(part) {
  2933. return part === "*" || part === "x" || part === "X";
  2934. }
  2935. function createComparator(operator, operand) {
  2936. return { operator: operator, operand: operand };
  2937. }
  2938. function testDisjunction(version, alternatives) {
  2939. // an empty disjunction is treated as "*" (all versions)
  2940. if (alternatives.length === 0)
  2941. return true;
  2942. for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
  2943. var alternative = alternatives_1[_i];
  2944. if (testAlternative(version, alternative))
  2945. return true;
  2946. }
  2947. return false;
  2948. }
  2949. function testAlternative(version, comparators) {
  2950. for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
  2951. var comparator = comparators_1[_i];
  2952. if (!testComparator(version, comparator.operator, comparator.operand))
  2953. return false;
  2954. }
  2955. return true;
  2956. }
  2957. function testComparator(version, operator, operand) {
  2958. var cmp = version.compareTo(operand);
  2959. switch (operator) {
  2960. case "<": return cmp < 0;
  2961. case "<=": return cmp <= 0;
  2962. case ">": return cmp > 0;
  2963. case ">=": return cmp >= 0;
  2964. case "=": return cmp === 0;
  2965. default: return ts.Debug.assertNever(operator);
  2966. }
  2967. }
  2968. function formatDisjunction(alternatives) {
  2969. return ts.map(alternatives, formatAlternative).join(" || ") || "*";
  2970. }
  2971. function formatAlternative(comparators) {
  2972. return ts.map(comparators, formatComparator).join(" ");
  2973. }
  2974. function formatComparator(comparator) {
  2975. return "" + comparator.operator + comparator.operand;
  2976. }
  2977. })(ts || (ts = {}));
  2978. var ts;
  2979. (function (ts) {
  2980. // token > SyntaxKind.Identifier => token is a keyword
  2981. // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
  2982. var SyntaxKind;
  2983. (function (SyntaxKind) {
  2984. SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
  2985. SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
  2986. SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
  2987. SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
  2988. SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
  2989. SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
  2990. // We detect and preserve #! on the first line
  2991. SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
  2992. // We detect and provide better error recovery when we encounter a git merge marker. This
  2993. // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
  2994. SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
  2995. // Literals
  2996. SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
  2997. SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
  2998. SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
  2999. SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
  3000. SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
  3001. SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
  3002. SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
  3003. // Pseudo-literals
  3004. SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
  3005. SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
  3006. SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
  3007. // Punctuation
  3008. SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
  3009. SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
  3010. SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
  3011. SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
  3012. SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
  3013. SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
  3014. SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
  3015. SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
  3016. SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
  3017. SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
  3018. SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
  3019. SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
  3020. SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
  3021. SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
  3022. SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
  3023. SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
  3024. SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
  3025. SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
  3026. SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
  3027. SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
  3028. SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
  3029. SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
  3030. SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
  3031. SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
  3032. SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
  3033. SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
  3034. SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
  3035. SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
  3036. SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
  3037. SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
  3038. SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
  3039. SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
  3040. SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
  3041. SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
  3042. SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
  3043. SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
  3044. SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
  3045. SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
  3046. SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
  3047. SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
  3048. SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
  3049. SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
  3050. SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
  3051. /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
  3052. SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
  3053. // Assignments
  3054. SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
  3055. SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
  3056. SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
  3057. SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
  3058. SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
  3059. SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
  3060. SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
  3061. SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
  3062. SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
  3063. SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
  3064. SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
  3065. SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
  3066. SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
  3067. // Identifiers and PrivateIdentifiers
  3068. SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
  3069. SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
  3070. // Reserved words
  3071. SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
  3072. SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
  3073. SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
  3074. SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
  3075. SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
  3076. SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
  3077. SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
  3078. SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
  3079. SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
  3080. SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
  3081. SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
  3082. SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
  3083. SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
  3084. SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
  3085. SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
  3086. SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
  3087. SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
  3088. SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
  3089. SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
  3090. SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
  3091. SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
  3092. SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
  3093. SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
  3094. SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
  3095. SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
  3096. SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
  3097. SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
  3098. SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
  3099. SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
  3100. SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
  3101. SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
  3102. SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
  3103. SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
  3104. SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
  3105. SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
  3106. SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
  3107. // Strict mode reserved words
  3108. SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
  3109. SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
  3110. SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
  3111. SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
  3112. SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
  3113. SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
  3114. SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
  3115. SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
  3116. SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
  3117. // Contextual keywords
  3118. SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
  3119. SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
  3120. SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
  3121. SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
  3122. SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
  3123. SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
  3124. SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
  3125. SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
  3126. SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
  3127. SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
  3128. SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
  3129. SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
  3130. SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
  3131. SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
  3132. SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
  3133. SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
  3134. SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
  3135. SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
  3136. SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
  3137. SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
  3138. SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
  3139. SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
  3140. SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
  3141. SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
  3142. SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
  3143. SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
  3144. SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
  3145. SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
  3146. SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
  3147. SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
  3148. SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
  3149. // Parse tree nodes
  3150. // Names
  3151. SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
  3152. SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
  3153. // Signature elements
  3154. SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
  3155. SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
  3156. SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
  3157. // TypeMember
  3158. SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
  3159. SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
  3160. SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
  3161. SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
  3162. SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
  3163. SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
  3164. SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
  3165. SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
  3166. SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
  3167. SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
  3168. // Type
  3169. SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
  3170. SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
  3171. SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
  3172. SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
  3173. SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
  3174. SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
  3175. SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
  3176. SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
  3177. SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
  3178. SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
  3179. SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
  3180. SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
  3181. SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
  3182. SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
  3183. SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
  3184. SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
  3185. SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
  3186. SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
  3187. SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
  3188. SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
  3189. SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
  3190. // Binding patterns
  3191. SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
  3192. SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
  3193. SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
  3194. // Expression
  3195. SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
  3196. SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
  3197. SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
  3198. SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
  3199. SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
  3200. SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
  3201. SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
  3202. SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
  3203. SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
  3204. SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
  3205. SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
  3206. SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
  3207. SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
  3208. SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
  3209. SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
  3210. SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
  3211. SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
  3212. SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
  3213. SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
  3214. SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
  3215. SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
  3216. SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
  3217. SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
  3218. SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
  3219. SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
  3220. SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
  3221. SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
  3222. SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
  3223. SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
  3224. // Misc
  3225. SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
  3226. SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
  3227. // Element
  3228. SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
  3229. SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
  3230. SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
  3231. SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
  3232. SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
  3233. SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
  3234. SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
  3235. SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
  3236. SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
  3237. SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
  3238. SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
  3239. SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
  3240. SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
  3241. SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
  3242. SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
  3243. SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
  3244. SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
  3245. SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
  3246. SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
  3247. SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
  3248. SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
  3249. SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
  3250. SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
  3251. SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
  3252. SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
  3253. SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
  3254. SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
  3255. SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
  3256. SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
  3257. SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
  3258. SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
  3259. SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
  3260. SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
  3261. SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
  3262. SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
  3263. SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
  3264. SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
  3265. SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
  3266. SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
  3267. SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
  3268. SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
  3269. SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
  3270. // Module references
  3271. SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
  3272. // JSX
  3273. SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
  3274. SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
  3275. SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
  3276. SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
  3277. SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
  3278. SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
  3279. SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
  3280. SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
  3281. SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
  3282. SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
  3283. SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
  3284. // Clauses
  3285. SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
  3286. SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
  3287. SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
  3288. SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
  3289. // Property assignments
  3290. SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
  3291. SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
  3292. SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
  3293. // Enum
  3294. SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
  3295. // Unparsed
  3296. SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
  3297. SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
  3298. SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
  3299. SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
  3300. SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
  3301. // Top-level nodes
  3302. SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
  3303. SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
  3304. SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
  3305. SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
  3306. // JSDoc nodes
  3307. SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
  3308. // The * type
  3309. SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
  3310. // The ? type
  3311. SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
  3312. SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
  3313. SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
  3314. SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
  3315. SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
  3316. SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
  3317. // https://jsdoc.app/about-namepaths.html
  3318. SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
  3319. SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
  3320. SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
  3321. SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
  3322. SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
  3323. SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
  3324. SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 308] = "JSDocAuthorTag";
  3325. SyntaxKind[SyntaxKind["JSDocClassTag"] = 309] = "JSDocClassTag";
  3326. SyntaxKind[SyntaxKind["JSDocPublicTag"] = 310] = "JSDocPublicTag";
  3327. SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 311] = "JSDocPrivateTag";
  3328. SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 312] = "JSDocProtectedTag";
  3329. SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 313] = "JSDocReadonlyTag";
  3330. SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 314] = "JSDocCallbackTag";
  3331. SyntaxKind[SyntaxKind["JSDocEnumTag"] = 315] = "JSDocEnumTag";
  3332. SyntaxKind[SyntaxKind["JSDocParameterTag"] = 316] = "JSDocParameterTag";
  3333. SyntaxKind[SyntaxKind["JSDocReturnTag"] = 317] = "JSDocReturnTag";
  3334. SyntaxKind[SyntaxKind["JSDocThisTag"] = 318] = "JSDocThisTag";
  3335. SyntaxKind[SyntaxKind["JSDocTypeTag"] = 319] = "JSDocTypeTag";
  3336. SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 320] = "JSDocTemplateTag";
  3337. SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 321] = "JSDocTypedefTag";
  3338. SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 322] = "JSDocPropertyTag";
  3339. // Synthesized list
  3340. SyntaxKind[SyntaxKind["SyntaxList"] = 323] = "SyntaxList";
  3341. // Transformation nodes
  3342. SyntaxKind[SyntaxKind["NotEmittedStatement"] = 324] = "NotEmittedStatement";
  3343. SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 325] = "PartiallyEmittedExpression";
  3344. SyntaxKind[SyntaxKind["CommaListExpression"] = 326] = "CommaListExpression";
  3345. SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 327] = "MergeDeclarationMarker";
  3346. SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 328] = "EndOfDeclarationMarker";
  3347. SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 329] = "SyntheticReferenceExpression";
  3348. // Enum value count
  3349. SyntaxKind[SyntaxKind["Count"] = 330] = "Count";
  3350. // Markers
  3351. SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
  3352. SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
  3353. SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
  3354. SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
  3355. SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
  3356. SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
  3357. SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
  3358. SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
  3359. SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
  3360. SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
  3361. SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
  3362. SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
  3363. SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
  3364. SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
  3365. SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
  3366. SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
  3367. SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
  3368. SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
  3369. SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
  3370. SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
  3371. SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
  3372. SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
  3373. SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
  3374. SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
  3375. SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
  3376. SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
  3377. SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
  3378. SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
  3379. SyntaxKind[SyntaxKind["LastJSDocNode"] = 322] = "LastJSDocNode";
  3380. SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
  3381. SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 322] = "LastJSDocTagNode";
  3382. /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
  3383. /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
  3384. })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
  3385. var NodeFlags;
  3386. (function (NodeFlags) {
  3387. NodeFlags[NodeFlags["None"] = 0] = "None";
  3388. NodeFlags[NodeFlags["Let"] = 1] = "Let";
  3389. NodeFlags[NodeFlags["Const"] = 2] = "Const";
  3390. NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
  3391. NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
  3392. NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
  3393. NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
  3394. NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
  3395. NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
  3396. NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
  3397. NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
  3398. NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
  3399. NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
  3400. NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
  3401. NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
  3402. NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
  3403. NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
  3404. NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
  3405. NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
  3406. NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
  3407. NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
  3408. // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
  3409. // walking the tree if the flags are not set. However, these flags are just a approximation
  3410. // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
  3411. // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
  3412. // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
  3413. // However, the removal operation should not occur often and in the case of the
  3414. // removal, it is likely that users will add the import anyway.
  3415. // The advantage of this approach is its simplicity. For the case of batch compilation,
  3416. // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
  3417. /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
  3418. /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
  3419. NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
  3420. /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
  3421. /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
  3422. NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
  3423. /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
  3424. NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
  3425. NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
  3426. NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
  3427. // Parsing context flags
  3428. NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
  3429. // Exclude these flags when parsing a Type
  3430. NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
  3431. // Represents all flags that are potentially set once and
  3432. // never cleared on SourceFiles which get re-used in between incremental parses.
  3433. // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
  3434. /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
  3435. })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
  3436. var ModifierFlags;
  3437. (function (ModifierFlags) {
  3438. ModifierFlags[ModifierFlags["None"] = 0] = "None";
  3439. ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
  3440. ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
  3441. ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
  3442. ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
  3443. ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
  3444. ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
  3445. ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
  3446. ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
  3447. ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
  3448. ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
  3449. ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
  3450. ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
  3451. ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
  3452. // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
  3453. ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
  3454. ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
  3455. ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
  3456. ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
  3457. ModifierFlags[ModifierFlags["All"] = 3071] = "All";
  3458. })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
  3459. var JsxFlags;
  3460. (function (JsxFlags) {
  3461. JsxFlags[JsxFlags["None"] = 0] = "None";
  3462. /** An element from a named property of the JSX.IntrinsicElements interface */
  3463. JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
  3464. /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
  3465. JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
  3466. JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
  3467. })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
  3468. /* @internal */
  3469. var RelationComparisonResult;
  3470. (function (RelationComparisonResult) {
  3471. RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
  3472. RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
  3473. RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
  3474. RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
  3475. RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
  3476. RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
  3477. })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
  3478. /*@internal*/
  3479. var GeneratedIdentifierFlags;
  3480. (function (GeneratedIdentifierFlags) {
  3481. // Kinds
  3482. GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
  3483. GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
  3484. GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
  3485. GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
  3486. GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
  3487. GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
  3488. // Flags
  3489. GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
  3490. GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
  3491. GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
  3492. })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
  3493. var TokenFlags;
  3494. (function (TokenFlags) {
  3495. TokenFlags[TokenFlags["None"] = 0] = "None";
  3496. /* @internal */
  3497. TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
  3498. /* @internal */
  3499. TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
  3500. /* @internal */
  3501. TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
  3502. /* @internal */
  3503. TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
  3504. TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
  3505. TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
  3506. TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
  3507. TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
  3508. TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
  3509. /* @internal */
  3510. TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
  3511. /* @internal */
  3512. TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
  3513. /* @internal */
  3514. TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
  3515. /* @internal */
  3516. TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
  3517. })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
  3518. // NOTE: Ensure this is up-to-date with src/debug/debug.ts
  3519. var FlowFlags;
  3520. (function (FlowFlags) {
  3521. FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
  3522. FlowFlags[FlowFlags["Start"] = 2] = "Start";
  3523. FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
  3524. FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
  3525. FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
  3526. FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
  3527. FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
  3528. FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
  3529. FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
  3530. FlowFlags[FlowFlags["Call"] = 512] = "Call";
  3531. FlowFlags[FlowFlags["Referenced"] = 1024] = "Referenced";
  3532. FlowFlags[FlowFlags["Shared"] = 2048] = "Shared";
  3533. FlowFlags[FlowFlags["PreFinally"] = 4096] = "PreFinally";
  3534. FlowFlags[FlowFlags["AfterFinally"] = 8192] = "AfterFinally";
  3535. FlowFlags[FlowFlags["Label"] = 12] = "Label";
  3536. FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
  3537. })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
  3538. var OperationCanceledException = /** @class */ (function () {
  3539. function OperationCanceledException() {
  3540. }
  3541. return OperationCanceledException;
  3542. }());
  3543. ts.OperationCanceledException = OperationCanceledException;
  3544. /*@internal*/
  3545. var RefFileKind;
  3546. (function (RefFileKind) {
  3547. RefFileKind[RefFileKind["Import"] = 0] = "Import";
  3548. RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
  3549. RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
  3550. })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
  3551. /* @internal */
  3552. var StructureIsReused;
  3553. (function (StructureIsReused) {
  3554. StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
  3555. StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
  3556. StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
  3557. })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
  3558. /** Return code used by getEmitOutput function to indicate status of the function */
  3559. var ExitStatus;
  3560. (function (ExitStatus) {
  3561. // Compiler ran successfully. Either this was a simple do-nothing compilation (for example,
  3562. // when -version or -help was provided, or this was a normal compilation, no diagnostics
  3563. // were produced, and all outputs were generated successfully.
  3564. ExitStatus[ExitStatus["Success"] = 0] = "Success";
  3565. // Diagnostics were produced and because of them no code was generated.
  3566. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
  3567. // Diagnostics were produced and outputs were generated in spite of them.
  3568. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
  3569. // When build skipped because passed in project is invalid
  3570. ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
  3571. // When build is skipped because project references form cycle
  3572. ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
  3573. /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
  3574. ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
  3575. })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
  3576. /* @internal */
  3577. var UnionReduction;
  3578. (function (UnionReduction) {
  3579. UnionReduction[UnionReduction["None"] = 0] = "None";
  3580. UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
  3581. UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
  3582. })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
  3583. /* @internal */
  3584. var ContextFlags;
  3585. (function (ContextFlags) {
  3586. ContextFlags[ContextFlags["None"] = 0] = "None";
  3587. ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
  3588. ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
  3589. ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
  3590. })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
  3591. // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
  3592. var NodeBuilderFlags;
  3593. (function (NodeBuilderFlags) {
  3594. NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
  3595. // Options
  3596. NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
  3597. NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
  3598. NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
  3599. NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
  3600. NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
  3601. NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
  3602. NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
  3603. NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
  3604. NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
  3605. NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
  3606. NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
  3607. NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
  3608. NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
  3609. NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
  3610. NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
  3611. NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
  3612. // Error handling
  3613. NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
  3614. NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
  3615. NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
  3616. NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
  3617. NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
  3618. NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
  3619. NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
  3620. // Errors (cont.)
  3621. NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
  3622. /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
  3623. NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
  3624. // State
  3625. NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
  3626. NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
  3627. NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
  3628. NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
  3629. })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
  3630. // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
  3631. var TypeFormatFlags;
  3632. (function (TypeFormatFlags) {
  3633. TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
  3634. TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
  3635. TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
  3636. // hole because there's a hole in node builder flags
  3637. TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
  3638. // hole because there's a hole in node builder flags
  3639. TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
  3640. TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
  3641. // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
  3642. TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
  3643. // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
  3644. TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
  3645. TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
  3646. TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
  3647. TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
  3648. TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
  3649. TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
  3650. // Error Handling
  3651. TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
  3652. // TypeFormatFlags exclusive
  3653. TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
  3654. TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
  3655. // State
  3656. TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
  3657. TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
  3658. TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
  3659. TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
  3660. /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
  3661. TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask";
  3662. })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
  3663. var SymbolFormatFlags;
  3664. (function (SymbolFormatFlags) {
  3665. SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
  3666. // Write symbols's type argument if it is instantiated symbol
  3667. // eg. class C<T> { p: T } <-- Show p as C<T>.p here
  3668. // var a: C<number>;
  3669. // var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
  3670. SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
  3671. // Use only external alias information to get the symbol name in the given context
  3672. // eg. module m { export class c { } } import x = m.c;
  3673. // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
  3674. SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
  3675. // Build symbol name using any nodes needed, instead of just components of an entity name
  3676. SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
  3677. // Prefer aliases which are not directly visible
  3678. SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
  3679. // Skip building an accessible symbol chain
  3680. /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
  3681. })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
  3682. /* @internal */
  3683. var SymbolAccessibility;
  3684. (function (SymbolAccessibility) {
  3685. SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
  3686. SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
  3687. SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
  3688. })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
  3689. /* @internal */
  3690. var SyntheticSymbolKind;
  3691. (function (SyntheticSymbolKind) {
  3692. SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
  3693. SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
  3694. })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
  3695. var TypePredicateKind;
  3696. (function (TypePredicateKind) {
  3697. TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
  3698. TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
  3699. TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
  3700. TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
  3701. })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
  3702. /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
  3703. /* @internal */
  3704. var TypeReferenceSerializationKind;
  3705. (function (TypeReferenceSerializationKind) {
  3706. // The TypeReferenceNode could not be resolved.
  3707. // The type name should be emitted using a safe fallback.
  3708. TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
  3709. // The TypeReferenceNode resolves to a type with a constructor
  3710. // function that can be reached at runtime (e.g. a `class`
  3711. // declaration or a `var` declaration for the static side
  3712. // of a type, such as the global `Promise` type in lib.d.ts).
  3713. TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
  3714. // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
  3715. TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
  3716. // The TypeReferenceNode resolves to a Number-like type.
  3717. TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
  3718. // The TypeReferenceNode resolves to a BigInt-like type.
  3719. TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
  3720. // The TypeReferenceNode resolves to a String-like type.
  3721. TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
  3722. // The TypeReferenceNode resolves to a Boolean-like type.
  3723. TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
  3724. // The TypeReferenceNode resolves to an Array-like type.
  3725. TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
  3726. // The TypeReferenceNode resolves to the ESSymbol type.
  3727. TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
  3728. // The TypeReferenceNode resolved to the global Promise constructor symbol.
  3729. TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
  3730. // The TypeReferenceNode resolves to a Function type or a type with call signatures.
  3731. TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
  3732. // The TypeReferenceNode resolves to any other type.
  3733. TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
  3734. })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
  3735. var SymbolFlags;
  3736. (function (SymbolFlags) {
  3737. SymbolFlags[SymbolFlags["None"] = 0] = "None";
  3738. SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
  3739. SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
  3740. SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
  3741. SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
  3742. SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
  3743. SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
  3744. SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
  3745. SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
  3746. SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
  3747. SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
  3748. SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
  3749. SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
  3750. SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
  3751. SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
  3752. SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
  3753. SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
  3754. SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
  3755. SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
  3756. SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
  3757. SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
  3758. SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
  3759. SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
  3760. SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
  3761. SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
  3762. SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
  3763. SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
  3764. SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
  3765. SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
  3766. /* @internal */
  3767. SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
  3768. SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
  3769. SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
  3770. SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
  3771. SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
  3772. SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
  3773. SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
  3774. SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
  3775. // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
  3776. // same name, or any other value that is not a variable, e.g. ValueModule or Class
  3777. SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
  3778. // Block-scoped declarations are not allowed to be re-declared
  3779. // they can not merge with anything in the value space
  3780. SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
  3781. SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
  3782. SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
  3783. SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
  3784. SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
  3785. SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
  3786. SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
  3787. SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
  3788. SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
  3789. SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
  3790. SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
  3791. SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
  3792. SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
  3793. SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
  3794. SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
  3795. SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
  3796. SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
  3797. SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
  3798. SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
  3799. SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
  3800. SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
  3801. SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
  3802. /* @internal */
  3803. SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
  3804. /* @internal */
  3805. SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
  3806. /* @internal */
  3807. // The set of things we consider semantically classifiable. Used to speed up the LS during
  3808. // classification.
  3809. SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
  3810. /* @internal */
  3811. SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
  3812. })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
  3813. /* @internal */
  3814. var EnumKind;
  3815. (function (EnumKind) {
  3816. EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
  3817. EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
  3818. })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
  3819. /* @internal */
  3820. var CheckFlags;
  3821. (function (CheckFlags) {
  3822. CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
  3823. CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
  3824. CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
  3825. CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
  3826. CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
  3827. CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
  3828. CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
  3829. CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
  3830. CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
  3831. CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
  3832. CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
  3833. CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
  3834. CheckFlags[CheckFlags["Late"] = 4096] = "Late";
  3835. CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
  3836. CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
  3837. CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
  3838. CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
  3839. CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
  3840. CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
  3841. CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
  3842. })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
  3843. var InternalSymbolName;
  3844. (function (InternalSymbolName) {
  3845. InternalSymbolName["Call"] = "__call";
  3846. InternalSymbolName["Constructor"] = "__constructor";
  3847. InternalSymbolName["New"] = "__new";
  3848. InternalSymbolName["Index"] = "__index";
  3849. InternalSymbolName["ExportStar"] = "__export";
  3850. InternalSymbolName["Global"] = "__global";
  3851. InternalSymbolName["Missing"] = "__missing";
  3852. InternalSymbolName["Type"] = "__type";
  3853. InternalSymbolName["Object"] = "__object";
  3854. InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
  3855. InternalSymbolName["Class"] = "__class";
  3856. InternalSymbolName["Function"] = "__function";
  3857. InternalSymbolName["Computed"] = "__computed";
  3858. InternalSymbolName["Resolving"] = "__resolving__";
  3859. InternalSymbolName["ExportEquals"] = "export=";
  3860. InternalSymbolName["Default"] = "default";
  3861. InternalSymbolName["This"] = "this";
  3862. })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
  3863. /* @internal */
  3864. var NodeCheckFlags;
  3865. (function (NodeCheckFlags) {
  3866. NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
  3867. NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
  3868. NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
  3869. NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
  3870. NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
  3871. NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
  3872. NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
  3873. NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
  3874. NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
  3875. NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
  3876. NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
  3877. NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
  3878. NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
  3879. NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
  3880. NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
  3881. NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
  3882. NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
  3883. NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
  3884. NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
  3885. NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
  3886. NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
  3887. NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
  3888. NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
  3889. })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
  3890. var TypeFlags;
  3891. (function (TypeFlags) {
  3892. TypeFlags[TypeFlags["Any"] = 1] = "Any";
  3893. TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
  3894. TypeFlags[TypeFlags["String"] = 4] = "String";
  3895. TypeFlags[TypeFlags["Number"] = 8] = "Number";
  3896. TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
  3897. TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
  3898. TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
  3899. TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
  3900. TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
  3901. TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
  3902. TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
  3903. TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
  3904. TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
  3905. TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
  3906. TypeFlags[TypeFlags["Void"] = 16384] = "Void";
  3907. TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
  3908. TypeFlags[TypeFlags["Null"] = 65536] = "Null";
  3909. TypeFlags[TypeFlags["Never"] = 131072] = "Never";
  3910. TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
  3911. TypeFlags[TypeFlags["Object"] = 524288] = "Object";
  3912. TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
  3913. TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
  3914. TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
  3915. TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
  3916. TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
  3917. TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
  3918. TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
  3919. /* @internal */
  3920. TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
  3921. /* @internal */
  3922. TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
  3923. TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
  3924. TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
  3925. TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
  3926. /* @internal */
  3927. TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
  3928. /* @internal */
  3929. TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
  3930. TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
  3931. /* @internal */
  3932. TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
  3933. /* @internal */
  3934. TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
  3935. TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
  3936. TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
  3937. TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
  3938. TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
  3939. TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
  3940. TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
  3941. TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
  3942. /* @internal */
  3943. TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
  3944. TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
  3945. TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
  3946. TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
  3947. TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
  3948. TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
  3949. TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
  3950. TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
  3951. /* @internal */
  3952. TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
  3953. /* @internal */
  3954. TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
  3955. // 'Narrowable' types are types where narrowing actually narrows.
  3956. // This *should* be every type other than null, undefined, void, and never
  3957. TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
  3958. TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
  3959. /* @internal */
  3960. TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
  3961. // The following flags are aggregated during union and intersection type construction
  3962. /* @internal */
  3963. TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask";
  3964. // The following flags are used for different purposes during union and intersection type construction
  3965. /* @internal */
  3966. TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
  3967. /* @internal */
  3968. TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
  3969. /* @internal */
  3970. TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
  3971. /* @internal */
  3972. TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
  3973. // The following flag is used for different purposes by maybeTypeOfKind
  3974. /* @internal */
  3975. TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
  3976. })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
  3977. var ObjectFlags;
  3978. (function (ObjectFlags) {
  3979. ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
  3980. ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
  3981. ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
  3982. ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
  3983. ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
  3984. ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
  3985. ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
  3986. ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
  3987. ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
  3988. ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
  3989. ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
  3990. ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
  3991. ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
  3992. ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
  3993. ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
  3994. ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
  3995. ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
  3996. ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
  3997. /* @internal */
  3998. ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
  3999. /* @internal */
  4000. ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
  4001. /* @internal */
  4002. ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
  4003. /* @internal */
  4004. ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
  4005. ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
  4006. /* @internal */
  4007. ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
  4008. /* @internal */
  4009. ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
  4010. })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
  4011. /* @internal */
  4012. var VarianceFlags;
  4013. (function (VarianceFlags) {
  4014. VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
  4015. VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
  4016. VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
  4017. VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
  4018. VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
  4019. VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
  4020. VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
  4021. VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
  4022. VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
  4023. })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
  4024. /* @internal */
  4025. var JsxReferenceKind;
  4026. (function (JsxReferenceKind) {
  4027. JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
  4028. JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
  4029. JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
  4030. })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
  4031. var SignatureKind;
  4032. (function (SignatureKind) {
  4033. SignatureKind[SignatureKind["Call"] = 0] = "Call";
  4034. SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
  4035. })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
  4036. /* @internal */
  4037. var SignatureFlags;
  4038. (function (SignatureFlags) {
  4039. SignatureFlags[SignatureFlags["None"] = 0] = "None";
  4040. SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
  4041. SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
  4042. SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
  4043. SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
  4044. // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
  4045. // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
  4046. // instantiating the return type.
  4047. SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
  4048. SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
  4049. })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
  4050. var IndexKind;
  4051. (function (IndexKind) {
  4052. IndexKind[IndexKind["String"] = 0] = "String";
  4053. IndexKind[IndexKind["Number"] = 1] = "Number";
  4054. })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
  4055. var InferencePriority;
  4056. (function (InferencePriority) {
  4057. InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
  4058. InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
  4059. InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
  4060. InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
  4061. InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
  4062. InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
  4063. InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
  4064. InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
  4065. InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
  4066. InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
  4067. InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
  4068. InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
  4069. })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
  4070. /* @internal */
  4071. var InferenceFlags;
  4072. (function (InferenceFlags) {
  4073. InferenceFlags[InferenceFlags["None"] = 0] = "None";
  4074. InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
  4075. InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
  4076. InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
  4077. })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
  4078. /**
  4079. * Ternary values are defined such that
  4080. * x & y is False if either x or y is False.
  4081. * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
  4082. * x & y is True if both x and y are True.
  4083. * x | y is False if both x and y are False.
  4084. * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
  4085. * x | y is True if either x or y is True.
  4086. */
  4087. /* @internal */
  4088. var Ternary;
  4089. (function (Ternary) {
  4090. Ternary[Ternary["False"] = 0] = "False";
  4091. Ternary[Ternary["Maybe"] = 1] = "Maybe";
  4092. Ternary[Ternary["True"] = -1] = "True";
  4093. })(Ternary = ts.Ternary || (ts.Ternary = {}));
  4094. /* @internal */
  4095. var AssignmentDeclarationKind;
  4096. (function (AssignmentDeclarationKind) {
  4097. AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
  4098. /// exports.name = expr
  4099. AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
  4100. /// module.exports = expr
  4101. AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
  4102. /// className.prototype.name = expr
  4103. AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
  4104. /// this.name = expr
  4105. AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
  4106. // F.name = expr
  4107. AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
  4108. // F.prototype = { ... }
  4109. AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
  4110. // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
  4111. // Object.defineProperty(x, 'name', { get: Function, set: Function });
  4112. // Object.defineProperty(x, 'name', { get: Function });
  4113. // Object.defineProperty(x, 'name', { set: Function });
  4114. AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
  4115. // Object.defineProperty(exports || module.exports, 'name', ...);
  4116. AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
  4117. // Object.defineProperty(Foo.prototype, 'name', ...);
  4118. AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
  4119. })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
  4120. var DiagnosticCategory;
  4121. (function (DiagnosticCategory) {
  4122. DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
  4123. DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
  4124. DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
  4125. DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
  4126. })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
  4127. /* @internal */
  4128. function diagnosticCategoryName(d, lowerCase) {
  4129. if (lowerCase === void 0) { lowerCase = true; }
  4130. var name = DiagnosticCategory[d.category];
  4131. return lowerCase ? name.toLowerCase() : name;
  4132. }
  4133. ts.diagnosticCategoryName = diagnosticCategoryName;
  4134. var ModuleResolutionKind;
  4135. (function (ModuleResolutionKind) {
  4136. ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
  4137. ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
  4138. })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
  4139. var WatchFileKind;
  4140. (function (WatchFileKind) {
  4141. WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
  4142. WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
  4143. WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
  4144. WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
  4145. WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
  4146. })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
  4147. var WatchDirectoryKind;
  4148. (function (WatchDirectoryKind) {
  4149. WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
  4150. WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
  4151. WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
  4152. })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
  4153. var PollingWatchKind;
  4154. (function (PollingWatchKind) {
  4155. PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
  4156. PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
  4157. PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
  4158. })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
  4159. var ModuleKind;
  4160. (function (ModuleKind) {
  4161. ModuleKind[ModuleKind["None"] = 0] = "None";
  4162. ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
  4163. ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
  4164. ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
  4165. ModuleKind[ModuleKind["System"] = 4] = "System";
  4166. // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
  4167. // Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
  4168. // module kind).
  4169. ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
  4170. ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
  4171. ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
  4172. })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
  4173. var JsxEmit;
  4174. (function (JsxEmit) {
  4175. JsxEmit[JsxEmit["None"] = 0] = "None";
  4176. JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
  4177. JsxEmit[JsxEmit["React"] = 2] = "React";
  4178. JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
  4179. })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
  4180. var ImportsNotUsedAsValues;
  4181. (function (ImportsNotUsedAsValues) {
  4182. ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
  4183. ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
  4184. ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
  4185. })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
  4186. var NewLineKind;
  4187. (function (NewLineKind) {
  4188. NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
  4189. NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
  4190. })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
  4191. var ScriptKind;
  4192. (function (ScriptKind) {
  4193. ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
  4194. ScriptKind[ScriptKind["JS"] = 1] = "JS";
  4195. ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
  4196. ScriptKind[ScriptKind["TS"] = 3] = "TS";
  4197. ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
  4198. ScriptKind[ScriptKind["External"] = 5] = "External";
  4199. ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
  4200. /**
  4201. * Used on extensions that doesn't define the ScriptKind but the content defines it.
  4202. * Deferred extensions are going to be included in all project contexts.
  4203. */
  4204. ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
  4205. })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
  4206. var ScriptTarget;
  4207. (function (ScriptTarget) {
  4208. ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
  4209. ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
  4210. ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
  4211. ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
  4212. ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
  4213. ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
  4214. ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
  4215. ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
  4216. ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
  4217. ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
  4218. ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
  4219. })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
  4220. var LanguageVariant;
  4221. (function (LanguageVariant) {
  4222. LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
  4223. LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
  4224. })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
  4225. var WatchDirectoryFlags;
  4226. (function (WatchDirectoryFlags) {
  4227. WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
  4228. WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
  4229. })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
  4230. /* @internal */
  4231. var CharacterCodes;
  4232. (function (CharacterCodes) {
  4233. CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
  4234. CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
  4235. CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
  4236. CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
  4237. CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
  4238. CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
  4239. CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
  4240. // Unicode 3.0 space characters
  4241. CharacterCodes[CharacterCodes["space"] = 32] = "space";
  4242. CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
  4243. CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
  4244. CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
  4245. CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
  4246. CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
  4247. CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
  4248. CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
  4249. CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
  4250. CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
  4251. CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
  4252. CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
  4253. CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
  4254. CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
  4255. CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
  4256. CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
  4257. CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
  4258. CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
  4259. CharacterCodes[CharacterCodes["_"] = 95] = "_";
  4260. CharacterCodes[CharacterCodes["$"] = 36] = "$";
  4261. CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
  4262. CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
  4263. CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
  4264. CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
  4265. CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
  4266. CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
  4267. CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
  4268. CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
  4269. CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
  4270. CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
  4271. CharacterCodes[CharacterCodes["a"] = 97] = "a";
  4272. CharacterCodes[CharacterCodes["b"] = 98] = "b";
  4273. CharacterCodes[CharacterCodes["c"] = 99] = "c";
  4274. CharacterCodes[CharacterCodes["d"] = 100] = "d";
  4275. CharacterCodes[CharacterCodes["e"] = 101] = "e";
  4276. CharacterCodes[CharacterCodes["f"] = 102] = "f";
  4277. CharacterCodes[CharacterCodes["g"] = 103] = "g";
  4278. CharacterCodes[CharacterCodes["h"] = 104] = "h";
  4279. CharacterCodes[CharacterCodes["i"] = 105] = "i";
  4280. CharacterCodes[CharacterCodes["j"] = 106] = "j";
  4281. CharacterCodes[CharacterCodes["k"] = 107] = "k";
  4282. CharacterCodes[CharacterCodes["l"] = 108] = "l";
  4283. CharacterCodes[CharacterCodes["m"] = 109] = "m";
  4284. CharacterCodes[CharacterCodes["n"] = 110] = "n";
  4285. CharacterCodes[CharacterCodes["o"] = 111] = "o";
  4286. CharacterCodes[CharacterCodes["p"] = 112] = "p";
  4287. CharacterCodes[CharacterCodes["q"] = 113] = "q";
  4288. CharacterCodes[CharacterCodes["r"] = 114] = "r";
  4289. CharacterCodes[CharacterCodes["s"] = 115] = "s";
  4290. CharacterCodes[CharacterCodes["t"] = 116] = "t";
  4291. CharacterCodes[CharacterCodes["u"] = 117] = "u";
  4292. CharacterCodes[CharacterCodes["v"] = 118] = "v";
  4293. CharacterCodes[CharacterCodes["w"] = 119] = "w";
  4294. CharacterCodes[CharacterCodes["x"] = 120] = "x";
  4295. CharacterCodes[CharacterCodes["y"] = 121] = "y";
  4296. CharacterCodes[CharacterCodes["z"] = 122] = "z";
  4297. CharacterCodes[CharacterCodes["A"] = 65] = "A";
  4298. CharacterCodes[CharacterCodes["B"] = 66] = "B";
  4299. CharacterCodes[CharacterCodes["C"] = 67] = "C";
  4300. CharacterCodes[CharacterCodes["D"] = 68] = "D";
  4301. CharacterCodes[CharacterCodes["E"] = 69] = "E";
  4302. CharacterCodes[CharacterCodes["F"] = 70] = "F";
  4303. CharacterCodes[CharacterCodes["G"] = 71] = "G";
  4304. CharacterCodes[CharacterCodes["H"] = 72] = "H";
  4305. CharacterCodes[CharacterCodes["I"] = 73] = "I";
  4306. CharacterCodes[CharacterCodes["J"] = 74] = "J";
  4307. CharacterCodes[CharacterCodes["K"] = 75] = "K";
  4308. CharacterCodes[CharacterCodes["L"] = 76] = "L";
  4309. CharacterCodes[CharacterCodes["M"] = 77] = "M";
  4310. CharacterCodes[CharacterCodes["N"] = 78] = "N";
  4311. CharacterCodes[CharacterCodes["O"] = 79] = "O";
  4312. CharacterCodes[CharacterCodes["P"] = 80] = "P";
  4313. CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
  4314. CharacterCodes[CharacterCodes["R"] = 82] = "R";
  4315. CharacterCodes[CharacterCodes["S"] = 83] = "S";
  4316. CharacterCodes[CharacterCodes["T"] = 84] = "T";
  4317. CharacterCodes[CharacterCodes["U"] = 85] = "U";
  4318. CharacterCodes[CharacterCodes["V"] = 86] = "V";
  4319. CharacterCodes[CharacterCodes["W"] = 87] = "W";
  4320. CharacterCodes[CharacterCodes["X"] = 88] = "X";
  4321. CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
  4322. CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
  4323. CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
  4324. CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
  4325. CharacterCodes[CharacterCodes["at"] = 64] = "at";
  4326. CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
  4327. CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
  4328. CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
  4329. CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
  4330. CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
  4331. CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
  4332. CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
  4333. CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
  4334. CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
  4335. CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
  4336. CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
  4337. CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
  4338. CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
  4339. CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
  4340. CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
  4341. CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
  4342. CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
  4343. CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
  4344. CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
  4345. CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
  4346. CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
  4347. CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
  4348. CharacterCodes[CharacterCodes["question"] = 63] = "question";
  4349. CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
  4350. CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
  4351. CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
  4352. CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
  4353. CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
  4354. CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
  4355. CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
  4356. CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
  4357. CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
  4358. })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
  4359. var Extension;
  4360. (function (Extension) {
  4361. Extension["Ts"] = ".ts";
  4362. Extension["Tsx"] = ".tsx";
  4363. Extension["Dts"] = ".d.ts";
  4364. Extension["Js"] = ".js";
  4365. Extension["Jsx"] = ".jsx";
  4366. Extension["Json"] = ".json";
  4367. Extension["TsBuildInfo"] = ".tsbuildinfo";
  4368. })(Extension = ts.Extension || (ts.Extension = {}));
  4369. /* @internal */
  4370. var TransformFlags;
  4371. (function (TransformFlags) {
  4372. TransformFlags[TransformFlags["None"] = 0] = "None";
  4373. // Facts
  4374. // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
  4375. TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
  4376. TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
  4377. TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
  4378. TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
  4379. TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
  4380. TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
  4381. TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
  4382. TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
  4383. TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
  4384. TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
  4385. TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
  4386. // Markers
  4387. // - Flags used to indicate that a subtree contains a specific transformation.
  4388. TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
  4389. TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
  4390. TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
  4391. TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
  4392. TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
  4393. TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
  4394. TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
  4395. TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
  4396. TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
  4397. TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
  4398. TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
  4399. TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
  4400. // Please leave this as 1 << 29.
  4401. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
  4402. // It is a good reminder of how much room we have left
  4403. TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
  4404. // Assertions
  4405. // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
  4406. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
  4407. TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
  4408. TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
  4409. TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
  4410. TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
  4411. TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
  4412. TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
  4413. TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
  4414. TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
  4415. TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
  4416. TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
  4417. // Scope Exclusions
  4418. // - Bitmasks that exclude flags from propagating out of a specific context
  4419. // into the subtree flags of their container.
  4420. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
  4421. TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
  4422. TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
  4423. TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
  4424. TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
  4425. TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
  4426. TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
  4427. TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
  4428. TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
  4429. TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
  4430. TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
  4431. TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
  4432. TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
  4433. TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
  4434. TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
  4435. TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
  4436. TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
  4437. // Propagating flags
  4438. // - Bitmasks for flags that should propagate from a child
  4439. TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
  4440. // Masks
  4441. // - Additional bitmasks
  4442. })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
  4443. var EmitFlags;
  4444. (function (EmitFlags) {
  4445. EmitFlags[EmitFlags["None"] = 0] = "None";
  4446. EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
  4447. EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
  4448. EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
  4449. EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
  4450. EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
  4451. EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
  4452. EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
  4453. EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
  4454. EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
  4455. EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
  4456. EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
  4457. EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
  4458. EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
  4459. EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
  4460. EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
  4461. EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
  4462. EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
  4463. EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
  4464. EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
  4465. EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
  4466. EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
  4467. EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
  4468. EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
  4469. EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
  4470. EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
  4471. EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
  4472. EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
  4473. EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
  4474. /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
  4475. /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
  4476. })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
  4477. /**
  4478. * Used by the checker, this enum keeps track of external emit helpers that should be type
  4479. * checked.
  4480. */
  4481. /* @internal */
  4482. var ExternalEmitHelpers;
  4483. (function (ExternalEmitHelpers) {
  4484. ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
  4485. ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
  4486. ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
  4487. ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
  4488. ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
  4489. ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
  4490. ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
  4491. ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
  4492. ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
  4493. ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
  4494. ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
  4495. ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
  4496. ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
  4497. ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
  4498. ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
  4499. ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
  4500. ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
  4501. ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
  4502. ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
  4503. ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
  4504. ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
  4505. ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 524288] = "LastEmitHelper";
  4506. // Helpers included by ES2015 for..of
  4507. ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
  4508. // Helpers included by ES2017 for..await..of
  4509. ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
  4510. // Helpers included by ES2017 async generators
  4511. ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
  4512. // Helpers included by yield* in ES2017 async generators
  4513. ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
  4514. // Helpers included by ES2015 spread
  4515. ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
  4516. })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
  4517. var EmitHint;
  4518. (function (EmitHint) {
  4519. EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
  4520. EmitHint[EmitHint["Expression"] = 1] = "Expression";
  4521. EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
  4522. EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
  4523. EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
  4524. EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
  4525. EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
  4526. })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
  4527. /*@internal*/
  4528. var BundleFileSectionKind;
  4529. (function (BundleFileSectionKind) {
  4530. BundleFileSectionKind["Prologue"] = "prologue";
  4531. BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
  4532. BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
  4533. BundleFileSectionKind["Reference"] = "reference";
  4534. BundleFileSectionKind["Type"] = "type";
  4535. BundleFileSectionKind["Lib"] = "lib";
  4536. BundleFileSectionKind["Prepend"] = "prepend";
  4537. BundleFileSectionKind["Text"] = "text";
  4538. BundleFileSectionKind["Internal"] = "internal";
  4539. // comments?
  4540. })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
  4541. var ListFormat;
  4542. (function (ListFormat) {
  4543. ListFormat[ListFormat["None"] = 0] = "None";
  4544. // Line separators
  4545. ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
  4546. ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
  4547. ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
  4548. ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
  4549. // Delimiters
  4550. ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
  4551. ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
  4552. ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
  4553. ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
  4554. ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
  4555. ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
  4556. ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
  4557. // Whitespace
  4558. ListFormat[ListFormat["Indented"] = 128] = "Indented";
  4559. ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
  4560. ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
  4561. // Brackets/Braces
  4562. ListFormat[ListFormat["Braces"] = 1024] = "Braces";
  4563. ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
  4564. ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
  4565. ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
  4566. ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
  4567. ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
  4568. ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
  4569. ListFormat[ListFormat["Optional"] = 49152] = "Optional";
  4570. // Other
  4571. ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
  4572. ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
  4573. ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
  4574. ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
  4575. ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
  4576. // Precomputed Formats
  4577. ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
  4578. ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
  4579. ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
  4580. ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
  4581. ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
  4582. ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
  4583. ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
  4584. ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
  4585. ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
  4586. ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
  4587. ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
  4588. ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
  4589. ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
  4590. ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
  4591. ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
  4592. ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
  4593. ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
  4594. ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
  4595. ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
  4596. ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
  4597. ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
  4598. ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
  4599. ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
  4600. ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
  4601. ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
  4602. ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
  4603. ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
  4604. ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
  4605. ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
  4606. ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
  4607. ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
  4608. ListFormat[ListFormat["Decorators"] = 49153] = "Decorators";
  4609. ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
  4610. ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
  4611. ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
  4612. ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
  4613. ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
  4614. })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
  4615. /* @internal */
  4616. var PragmaKindFlags;
  4617. (function (PragmaKindFlags) {
  4618. PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
  4619. /**
  4620. * Triple slash comment of the form
  4621. * /// <pragma-name argname="value" />
  4622. */
  4623. PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
  4624. /**
  4625. * Single line comment of the form
  4626. * // @pragma-name argval1 argval2
  4627. * or
  4628. * /// @pragma-name argval1 argval2
  4629. */
  4630. PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
  4631. /**
  4632. * Multiline non-jsdoc pragma of the form
  4633. * /* @pragma-name argval1 argval2 * /
  4634. */
  4635. PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
  4636. PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
  4637. PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
  4638. })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
  4639. // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
  4640. // fancy effectively defining it twice, once in value-space and once in type-space
  4641. /* @internal */
  4642. ts.commentPragmas = {
  4643. "reference": {
  4644. args: [
  4645. { name: "types", optional: true, captureSpan: true },
  4646. { name: "lib", optional: true, captureSpan: true },
  4647. { name: "path", optional: true, captureSpan: true },
  4648. { name: "no-default-lib", optional: true }
  4649. ],
  4650. kind: 1 /* TripleSlashXML */
  4651. },
  4652. "amd-dependency": {
  4653. args: [{ name: "path" }, { name: "name", optional: true }],
  4654. kind: 1 /* TripleSlashXML */
  4655. },
  4656. "amd-module": {
  4657. args: [{ name: "name" }],
  4658. kind: 1 /* TripleSlashXML */
  4659. },
  4660. "ts-check": {
  4661. kind: 2 /* SingleLine */
  4662. },
  4663. "ts-nocheck": {
  4664. kind: 2 /* SingleLine */
  4665. },
  4666. "jsx": {
  4667. args: [{ name: "factory" }],
  4668. kind: 4 /* MultiLine */
  4669. },
  4670. };
  4671. })(ts || (ts = {}));
  4672. var ts;
  4673. (function (ts) {
  4674. /**
  4675. * djb2 hashing algorithm
  4676. * http://www.cse.yorku.ca/~oz/hash.html
  4677. */
  4678. /* @internal */
  4679. function generateDjb2Hash(data) {
  4680. var acc = 5381;
  4681. for (var i = 0; i < data.length; i++) {
  4682. acc = ((acc << 5) + acc) + data.charCodeAt(i);
  4683. }
  4684. return acc.toString();
  4685. }
  4686. ts.generateDjb2Hash = generateDjb2Hash;
  4687. /**
  4688. * Set a high stack trace limit to provide more information in case of an error.
  4689. * Called for command-line and server use cases.
  4690. * Not called if TypeScript is used as a library.
  4691. */
  4692. /* @internal */
  4693. function setStackTraceLimit() {
  4694. if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
  4695. Error.stackTraceLimit = 100;
  4696. }
  4697. }
  4698. ts.setStackTraceLimit = setStackTraceLimit;
  4699. var FileWatcherEventKind;
  4700. (function (FileWatcherEventKind) {
  4701. FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
  4702. FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
  4703. FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
  4704. })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
  4705. /* @internal */
  4706. var PollingInterval;
  4707. (function (PollingInterval) {
  4708. PollingInterval[PollingInterval["High"] = 2000] = "High";
  4709. PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
  4710. PollingInterval[PollingInterval["Low"] = 250] = "Low";
  4711. })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
  4712. /* @internal */
  4713. ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
  4714. function createPollingIntervalBasedLevels(levels) {
  4715. var _a;
  4716. return _a = {},
  4717. _a[PollingInterval.Low] = levels.Low,
  4718. _a[PollingInterval.Medium] = levels.Medium,
  4719. _a[PollingInterval.High] = levels.High,
  4720. _a;
  4721. }
  4722. var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
  4723. var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
  4724. /* @internal */
  4725. ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
  4726. /* @internal */
  4727. function setCustomPollingValues(system) {
  4728. if (!system.getEnvironmentVariable) {
  4729. return;
  4730. }
  4731. var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
  4732. pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
  4733. ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
  4734. function getLevel(envVar, level) {
  4735. return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
  4736. }
  4737. function getCustomLevels(baseVariable) {
  4738. var customLevels;
  4739. setCustomLevel("Low");
  4740. setCustomLevel("Medium");
  4741. setCustomLevel("High");
  4742. return customLevels;
  4743. function setCustomLevel(level) {
  4744. var customLevel = getLevel(baseVariable, level);
  4745. if (customLevel) {
  4746. (customLevels || (customLevels = {}))[level] = Number(customLevel);
  4747. }
  4748. }
  4749. }
  4750. function setCustomLevels(baseVariable, levels) {
  4751. var customLevels = getCustomLevels(baseVariable);
  4752. if (customLevels) {
  4753. setLevel("Low");
  4754. setLevel("Medium");
  4755. setLevel("High");
  4756. return true;
  4757. }
  4758. return false;
  4759. function setLevel(level) {
  4760. levels[level] = customLevels[level] || levels[level];
  4761. }
  4762. }
  4763. function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
  4764. var customLevels = getCustomLevels(baseVariable);
  4765. return (pollingIntervalChanged || customLevels) &&
  4766. createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
  4767. }
  4768. }
  4769. ts.setCustomPollingValues = setCustomPollingValues;
  4770. /* @internal */
  4771. function createDynamicPriorityPollingWatchFile(host) {
  4772. var watchedFiles = [];
  4773. var changedFilesInLastPoll = [];
  4774. var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
  4775. var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
  4776. var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
  4777. return watchFile;
  4778. function watchFile(fileName, callback, defaultPollingInterval) {
  4779. var file = {
  4780. fileName: fileName,
  4781. callback: callback,
  4782. unchangedPolls: 0,
  4783. mtime: getModifiedTime(fileName)
  4784. };
  4785. watchedFiles.push(file);
  4786. addToPollingIntervalQueue(file, defaultPollingInterval);
  4787. return {
  4788. close: function () {
  4789. file.isClosed = true;
  4790. // Remove from watchedFiles
  4791. ts.unorderedRemoveItem(watchedFiles, file);
  4792. // Do not update polling interval queue since that will happen as part of polling
  4793. }
  4794. };
  4795. }
  4796. function createPollingIntervalQueue(pollingInterval) {
  4797. var queue = [];
  4798. queue.pollingInterval = pollingInterval;
  4799. queue.pollIndex = 0;
  4800. queue.pollScheduled = false;
  4801. return queue;
  4802. }
  4803. function pollPollingIntervalQueue(queue) {
  4804. queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
  4805. // Set the next polling index and timeout
  4806. if (queue.length) {
  4807. scheduleNextPoll(queue.pollingInterval);
  4808. }
  4809. else {
  4810. ts.Debug.assert(queue.pollIndex === 0);
  4811. queue.pollScheduled = false;
  4812. }
  4813. }
  4814. function pollLowPollingIntervalQueue(queue) {
  4815. // Always poll complete list of changedFilesInLastPoll
  4816. pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
  4817. // Finally do the actual polling of the queue
  4818. pollPollingIntervalQueue(queue);
  4819. // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
  4820. // as pollPollingIntervalQueue wont schedule for next poll
  4821. if (!queue.pollScheduled && changedFilesInLastPoll.length) {
  4822. scheduleNextPoll(PollingInterval.Low);
  4823. }
  4824. }
  4825. function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
  4826. // Max visit would be all elements of the queue
  4827. var needsVisit = queue.length;
  4828. var definedValueCopyToIndex = pollIndex;
  4829. for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
  4830. var watchedFile = queue[pollIndex];
  4831. if (!watchedFile) {
  4832. continue;
  4833. }
  4834. else if (watchedFile.isClosed) {
  4835. queue[pollIndex] = undefined;
  4836. continue;
  4837. }
  4838. polled++;
  4839. var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
  4840. if (watchedFile.isClosed) {
  4841. // Closed watcher as part of callback
  4842. queue[pollIndex] = undefined;
  4843. }
  4844. else if (fileChanged) {
  4845. watchedFile.unchangedPolls = 0;
  4846. // Changed files go to changedFilesInLastPoll queue
  4847. if (queue !== changedFilesInLastPoll) {
  4848. queue[pollIndex] = undefined;
  4849. addChangedFileToLowPollingIntervalQueue(watchedFile);
  4850. }
  4851. }
  4852. else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
  4853. watchedFile.unchangedPolls++;
  4854. }
  4855. else if (queue === changedFilesInLastPoll) {
  4856. // Restart unchangedPollCount for unchanged file and move to low polling interval queue
  4857. watchedFile.unchangedPolls = 1;
  4858. queue[pollIndex] = undefined;
  4859. addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
  4860. }
  4861. else if (pollingInterval !== PollingInterval.High) {
  4862. watchedFile.unchangedPolls++;
  4863. queue[pollIndex] = undefined;
  4864. addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
  4865. }
  4866. if (queue[pollIndex]) {
  4867. // Copy this file to the non hole location
  4868. if (definedValueCopyToIndex < pollIndex) {
  4869. queue[definedValueCopyToIndex] = watchedFile;
  4870. queue[pollIndex] = undefined;
  4871. }
  4872. definedValueCopyToIndex++;
  4873. }
  4874. }
  4875. // Return next poll index
  4876. return pollIndex;
  4877. function nextPollIndex() {
  4878. pollIndex++;
  4879. if (pollIndex === queue.length) {
  4880. if (definedValueCopyToIndex < pollIndex) {
  4881. // There are holes from nextDefinedValueIndex to end of queue, change queue size
  4882. queue.length = definedValueCopyToIndex;
  4883. }
  4884. pollIndex = 0;
  4885. definedValueCopyToIndex = 0;
  4886. }
  4887. }
  4888. }
  4889. function pollingIntervalQueue(pollingInterval) {
  4890. switch (pollingInterval) {
  4891. case PollingInterval.Low:
  4892. return lowPollingIntervalQueue;
  4893. case PollingInterval.Medium:
  4894. return mediumPollingIntervalQueue;
  4895. case PollingInterval.High:
  4896. return highPollingIntervalQueue;
  4897. }
  4898. }
  4899. function addToPollingIntervalQueue(file, pollingInterval) {
  4900. pollingIntervalQueue(pollingInterval).push(file);
  4901. scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
  4902. }
  4903. function addChangedFileToLowPollingIntervalQueue(file) {
  4904. changedFilesInLastPoll.push(file);
  4905. scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
  4906. }
  4907. function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
  4908. if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
  4909. scheduleNextPoll(pollingInterval);
  4910. }
  4911. }
  4912. function scheduleNextPoll(pollingInterval) {
  4913. pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
  4914. }
  4915. function getModifiedTime(fileName) {
  4916. return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
  4917. }
  4918. }
  4919. ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
  4920. function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
  4921. // One file can have multiple watchers
  4922. var fileWatcherCallbacks = ts.createMultiMap();
  4923. var dirWatchers = ts.createMap();
  4924. var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  4925. return nonPollingWatchFile;
  4926. function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
  4927. var filePath = toCanonicalName(fileName);
  4928. fileWatcherCallbacks.add(filePath, callback);
  4929. var dirPath = ts.getDirectoryPath(filePath) || ".";
  4930. var watcher = dirWatchers.get(dirPath) ||
  4931. createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
  4932. watcher.referenceCount++;
  4933. return {
  4934. close: function () {
  4935. if (watcher.referenceCount === 1) {
  4936. watcher.close();
  4937. dirWatchers.delete(dirPath);
  4938. }
  4939. else {
  4940. watcher.referenceCount--;
  4941. }
  4942. fileWatcherCallbacks.remove(filePath, callback);
  4943. }
  4944. };
  4945. }
  4946. function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
  4947. var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
  4948. // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
  4949. if (!ts.isString(relativeFileName)) {
  4950. return;
  4951. }
  4952. var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
  4953. // Some applications save a working file via rename operations
  4954. var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
  4955. if (callbacks) {
  4956. for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
  4957. var fileCallback = callbacks_1[_i];
  4958. fileCallback(fileName, FileWatcherEventKind.Changed);
  4959. }
  4960. }
  4961. },
  4962. /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
  4963. watcher.referenceCount = 0;
  4964. dirWatchers.set(dirPath, watcher);
  4965. return watcher;
  4966. }
  4967. }
  4968. /* @internal */
  4969. function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
  4970. var cache = ts.createMap();
  4971. var callbacksCache = ts.createMultiMap();
  4972. var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  4973. return function (fileName, callback, pollingInterval, options) {
  4974. var path = toCanonicalFileName(fileName);
  4975. var existing = cache.get(path);
  4976. if (existing) {
  4977. existing.refCount++;
  4978. }
  4979. else {
  4980. cache.set(path, {
  4981. watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
  4982. refCount: 1
  4983. });
  4984. }
  4985. callbacksCache.add(path, callback);
  4986. return {
  4987. close: function () {
  4988. var watcher = ts.Debug.assertDefined(cache.get(path));
  4989. callbacksCache.remove(path, callback);
  4990. watcher.refCount--;
  4991. if (watcher.refCount)
  4992. return;
  4993. cache.delete(path);
  4994. ts.closeFileWatcherOf(watcher);
  4995. }
  4996. };
  4997. };
  4998. }
  4999. ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
  5000. /**
  5001. * Returns true if file status changed
  5002. */
  5003. /*@internal*/
  5004. function onWatchedFileStat(watchedFile, modifiedTime) {
  5005. var oldTime = watchedFile.mtime.getTime();
  5006. var newTime = modifiedTime.getTime();
  5007. if (oldTime !== newTime) {
  5008. watchedFile.mtime = modifiedTime;
  5009. watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
  5010. return true;
  5011. }
  5012. return false;
  5013. }
  5014. ts.onWatchedFileStat = onWatchedFileStat;
  5015. /*@internal*/
  5016. function getFileWatcherEventKind(oldTime, newTime) {
  5017. return oldTime === 0
  5018. ? FileWatcherEventKind.Created
  5019. : newTime === 0
  5020. ? FileWatcherEventKind.Deleted
  5021. : FileWatcherEventKind.Changed;
  5022. }
  5023. ts.getFileWatcherEventKind = getFileWatcherEventKind;
  5024. /*@internal*/
  5025. ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
  5026. /*@internal*/
  5027. ts.sysLog = ts.noop; // eslint-disable-line prefer-const
  5028. /*@internal*/
  5029. function setSysLog(logger) {
  5030. ts.sysLog = logger;
  5031. }
  5032. ts.setSysLog = setSysLog;
  5033. /**
  5034. * Watch the directory recursively using host provided method to watch child directories
  5035. * that means if this is recursive watcher, watch the children directories as well
  5036. * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
  5037. */
  5038. /*@internal*/
  5039. function createDirectoryWatcherSupportingRecursive(host) {
  5040. var cache = ts.createMap();
  5041. var callbackCache = ts.createMultiMap();
  5042. var cacheToUpdateChildWatches = ts.createMap();
  5043. var timerToUpdateChildWatches;
  5044. var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
  5045. var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  5046. return function (dirName, callback, recursive, options) { return recursive ?
  5047. createDirectoryWatcher(dirName, options, callback) :
  5048. host.watchDirectory(dirName, callback, recursive, options); };
  5049. /**
  5050. * Create the directory watcher for the dirPath.
  5051. */
  5052. function createDirectoryWatcher(dirName, options, callback) {
  5053. var dirPath = toCanonicalFilePath(dirName);
  5054. var directoryWatcher = cache.get(dirPath);
  5055. if (directoryWatcher) {
  5056. directoryWatcher.refCount++;
  5057. }
  5058. else {
  5059. directoryWatcher = {
  5060. watcher: host.watchDirectory(dirName, function (fileName) {
  5061. if (isIgnoredPath(fileName))
  5062. return;
  5063. if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
  5064. // Call the actual callback
  5065. invokeCallbacks(dirPath, fileName);
  5066. // Iterate through existing children and update the watches if needed
  5067. updateChildWatches(dirName, dirPath, options);
  5068. }
  5069. else {
  5070. nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
  5071. }
  5072. }, /*recursive*/ false, options),
  5073. refCount: 1,
  5074. childWatches: ts.emptyArray
  5075. };
  5076. cache.set(dirPath, directoryWatcher);
  5077. updateChildWatches(dirName, dirPath, options);
  5078. }
  5079. var callbackToAdd = callback && { dirName: dirName, callback: callback };
  5080. if (callbackToAdd) {
  5081. callbackCache.add(dirPath, callbackToAdd);
  5082. }
  5083. return {
  5084. dirName: dirName,
  5085. close: function () {
  5086. var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath));
  5087. if (callbackToAdd)
  5088. callbackCache.remove(dirPath, callbackToAdd);
  5089. directoryWatcher.refCount--;
  5090. if (directoryWatcher.refCount)
  5091. return;
  5092. cache.delete(dirPath);
  5093. ts.closeFileWatcherOf(directoryWatcher);
  5094. directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
  5095. }
  5096. };
  5097. }
  5098. function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
  5099. var fileName;
  5100. var invokeMap;
  5101. if (ts.isString(fileNameOrInvokeMap)) {
  5102. fileName = fileNameOrInvokeMap;
  5103. }
  5104. else {
  5105. invokeMap = fileNameOrInvokeMap;
  5106. }
  5107. // Call the actual callback
  5108. callbackCache.forEach(function (callbacks, rootDirName) {
  5109. if (invokeMap && invokeMap.has(rootDirName))
  5110. return;
  5111. if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
  5112. if (invokeMap) {
  5113. invokeMap.set(rootDirName, true);
  5114. }
  5115. else {
  5116. callbacks.forEach(function (_a) {
  5117. var callback = _a.callback;
  5118. return callback(fileName);
  5119. });
  5120. }
  5121. }
  5122. });
  5123. }
  5124. function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
  5125. // Iterate through existing children and update the watches if needed
  5126. var parentWatcher = cache.get(dirPath);
  5127. if (parentWatcher && host.directoryExists(dirName)) {
  5128. // Schedule the update and postpone invoke for callbacks
  5129. scheduleUpdateChildWatches(dirName, dirPath, options);
  5130. return;
  5131. }
  5132. // Call the actual callbacks and remove child watches
  5133. invokeCallbacks(dirPath, fileName);
  5134. removeChildWatches(parentWatcher);
  5135. }
  5136. function scheduleUpdateChildWatches(dirName, dirPath, options) {
  5137. if (!cacheToUpdateChildWatches.has(dirPath)) {
  5138. cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
  5139. }
  5140. if (timerToUpdateChildWatches) {
  5141. host.clearTimeout(timerToUpdateChildWatches);
  5142. timerToUpdateChildWatches = undefined;
  5143. }
  5144. timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
  5145. }
  5146. function onTimerToUpdateChildWatches() {
  5147. timerToUpdateChildWatches = undefined;
  5148. ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
  5149. var start = ts.timestamp();
  5150. var invokeMap = ts.createMap();
  5151. while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
  5152. var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
  5153. ts.Debug.assert(!done);
  5154. cacheToUpdateChildWatches.delete(dirPath);
  5155. // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
  5156. // to ensure that all the changes are reflected at this time
  5157. invokeCallbacks(dirPath, invokeMap);
  5158. updateChildWatches(dirName, dirPath, options);
  5159. }
  5160. ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
  5161. callbackCache.forEach(function (callbacks, rootDirName) {
  5162. if (invokeMap.has(rootDirName)) {
  5163. callbacks.forEach(function (_a) {
  5164. var callback = _a.callback, dirName = _a.dirName;
  5165. return callback(dirName);
  5166. });
  5167. }
  5168. });
  5169. var elapsed = ts.timestamp() - start;
  5170. ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
  5171. }
  5172. function removeChildWatches(parentWatcher) {
  5173. if (!parentWatcher)
  5174. return;
  5175. var existingChildWatches = parentWatcher.childWatches;
  5176. parentWatcher.childWatches = ts.emptyArray;
  5177. for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
  5178. var childWatcher = existingChildWatches_1[_i];
  5179. childWatcher.close();
  5180. removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
  5181. }
  5182. }
  5183. function updateChildWatches(dirName, dirPath, options) {
  5184. // Iterate through existing children and update the watches if needed
  5185. var parentWatcher = cache.get(dirPath);
  5186. if (parentWatcher) {
  5187. parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
  5188. }
  5189. }
  5190. /**
  5191. * Watch the directories in the parentDir
  5192. */
  5193. function watchChildDirectories(parentDir, existingChildWatches, options) {
  5194. var newChildWatches;
  5195. ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
  5196. var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
  5197. // Filter our the symbolic link directories since those arent included in recursive watch
  5198. // which is same behaviour when recursive: true is passed to fs.watch
  5199. return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
  5200. }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
  5201. return newChildWatches || ts.emptyArray;
  5202. /**
  5203. * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
  5204. */
  5205. function createAndAddChildDirectoryWatcher(childName) {
  5206. var result = createDirectoryWatcher(childName, options);
  5207. addChildDirectoryWatcher(result);
  5208. }
  5209. /**
  5210. * Add child directory watcher to the new ChildDirectoryWatcher list
  5211. */
  5212. function addChildDirectoryWatcher(childWatcher) {
  5213. (newChildWatches || (newChildWatches = [])).push(childWatcher);
  5214. }
  5215. }
  5216. function isIgnoredPath(path) {
  5217. return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
  5218. }
  5219. function isInPath(path, searchPath) {
  5220. if (ts.stringContains(path, searchPath))
  5221. return true;
  5222. if (host.useCaseSensitiveFileNames)
  5223. return false;
  5224. return ts.stringContains(toCanonicalFilePath(path), searchPath);
  5225. }
  5226. }
  5227. ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
  5228. /*@internal*/
  5229. var FileSystemEntryKind;
  5230. (function (FileSystemEntryKind) {
  5231. FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
  5232. FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
  5233. })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
  5234. /*@internal*/
  5235. function createFileWatcherCallback(callback) {
  5236. return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
  5237. }
  5238. ts.createFileWatcherCallback = createFileWatcherCallback;
  5239. function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
  5240. return function (eventName) {
  5241. if (eventName === "rename") {
  5242. callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
  5243. }
  5244. else {
  5245. // Change
  5246. callback(fileName, FileWatcherEventKind.Changed);
  5247. }
  5248. };
  5249. }
  5250. function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
  5251. return function (eventName, relativeFileName) {
  5252. // In watchDirectory we only care about adding and removing files (when event name is
  5253. // "rename"); changes made within files are handled by corresponding fileWatchers (when
  5254. // event name is "change")
  5255. if (eventName === "rename") {
  5256. // When deleting a file, the passed baseFileName is null
  5257. callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
  5258. }
  5259. };
  5260. }
  5261. /*@internal*/
  5262. function createSystemWatchFunctions(_a) {
  5263. var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory;
  5264. var dynamicPollingWatchFile;
  5265. var nonPollingWatchFile;
  5266. var hostRecursiveDirectoryWatcher;
  5267. return {
  5268. watchFile: watchFile,
  5269. watchDirectory: watchDirectory
  5270. };
  5271. function watchFile(fileName, callback, pollingInterval, options) {
  5272. options = updateOptionsForWatchFile(options, useNonPollingWatchers);
  5273. var watchFileKind = ts.Debug.assertDefined(options.watchFile);
  5274. switch (watchFileKind) {
  5275. case ts.WatchFileKind.FixedPollingInterval:
  5276. return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
  5277. case ts.WatchFileKind.PriorityPollingInterval:
  5278. return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
  5279. case ts.WatchFileKind.DynamicPriorityPolling:
  5280. return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
  5281. case ts.WatchFileKind.UseFsEvents:
  5282. return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists),
  5283. /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
  5284. case ts.WatchFileKind.UseFsEventsOnParentDirectory:
  5285. if (!nonPollingWatchFile) {
  5286. nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
  5287. }
  5288. return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
  5289. default:
  5290. ts.Debug.assertNever(watchFileKind);
  5291. }
  5292. }
  5293. function ensureDynamicPollingWatchFile() {
  5294. return dynamicPollingWatchFile ||
  5295. (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
  5296. }
  5297. function updateOptionsForWatchFile(options, useNonPollingWatchers) {
  5298. if (options && options.watchFile !== undefined)
  5299. return options;
  5300. switch (tscWatchFile) {
  5301. case "PriorityPollingInterval":
  5302. // Use polling interval based on priority when create watch using host.watchFile
  5303. return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
  5304. case "DynamicPriorityPolling":
  5305. // Use polling interval but change the interval depending on file changes and their default polling interval
  5306. return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
  5307. case "UseFsEvents":
  5308. // Use notifications from FS to watch with falling back to fs.watchFile
  5309. return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
  5310. case "UseFsEventsWithFallbackDynamicPolling":
  5311. // Use notifications from FS to watch with falling back to dynamic watch file
  5312. return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
  5313. case "UseFsEventsOnParentDirectory":
  5314. useNonPollingWatchers = true;
  5315. // fall through
  5316. default:
  5317. return useNonPollingWatchers ?
  5318. // Use notifications from FS to watch with falling back to fs.watchFile
  5319. generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
  5320. // Default to do not use fixed polling interval
  5321. { watchFile: ts.WatchFileKind.FixedPollingInterval };
  5322. }
  5323. }
  5324. function generateWatchFileOptions(watchFile, fallbackPolling, options) {
  5325. var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
  5326. return {
  5327. watchFile: watchFile,
  5328. fallbackPolling: defaultFallbackPolling === undefined ?
  5329. fallbackPolling :
  5330. defaultFallbackPolling
  5331. };
  5332. }
  5333. function watchDirectory(directoryName, callback, recursive, options) {
  5334. if (fsSupportsRecursiveFsWatch) {
  5335. return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
  5336. }
  5337. if (!hostRecursiveDirectoryWatcher) {
  5338. hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
  5339. useCaseSensitiveFileNames: useCaseSensitiveFileNames,
  5340. directoryExists: directoryExists,
  5341. getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
  5342. watchDirectory: nonRecursiveWatchDirectory,
  5343. realpath: realpath,
  5344. setTimeout: setTimeout,
  5345. clearTimeout: clearTimeout
  5346. });
  5347. }
  5348. return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
  5349. }
  5350. function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
  5351. ts.Debug.assert(!recursive);
  5352. options = updateOptionsForWatchDirectory(options);
  5353. var watchDirectoryKind = ts.Debug.assertDefined(options.watchDirectory);
  5354. switch (watchDirectoryKind) {
  5355. case ts.WatchDirectoryKind.FixedPollingInterval:
  5356. return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
  5357. /*options*/ undefined);
  5358. case ts.WatchDirectoryKind.DynamicPriorityPolling:
  5359. return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium,
  5360. /*options*/ undefined);
  5361. case ts.WatchDirectoryKind.UseFsEvents:
  5362. return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
  5363. default:
  5364. ts.Debug.assertNever(watchDirectoryKind);
  5365. }
  5366. }
  5367. function updateOptionsForWatchDirectory(options) {
  5368. if (options && options.watchDirectory !== undefined)
  5369. return options;
  5370. switch (tscWatchDirectory) {
  5371. case "RecursiveDirectoryUsingFsWatchFile":
  5372. // Use polling interval based on priority when create watch using host.watchFile
  5373. return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
  5374. case "RecursiveDirectoryUsingDynamicPriorityPolling":
  5375. // Use polling interval but change the interval depending on file changes and their default polling interval
  5376. return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
  5377. default:
  5378. var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
  5379. return {
  5380. watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
  5381. fallbackPolling: defaultFallbackPolling !== undefined ?
  5382. defaultFallbackPolling :
  5383. undefined
  5384. };
  5385. }
  5386. }
  5387. }
  5388. ts.createSystemWatchFunctions = createSystemWatchFunctions;
  5389. /**
  5390. * patch writefile to create folder before writing the file
  5391. */
  5392. /*@internal*/
  5393. function patchWriteFileEnsuringDirectory(sys) {
  5394. // patch writefile to create folder before writing the file
  5395. var originalWriteFile = sys.writeFile;
  5396. sys.writeFile = function (path, data, writeBom) {
  5397. return ts.writeFileEnsuringDirectories(path, data, !!writeBom, function (path, data, writeByteOrderMark) { return originalWriteFile.call(sys, path, data, writeByteOrderMark); }, function (path) { return sys.createDirectory(path); }, function (path) { return sys.directoryExists(path); });
  5398. };
  5399. }
  5400. ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
  5401. function getNodeMajorVersion() {
  5402. if (typeof process === "undefined") {
  5403. return undefined;
  5404. }
  5405. var version = process.version;
  5406. if (!version) {
  5407. return undefined;
  5408. }
  5409. var dot = version.indexOf(".");
  5410. if (dot === -1) {
  5411. return undefined;
  5412. }
  5413. return parseInt(version.substring(1, dot));
  5414. }
  5415. ts.getNodeMajorVersion = getNodeMajorVersion;
  5416. // TODO: GH#18217 this is used as if it's certainly defined in many places.
  5417. // eslint-disable-next-line prefer-const
  5418. // MONACOCHANGE
  5419. ts.sys = undefined;
  5420. // END MONACOCHANGE
  5421. if (ts.sys && ts.sys.getEnvironmentVariable) {
  5422. setCustomPollingValues(ts.sys);
  5423. ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
  5424. ? 1 /* Normal */
  5425. : 0 /* None */;
  5426. }
  5427. if (ts.sys && ts.sys.debugMode) {
  5428. ts.Debug.isDebugging = true;
  5429. }
  5430. })(ts || (ts = {}));
  5431. /* @internal */
  5432. var ts;
  5433. (function (ts) {
  5434. /**
  5435. * Internally, we represent paths as strings with '/' as the directory separator.
  5436. * When we make system calls (eg: LanguageServiceHost.getDirectory()),
  5437. * we expect the host to correctly handle paths in our specified format.
  5438. */
  5439. ts.directorySeparator = "/";
  5440. var altDirectorySeparator = "\\";
  5441. var urlSchemeSeparator = "://";
  5442. var backslashRegExp = /\\/g;
  5443. //// Path Tests
  5444. /**
  5445. * Determines whether a charCode corresponds to `/` or `\`.
  5446. */
  5447. function isAnyDirectorySeparator(charCode) {
  5448. return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
  5449. }
  5450. ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
  5451. /**
  5452. * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
  5453. */
  5454. function isUrl(path) {
  5455. return getEncodedRootLength(path) < 0;
  5456. }
  5457. ts.isUrl = isUrl;
  5458. /**
  5459. * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
  5460. * like `c:`, `c:\` or `c:/`).
  5461. */
  5462. function isRootedDiskPath(path) {
  5463. return getEncodedRootLength(path) > 0;
  5464. }
  5465. ts.isRootedDiskPath = isRootedDiskPath;
  5466. /**
  5467. * Determines whether a path consists only of a path root.
  5468. */
  5469. function isDiskPathRoot(path) {
  5470. var rootLength = getEncodedRootLength(path);
  5471. return rootLength > 0 && rootLength === path.length;
  5472. }
  5473. ts.isDiskPathRoot = isDiskPathRoot;
  5474. /**
  5475. * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
  5476. *
  5477. * ```ts
  5478. * // POSIX
  5479. * pathIsAbsolute("/path/to/file.ext") === true
  5480. * // DOS
  5481. * pathIsAbsolute("c:/path/to/file.ext") === true
  5482. * // URL
  5483. * pathIsAbsolute("file:///path/to/file.ext") === true
  5484. * // Non-absolute
  5485. * pathIsAbsolute("path/to/file.ext") === false
  5486. * pathIsAbsolute("./path/to/file.ext") === false
  5487. * ```
  5488. */
  5489. function pathIsAbsolute(path) {
  5490. return getEncodedRootLength(path) !== 0;
  5491. }
  5492. ts.pathIsAbsolute = pathIsAbsolute;
  5493. /**
  5494. * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
  5495. */
  5496. function pathIsRelative(path) {
  5497. return /^\.\.?($|[\\/])/.test(path);
  5498. }
  5499. ts.pathIsRelative = pathIsRelative;
  5500. function hasExtension(fileName) {
  5501. return ts.stringContains(getBaseFileName(fileName), ".");
  5502. }
  5503. ts.hasExtension = hasExtension;
  5504. function fileExtensionIs(path, extension) {
  5505. return path.length > extension.length && ts.endsWith(path, extension);
  5506. }
  5507. ts.fileExtensionIs = fileExtensionIs;
  5508. function fileExtensionIsOneOf(path, extensions) {
  5509. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  5510. var extension = extensions_1[_i];
  5511. if (fileExtensionIs(path, extension)) {
  5512. return true;
  5513. }
  5514. }
  5515. return false;
  5516. }
  5517. ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
  5518. /**
  5519. * Determines whether a path has a trailing separator (`/` or `\\`).
  5520. */
  5521. function hasTrailingDirectorySeparator(path) {
  5522. return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
  5523. }
  5524. ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
  5525. //// Path Parsing
  5526. function isVolumeCharacter(charCode) {
  5527. return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
  5528. (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
  5529. }
  5530. function getFileUrlVolumeSeparatorEnd(url, start) {
  5531. var ch0 = url.charCodeAt(start);
  5532. if (ch0 === 58 /* colon */)
  5533. return start + 1;
  5534. if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
  5535. var ch2 = url.charCodeAt(start + 2);
  5536. if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
  5537. return start + 3;
  5538. }
  5539. return -1;
  5540. }
  5541. /**
  5542. * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
  5543. * If the root is part of a URL, the twos-complement of the root length is returned.
  5544. */
  5545. function getEncodedRootLength(path) {
  5546. if (!path)
  5547. return 0;
  5548. var ch0 = path.charCodeAt(0);
  5549. // POSIX or UNC
  5550. if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
  5551. if (path.charCodeAt(1) !== ch0)
  5552. return 1; // POSIX: "/" (or non-normalized "\")
  5553. var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
  5554. if (p1 < 0)
  5555. return path.length; // UNC: "//server" or "\\server"
  5556. return p1 + 1; // UNC: "//server/" or "\\server\"
  5557. }
  5558. // DOS
  5559. if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
  5560. var ch2 = path.charCodeAt(2);
  5561. if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
  5562. return 3; // DOS: "c:/" or "c:\"
  5563. if (path.length === 2)
  5564. return 2; // DOS: "c:" (but not "c:d")
  5565. }
  5566. // URL
  5567. var schemeEnd = path.indexOf(urlSchemeSeparator);
  5568. if (schemeEnd !== -1) {
  5569. var authorityStart = schemeEnd + urlSchemeSeparator.length;
  5570. var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
  5571. if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
  5572. // For local "file" URLs, include the leading DOS volume (if present).
  5573. // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
  5574. // special case interpreted as "the machine from which the URL is being interpreted".
  5575. var scheme = path.slice(0, schemeEnd);
  5576. var authority = path.slice(authorityStart, authorityEnd);
  5577. if (scheme === "file" && (authority === "" || authority === "localhost") &&
  5578. isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
  5579. var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
  5580. if (volumeSeparatorEnd !== -1) {
  5581. if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
  5582. // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
  5583. return ~(volumeSeparatorEnd + 1);
  5584. }
  5585. if (volumeSeparatorEnd === path.length) {
  5586. // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
  5587. // but not "file:///c:d" or "file:///c%3ad"
  5588. return ~volumeSeparatorEnd;
  5589. }
  5590. }
  5591. }
  5592. return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
  5593. }
  5594. return ~path.length; // URL: "file://server", "http://server"
  5595. }
  5596. // relative
  5597. return 0;
  5598. }
  5599. /**
  5600. * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
  5601. *
  5602. * For example:
  5603. * ```ts
  5604. * getRootLength("a") === 0 // ""
  5605. * getRootLength("/") === 1 // "/"
  5606. * getRootLength("c:") === 2 // "c:"
  5607. * getRootLength("c:d") === 0 // ""
  5608. * getRootLength("c:/") === 3 // "c:/"
  5609. * getRootLength("c:\\") === 3 // "c:\\"
  5610. * getRootLength("//server") === 7 // "//server"
  5611. * getRootLength("//server/share") === 8 // "//server/"
  5612. * getRootLength("\\\\server") === 7 // "\\\\server"
  5613. * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
  5614. * getRootLength("file:///path") === 8 // "file:///"
  5615. * getRootLength("file:///c:") === 10 // "file:///c:"
  5616. * getRootLength("file:///c:d") === 8 // "file:///"
  5617. * getRootLength("file:///c:/path") === 11 // "file:///c:/"
  5618. * getRootLength("file://server") === 13 // "file://server"
  5619. * getRootLength("file://server/path") === 14 // "file://server/"
  5620. * getRootLength("http://server") === 13 // "http://server"
  5621. * getRootLength("http://server/path") === 14 // "http://server/"
  5622. * ```
  5623. */
  5624. function getRootLength(path) {
  5625. var rootLength = getEncodedRootLength(path);
  5626. return rootLength < 0 ? ~rootLength : rootLength;
  5627. }
  5628. ts.getRootLength = getRootLength;
  5629. function getDirectoryPath(path) {
  5630. path = normalizeSlashes(path);
  5631. // If the path provided is itself the root, then return it.
  5632. var rootLength = getRootLength(path);
  5633. if (rootLength === path.length)
  5634. return path;
  5635. // return the leading portion of the path up to the last (non-terminal) directory separator
  5636. // but not including any trailing directory separator.
  5637. path = removeTrailingDirectorySeparator(path);
  5638. return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
  5639. }
  5640. ts.getDirectoryPath = getDirectoryPath;
  5641. function getBaseFileName(path, extensions, ignoreCase) {
  5642. path = normalizeSlashes(path);
  5643. // if the path provided is itself the root, then it has not file name.
  5644. var rootLength = getRootLength(path);
  5645. if (rootLength === path.length)
  5646. return "";
  5647. // return the trailing portion of the path starting after the last (non-terminal) directory
  5648. // separator but not including any trailing directory separator.
  5649. path = removeTrailingDirectorySeparator(path);
  5650. var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
  5651. var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
  5652. return extension ? name.slice(0, name.length - extension.length) : name;
  5653. }
  5654. ts.getBaseFileName = getBaseFileName;
  5655. function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
  5656. if (!ts.startsWith(extension, "."))
  5657. extension = "." + extension;
  5658. if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
  5659. var pathExtension = path.slice(path.length - extension.length);
  5660. if (stringEqualityComparer(pathExtension, extension)) {
  5661. return pathExtension;
  5662. }
  5663. }
  5664. }
  5665. function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
  5666. if (typeof extensions === "string") {
  5667. return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
  5668. }
  5669. for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
  5670. var extension = extensions_2[_i];
  5671. var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
  5672. if (result)
  5673. return result;
  5674. }
  5675. return "";
  5676. }
  5677. function getAnyExtensionFromPath(path, extensions, ignoreCase) {
  5678. // Retrieves any string from the final "." onwards from a base file name.
  5679. // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
  5680. if (extensions) {
  5681. return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
  5682. }
  5683. var baseFileName = getBaseFileName(path);
  5684. var extensionIndex = baseFileName.lastIndexOf(".");
  5685. if (extensionIndex >= 0) {
  5686. return baseFileName.substring(extensionIndex);
  5687. }
  5688. return "";
  5689. }
  5690. ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
  5691. function pathComponents(path, rootLength) {
  5692. var root = path.substring(0, rootLength);
  5693. var rest = path.substring(rootLength).split(ts.directorySeparator);
  5694. if (rest.length && !ts.lastOrUndefined(rest))
  5695. rest.pop();
  5696. return __spreadArrays([root], rest);
  5697. }
  5698. /**
  5699. * Parse a path into an array containing a root component (at index 0) and zero or more path
  5700. * components (at indices > 0). The result is not normalized.
  5701. * If the path is relative, the root component is `""`.
  5702. * If the path is absolute, the root component includes the first path separator (`/`).
  5703. *
  5704. * ```ts
  5705. * // POSIX
  5706. * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
  5707. * getPathComponents("/path/to/") === ["/", "path", "to"]
  5708. * getPathComponents("/") === ["/"]
  5709. * // DOS
  5710. * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
  5711. * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
  5712. * getPathComponents("c:/") === ["c:/"]
  5713. * getPathComponents("c:") === ["c:"]
  5714. * // URL
  5715. * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
  5716. * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
  5717. * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
  5718. * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
  5719. * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
  5720. * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
  5721. * getPathComponents("file://server/") === ["file://server/"]
  5722. * getPathComponents("file://server") === ["file://server"]
  5723. * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
  5724. * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
  5725. * getPathComponents("file:///") === ["file:///"]
  5726. * getPathComponents("file://") === ["file://"]
  5727. */
  5728. function getPathComponents(path, currentDirectory) {
  5729. if (currentDirectory === void 0) { currentDirectory = ""; }
  5730. path = combinePaths(currentDirectory, path);
  5731. return pathComponents(path, getRootLength(path));
  5732. }
  5733. ts.getPathComponents = getPathComponents;
  5734. //// Path Formatting
  5735. /**
  5736. * Formats a parsed path consisting of a root component (at index 0) and zero or more path
  5737. * segments (at indices > 0).
  5738. *
  5739. * ```ts
  5740. * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
  5741. * ```
  5742. */
  5743. function getPathFromPathComponents(pathComponents) {
  5744. if (pathComponents.length === 0)
  5745. return "";
  5746. var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
  5747. return root + pathComponents.slice(1).join(ts.directorySeparator);
  5748. }
  5749. ts.getPathFromPathComponents = getPathFromPathComponents;
  5750. //// Path Normalization
  5751. /**
  5752. * Normalize path separators, converting `\` into `/`.
  5753. */
  5754. function normalizeSlashes(path) {
  5755. return path.replace(backslashRegExp, ts.directorySeparator);
  5756. }
  5757. ts.normalizeSlashes = normalizeSlashes;
  5758. /**
  5759. * Reduce an array of path components to a more simplified path by navigating any
  5760. * `"."` or `".."` entries in the path.
  5761. */
  5762. function reducePathComponents(components) {
  5763. if (!ts.some(components))
  5764. return [];
  5765. var reduced = [components[0]];
  5766. for (var i = 1; i < components.length; i++) {
  5767. var component = components[i];
  5768. if (!component)
  5769. continue;
  5770. if (component === ".")
  5771. continue;
  5772. if (component === "..") {
  5773. if (reduced.length > 1) {
  5774. if (reduced[reduced.length - 1] !== "..") {
  5775. reduced.pop();
  5776. continue;
  5777. }
  5778. }
  5779. else if (reduced[0])
  5780. continue;
  5781. }
  5782. reduced.push(component);
  5783. }
  5784. return reduced;
  5785. }
  5786. ts.reducePathComponents = reducePathComponents;
  5787. /**
  5788. * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
  5789. *
  5790. * ```ts
  5791. * // Non-rooted
  5792. * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
  5793. * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
  5794. * // POSIX
  5795. * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
  5796. * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
  5797. * // DOS
  5798. * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
  5799. * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
  5800. * // URL
  5801. * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
  5802. * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
  5803. * ```
  5804. */
  5805. function combinePaths(path) {
  5806. var paths = [];
  5807. for (var _i = 1; _i < arguments.length; _i++) {
  5808. paths[_i - 1] = arguments[_i];
  5809. }
  5810. if (path)
  5811. path = normalizeSlashes(path);
  5812. for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
  5813. var relativePath = paths_1[_a];
  5814. if (!relativePath)
  5815. continue;
  5816. relativePath = normalizeSlashes(relativePath);
  5817. if (!path || getRootLength(relativePath) !== 0) {
  5818. path = relativePath;
  5819. }
  5820. else {
  5821. path = ensureTrailingDirectorySeparator(path) + relativePath;
  5822. }
  5823. }
  5824. return path;
  5825. }
  5826. ts.combinePaths = combinePaths;
  5827. /**
  5828. * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
  5829. * `.` and `..` path components are resolved. Trailing directory separators are preserved.
  5830. *
  5831. * ```ts
  5832. * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
  5833. * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
  5834. * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
  5835. * ```
  5836. */
  5837. function resolvePath(path) {
  5838. var paths = [];
  5839. for (var _i = 1; _i < arguments.length; _i++) {
  5840. paths[_i - 1] = arguments[_i];
  5841. }
  5842. return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
  5843. }
  5844. ts.resolvePath = resolvePath;
  5845. /**
  5846. * Parse a path into an array containing a root component (at index 0) and zero or more path
  5847. * components (at indices > 0). The result is normalized.
  5848. * If the path is relative, the root component is `""`.
  5849. * If the path is absolute, the root component includes the first path separator (`/`).
  5850. *
  5851. * ```ts
  5852. * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
  5853. */
  5854. function getNormalizedPathComponents(path, currentDirectory) {
  5855. return reducePathComponents(getPathComponents(path, currentDirectory));
  5856. }
  5857. ts.getNormalizedPathComponents = getNormalizedPathComponents;
  5858. function getNormalizedAbsolutePath(fileName, currentDirectory) {
  5859. return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
  5860. }
  5861. ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
  5862. function normalizePath(path) {
  5863. path = normalizeSlashes(path);
  5864. var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
  5865. return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
  5866. }
  5867. ts.normalizePath = normalizePath;
  5868. function getPathWithoutRoot(pathComponents) {
  5869. if (pathComponents.length === 0)
  5870. return "";
  5871. return pathComponents.slice(1).join(ts.directorySeparator);
  5872. }
  5873. function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
  5874. return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
  5875. }
  5876. ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
  5877. function toPath(fileName, basePath, getCanonicalFileName) {
  5878. var nonCanonicalizedPath = isRootedDiskPath(fileName)
  5879. ? normalizePath(fileName)
  5880. : getNormalizedAbsolutePath(fileName, basePath);
  5881. return getCanonicalFileName(nonCanonicalizedPath);
  5882. }
  5883. ts.toPath = toPath;
  5884. function normalizePathAndParts(path) {
  5885. path = normalizeSlashes(path);
  5886. var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
  5887. if (parts.length) {
  5888. var joinedParts = root + parts.join(ts.directorySeparator);
  5889. return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
  5890. }
  5891. else {
  5892. return { path: root, parts: parts };
  5893. }
  5894. }
  5895. ts.normalizePathAndParts = normalizePathAndParts;
  5896. function removeTrailingDirectorySeparator(path) {
  5897. if (hasTrailingDirectorySeparator(path)) {
  5898. return path.substr(0, path.length - 1);
  5899. }
  5900. return path;
  5901. }
  5902. ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
  5903. function ensureTrailingDirectorySeparator(path) {
  5904. if (!hasTrailingDirectorySeparator(path)) {
  5905. return path + ts.directorySeparator;
  5906. }
  5907. return path;
  5908. }
  5909. ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
  5910. /**
  5911. * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
  5912. * with `./` or `../`) so as not to be confused with an unprefixed module name.
  5913. *
  5914. * ```ts
  5915. * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
  5916. * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
  5917. * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
  5918. * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
  5919. * ```
  5920. */
  5921. function ensurePathIsNonModuleName(path) {
  5922. return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
  5923. }
  5924. ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
  5925. function changeAnyExtension(path, ext, extensions, ignoreCase) {
  5926. var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
  5927. return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
  5928. }
  5929. ts.changeAnyExtension = changeAnyExtension;
  5930. //// Path Comparisons
  5931. // check path for these segments: '', '.'. '..'
  5932. var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
  5933. function comparePathsWorker(a, b, componentComparer) {
  5934. if (a === b)
  5935. return 0 /* EqualTo */;
  5936. if (a === undefined)
  5937. return -1 /* LessThan */;
  5938. if (b === undefined)
  5939. return 1 /* GreaterThan */;
  5940. // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
  5941. // need to perform path reduction.
  5942. var aRoot = a.substring(0, getRootLength(a));
  5943. var bRoot = b.substring(0, getRootLength(b));
  5944. var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
  5945. if (result !== 0 /* EqualTo */) {
  5946. return result;
  5947. }
  5948. // NOTE: Performance optimization - shortcut if there are no relative path segments in
  5949. // the non-root portion of the path
  5950. var aRest = a.substring(aRoot.length);
  5951. var bRest = b.substring(bRoot.length);
  5952. if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
  5953. return componentComparer(aRest, bRest);
  5954. }
  5955. // The path contains a relative path segment. Normalize the paths and perform a slower component
  5956. // by component comparison.
  5957. var aComponents = reducePathComponents(getPathComponents(a));
  5958. var bComponents = reducePathComponents(getPathComponents(b));
  5959. var sharedLength = Math.min(aComponents.length, bComponents.length);
  5960. for (var i = 1; i < sharedLength; i++) {
  5961. var result_1 = componentComparer(aComponents[i], bComponents[i]);
  5962. if (result_1 !== 0 /* EqualTo */) {
  5963. return result_1;
  5964. }
  5965. }
  5966. return ts.compareValues(aComponents.length, bComponents.length);
  5967. }
  5968. /**
  5969. * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
  5970. */
  5971. function comparePathsCaseSensitive(a, b) {
  5972. return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
  5973. }
  5974. ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
  5975. /**
  5976. * Performs a case-insensitive comparison of two paths.
  5977. */
  5978. function comparePathsCaseInsensitive(a, b) {
  5979. return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
  5980. }
  5981. ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
  5982. function comparePaths(a, b, currentDirectory, ignoreCase) {
  5983. if (typeof currentDirectory === "string") {
  5984. a = combinePaths(currentDirectory, a);
  5985. b = combinePaths(currentDirectory, b);
  5986. }
  5987. else if (typeof currentDirectory === "boolean") {
  5988. ignoreCase = currentDirectory;
  5989. }
  5990. return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
  5991. }
  5992. ts.comparePaths = comparePaths;
  5993. function containsPath(parent, child, currentDirectory, ignoreCase) {
  5994. if (typeof currentDirectory === "string") {
  5995. parent = combinePaths(currentDirectory, parent);
  5996. child = combinePaths(currentDirectory, child);
  5997. }
  5998. else if (typeof currentDirectory === "boolean") {
  5999. ignoreCase = currentDirectory;
  6000. }
  6001. if (parent === undefined || child === undefined)
  6002. return false;
  6003. if (parent === child)
  6004. return true;
  6005. var parentComponents = reducePathComponents(getPathComponents(parent));
  6006. var childComponents = reducePathComponents(getPathComponents(child));
  6007. if (childComponents.length < parentComponents.length) {
  6008. return false;
  6009. }
  6010. var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
  6011. for (var i = 0; i < parentComponents.length; i++) {
  6012. var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
  6013. if (!equalityComparer(parentComponents[i], childComponents[i])) {
  6014. return false;
  6015. }
  6016. }
  6017. return true;
  6018. }
  6019. ts.containsPath = containsPath;
  6020. /**
  6021. * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
  6022. * Comparison is case-sensitive between the canonical paths.
  6023. *
  6024. * @deprecated Use `containsPath` if possible.
  6025. */
  6026. function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
  6027. var canonicalFileName = getCanonicalFileName(fileName);
  6028. var canonicalDirectoryName = getCanonicalFileName(directoryName);
  6029. return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
  6030. }
  6031. ts.startsWithDirectory = startsWithDirectory;
  6032. //// Relative Paths
  6033. function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
  6034. var fromComponents = reducePathComponents(getPathComponents(from));
  6035. var toComponents = reducePathComponents(getPathComponents(to));
  6036. var start;
  6037. for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
  6038. var fromComponent = getCanonicalFileName(fromComponents[start]);
  6039. var toComponent = getCanonicalFileName(toComponents[start]);
  6040. var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
  6041. if (!comparer(fromComponent, toComponent))
  6042. break;
  6043. }
  6044. if (start === 0) {
  6045. return toComponents;
  6046. }
  6047. var components = toComponents.slice(start);
  6048. var relative = [];
  6049. for (; start < fromComponents.length; start++) {
  6050. relative.push("..");
  6051. }
  6052. return __spreadArrays([""], relative, components);
  6053. }
  6054. ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
  6055. function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
  6056. ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
  6057. var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
  6058. var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
  6059. var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
  6060. return getPathFromPathComponents(pathComponents);
  6061. }
  6062. ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
  6063. function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
  6064. return !isRootedDiskPath(absoluteOrRelativePath)
  6065. ? absoluteOrRelativePath
  6066. : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
  6067. }
  6068. ts.convertToRelativePath = convertToRelativePath;
  6069. function getRelativePathFromFile(from, to, getCanonicalFileName) {
  6070. return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
  6071. }
  6072. ts.getRelativePathFromFile = getRelativePathFromFile;
  6073. function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
  6074. var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
  6075. var firstComponent = pathComponents[0];
  6076. if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
  6077. var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
  6078. pathComponents[0] = prefix + firstComponent;
  6079. }
  6080. return getPathFromPathComponents(pathComponents);
  6081. }
  6082. ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
  6083. function forEachAncestorDirectory(directory, callback) {
  6084. while (true) {
  6085. var result = callback(directory);
  6086. if (result !== undefined) {
  6087. return result;
  6088. }
  6089. var parentPath = getDirectoryPath(directory);
  6090. if (parentPath === directory) {
  6091. return undefined;
  6092. }
  6093. directory = parentPath;
  6094. }
  6095. }
  6096. ts.forEachAncestorDirectory = forEachAncestorDirectory;
  6097. })(ts || (ts = {}));
  6098. // <auto-generated />
  6099. // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
  6100. /* @internal */
  6101. var ts;
  6102. (function (ts) {
  6103. function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
  6104. return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
  6105. }
  6106. ts.Diagnostics = {
  6107. Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
  6108. Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
  6109. _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
  6110. A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."),
  6111. The_parser_expected_to_find_a_to_match_the_token_here: diag(1007, ts.DiagnosticCategory.Error, "The_parser_expected_to_find_a_to_match_the_token_here_1007", "The parser expected to find a '}' to match the '{' token here."),
  6112. Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
  6113. Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
  6114. An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."),
  6115. Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
  6116. A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."),
  6117. A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."),
  6118. Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."),
  6119. A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."),
  6120. An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."),
  6121. An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."),
  6122. An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."),
  6123. An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."),
  6124. An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."),
  6125. An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."),
  6126. An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."),
  6127. readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."),
  6128. Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
  6129. _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
  6130. _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
  6131. _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."),
  6132. super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."),
  6133. Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."),
  6134. Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."),
  6135. A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."),
  6136. Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."),
  6137. _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."),
  6138. _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."),
  6139. _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
  6140. _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."),
  6141. _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."),
  6142. A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."),
  6143. Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier: diag(1046, ts.DiagnosticCategory.Error, "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046", "Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier."),
  6144. A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
  6145. A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."),
  6146. A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."),
  6147. A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."),
  6148. A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."),
  6149. A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."),
  6150. A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
  6151. Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."),
  6152. Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."),
  6153. An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."),
  6154. The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."),
  6155. A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."),
  6156. The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."),
  6157. Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
  6158. Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."),
  6159. An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."),
  6160. The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise<T> type."),
  6161. In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."),
  6162. Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."),
  6163. Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."),
  6164. _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."),
  6165. _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."),
  6166. A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."),
  6167. Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
  6168. Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."),
  6169. _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."),
  6170. _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."),
  6171. Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."),
  6172. Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."),
  6173. Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."),
  6174. An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
  6175. A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."),
  6176. An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."),
  6177. _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
  6178. Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
  6179. Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
  6180. Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."),
  6181. with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."),
  6182. delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."),
  6183. A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."),
  6184. A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."),
  6185. A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."),
  6186. Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
  6187. A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."),
  6188. Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
  6189. Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
  6190. A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."),
  6191. Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
  6192. A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."),
  6193. A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."),
  6194. An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."),
  6195. An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."),
  6196. An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."),
  6197. An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
  6198. Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."),
  6199. Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
  6200. Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
  6201. Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
  6202. Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
  6203. Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
  6204. Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
  6205. Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
  6206. case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
  6207. Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
  6208. Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
  6209. Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
  6210. Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
  6211. Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
  6212. Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
  6213. Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
  6214. Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
  6215. Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
  6216. String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
  6217. Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
  6218. or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
  6219. Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
  6220. Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."),
  6221. Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."),
  6222. File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."),
  6223. const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
  6224. const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."),
  6225. let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."),
  6226. Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
  6227. Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
  6228. An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."),
  6229. A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."),
  6230. Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."),
  6231. A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."),
  6232. A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."),
  6233. A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."),
  6234. A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."),
  6235. A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."),
  6236. A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."),
  6237. extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
  6238. extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
  6239. Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."),
  6240. implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
  6241. Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
  6242. Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
  6243. Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
  6244. Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
  6245. Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
  6246. Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
  6247. A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."),
  6248. An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."),
  6249. Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
  6250. Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
  6251. A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."),
  6252. A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."),
  6253. Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."),
  6254. The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."),
  6255. The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."),
  6256. An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
  6257. Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
  6258. An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
  6259. Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."),
  6260. Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."),
  6261. Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."),
  6262. An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."),
  6263. Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
  6264. Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
  6265. Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."),
  6266. Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."),
  6267. Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type: diag(1205, ts.DiagnosticCategory.Error, "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205", "Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'."),
  6268. Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
  6269. Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
  6270. All_files_must_be_modules_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "All_files_must_be_modules_when_the_isolatedModules_flag_is_provided_1208", "All files must be modules when the '--isolatedModules' flag is provided."),
  6271. Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
  6272. A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
  6273. Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
  6274. Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."),
  6275. Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."),
  6276. Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."),
  6277. Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."),
  6278. Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."),
  6279. Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning."),
  6280. Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."),
  6281. Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."),
  6282. An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."),
  6283. _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
  6284. Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."),
  6285. Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
  6286. Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."),
  6287. Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."),
  6288. A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."),
  6289. A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."),
  6290. A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."),
  6291. An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."),
  6292. An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."),
  6293. An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."),
  6294. An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."),
  6295. A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."),
  6296. The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."),
  6297. The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."),
  6298. Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."),
  6299. Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."),
  6300. Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."),
  6301. Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."),
  6302. abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."),
  6303. _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."),
  6304. Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."),
  6305. Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."),
  6306. An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."),
  6307. A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."),
  6308. A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."),
  6309. A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."),
  6310. Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."),
  6311. Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),
  6312. Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),
  6313. _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."),
  6314. A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),
  6315. A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."),
  6316. A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."),
  6317. A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."),
  6318. Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation: diag(1258, ts.DiagnosticCategory.Error, "Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation_1258", "Definite assignment assertions can only be used along with a type annotation."),
  6319. Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"),
  6320. Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
  6321. Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."),
  6322. with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."),
  6323. await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."),
  6324. can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."),
  6325. The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."),
  6326. Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."),
  6327. Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."),
  6328. Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."),
  6329. A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."),
  6330. An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."),
  6331. A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."),
  6332. Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
  6333. Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
  6334. Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
  6335. Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'."),
  6336. Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
  6337. Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
  6338. Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
  6339. String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
  6340. Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."),
  6341. _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"),
  6342. A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."),
  6343. A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."),
  6344. A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."),
  6345. unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."),
  6346. unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."),
  6347. unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."),
  6348. An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."),
  6349. An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."),
  6350. infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."),
  6351. Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."),
  6352. Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"),
  6353. Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
  6354. The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'esnext' or 'system'."),
  6355. A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
  6356. An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"),
  6357. This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."),
  6358. use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."),
  6359. Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
  6360. use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
  6361. Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."),
  6362. An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
  6363. A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
  6364. A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
  6365. readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
  6366. A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355", "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."),
  6367. Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"),
  6368. An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."),
  6369. Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."),
  6370. Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."),
  6371. Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"),
  6372. _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."),
  6373. _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."),
  6374. A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."),
  6375. Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
  6376. Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"),
  6377. Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
  6378. Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
  6379. Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"),
  6380. Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
  6381. Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."),
  6382. This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371", "This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'."),
  6383. Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
  6384. Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"),
  6385. await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."),
  6386. _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
  6387. _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
  6388. Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
  6389. An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."),
  6390. An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."),
  6391. Only_named_exports_may_use_export_type: diag(1383, ts.DiagnosticCategory.Error, "Only_named_exports_may_use_export_type_1383", "Only named exports may use 'export type'."),
  6392. The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."),
  6393. The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."),
  6394. Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
  6395. Construct_signature_return_types_0_and_1_are_incompatible: diag(2203, ts.DiagnosticCategory.Error, "Construct_signature_return_types_0_and_1_are_incompatible_2203", "Construct signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
  6396. Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2204, ts.DiagnosticCategory.Error, "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
  6397. Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true),
  6398. Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
  6399. Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),
  6400. Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."),
  6401. Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
  6402. Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
  6403. Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."),
  6404. File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
  6405. Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."),
  6406. Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."),
  6407. An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
  6408. Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
  6409. A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
  6410. An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
  6411. Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
  6412. Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
  6413. Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
  6414. Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."),
  6415. Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."),
  6416. Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
  6417. Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."),
  6418. Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."),
  6419. Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."),
  6420. Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."),
  6421. Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
  6422. Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."),
  6423. Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."),
  6424. Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
  6425. Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."),
  6426. Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."),
  6427. Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."),
  6428. Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
  6429. this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."),
  6430. this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."),
  6431. this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."),
  6432. this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."),
  6433. super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."),
  6434. super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."),
  6435. Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."),
  6436. super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."),
  6437. Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."),
  6438. Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."),
  6439. Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."),
  6440. An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."),
  6441. This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."),
  6442. Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."),
  6443. Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."),
  6444. Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."),
  6445. Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."),
  6446. Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"),
  6447. This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
  6448. Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."),
  6449. This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
  6450. Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."),
  6451. Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."),
  6452. This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."),
  6453. A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."),
  6454. An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."),
  6455. The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."),
  6456. The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."),
  6457. The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."),
  6458. The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."),
  6459. The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."),
  6460. The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
  6461. The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),
  6462. The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."),
  6463. Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."),
  6464. Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."),
  6465. This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."),
  6466. Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
  6467. A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."),
  6468. A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."),
  6469. A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."),
  6470. Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."),
  6471. Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."),
  6472. Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
  6473. Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
  6474. A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."),
  6475. Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."),
  6476. A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."),
  6477. Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."),
  6478. get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."),
  6479. A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."),
  6480. Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."),
  6481. Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."),
  6482. Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."),
  6483. Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."),
  6484. Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."),
  6485. Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
  6486. Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
  6487. Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
  6488. Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
  6489. Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
  6490. Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
  6491. Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
  6492. This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
  6493. Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
  6494. Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
  6495. Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
  6496. Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."),
  6497. Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."),
  6498. Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."),
  6499. Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."),
  6500. Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."),
  6501. The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."),
  6502. The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."),
  6503. The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."),
  6504. The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."),
  6505. Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
  6506. Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."),
  6507. The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."),
  6508. Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."),
  6509. Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."),
  6510. Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."),
  6511. Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
  6512. Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."),
  6513. Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."),
  6514. Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
  6515. Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
  6516. Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
  6517. A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
  6518. Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
  6519. Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
  6520. Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."),
  6521. Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
  6522. All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."),
  6523. Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
  6524. Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
  6525. In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."),
  6526. A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."),
  6527. A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."),
  6528. Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."),
  6529. Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."),
  6530. Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."),
  6531. Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
  6532. Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."),
  6533. Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."),
  6534. Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."),
  6535. Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."),
  6536. Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."),
  6537. Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."),
  6538. Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."),
  6539. Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."),
  6540. The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."),
  6541. Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."),
  6542. Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
  6543. Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
  6544. Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
  6545. An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."),
  6546. The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."),
  6547. Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."),
  6548. Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."),
  6549. Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
  6550. Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
  6551. An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."),
  6552. Module_0_declares_1_locally_but_it_is_not_exported: diag(2459, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_not_exported_2459", "Module '{0}' declares '{1}' locally, but it is not exported."),
  6553. Module_0_declares_1_locally_but_it_is_exported_as_2: diag(2460, ts.DiagnosticCategory.Error, "Module_0_declares_1_locally_but_it_is_exported_as_2_2460", "Module '{0}' declares '{1}' locally, but it is exported as '{2}'."),
  6554. Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."),
  6555. A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."),
  6556. A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."),
  6557. A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."),
  6558. this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."),
  6559. super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."),
  6560. A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."),
  6561. Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
  6562. The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."),
  6563. Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."),
  6564. A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."),
  6565. Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."),
  6566. Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."),
  6567. const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."),
  6568. const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."),
  6569. A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."),
  6570. const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."),
  6571. const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."),
  6572. Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."),
  6573. let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."),
  6574. Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."),
  6575. The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."),
  6576. Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."),
  6577. The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."),
  6578. Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."),
  6579. An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."),
  6580. The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the '{0}()' method of an iterator must have a 'value' property."),
  6581. The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."),
  6582. Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."),
  6583. Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."),
  6584. Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."),
  6585. Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."),
  6586. The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."),
  6587. This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."),
  6588. Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."),
  6589. An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."),
  6590. A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."),
  6591. A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."),
  6592. _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."),
  6593. Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
  6594. Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."),
  6595. A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."),
  6596. _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
  6597. Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
  6598. No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
  6599. Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
  6600. Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
  6601. Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
  6602. Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
  6603. Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."),
  6604. Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."),
  6605. Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."),
  6606. All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."),
  6607. Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."),
  6608. A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."),
  6609. An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."),
  6610. Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."),
  6611. Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."),
  6612. The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."),
  6613. yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."),
  6614. await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."),
  6615. Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."),
  6616. A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."),
  6617. The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."),
  6618. A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."),
  6619. Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."),
  6620. Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."),
  6621. Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
  6622. Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
  6623. Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
  6624. A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."),
  6625. Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."),
  6626. Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."),
  6627. Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
  6628. Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
  6629. Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
  6630. Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
  6631. The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
  6632. Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
  6633. Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
  6634. Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."),
  6635. A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."),
  6636. Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."),
  6637. The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."),
  6638. Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
  6639. Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
  6640. Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),
  6641. Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"),
  6642. Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."),
  6643. Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
  6644. Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."),
  6645. Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."),
  6646. Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."),
  6647. Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."),
  6648. Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."),
  6649. Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"),
  6650. Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"),
  6651. Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."),
  6652. The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."),
  6653. Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."),
  6654. Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."),
  6655. A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."),
  6656. Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."),
  6657. Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),
  6658. Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
  6659. Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
  6660. Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."),
  6661. A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."),
  6662. No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),
  6663. Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"),
  6664. Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
  6665. Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
  6666. Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
  6667. Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
  6668. Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
  6669. Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
  6670. _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
  6671. Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
  6672. JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
  6673. Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
  6674. Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
  6675. Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
  6676. Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
  6677. Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
  6678. Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
  6679. This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."),
  6680. JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
  6681. The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
  6682. JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
  6683. Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."),
  6684. JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."),
  6685. JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."),
  6686. Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."),
  6687. JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."),
  6688. The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."),
  6689. JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."),
  6690. _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, ts.DiagnosticCategory.Error, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."),
  6691. _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, ts.DiagnosticCategory.Error, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."),
  6692. Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."),
  6693. Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"),
  6694. Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"),
  6695. Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."),
  6696. A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."),
  6697. Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."),
  6698. Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."),
  6699. Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."),
  6700. Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."),
  6701. JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."),
  6702. Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."),
  6703. super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."),
  6704. super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."),
  6705. Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."),
  6706. Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"),
  6707. Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"),
  6708. Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."),
  6709. Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."),
  6710. Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."),
  6711. Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."),
  6712. export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."),
  6713. Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."),
  6714. Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."),
  6715. Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."),
  6716. Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."),
  6717. Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."),
  6718. Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."),
  6719. Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."),
  6720. Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."),
  6721. A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."),
  6722. Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."),
  6723. A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."),
  6724. A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."),
  6725. A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."),
  6726. get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."),
  6727. this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."),
  6728. The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."),
  6729. The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."),
  6730. _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."),
  6731. All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."),
  6732. Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."),
  6733. Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"),
  6734. An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."),
  6735. _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."),
  6736. _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."),
  6737. Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."),
  6738. Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true),
  6739. The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"),
  6740. An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
  6741. Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."),
  6742. Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."),
  6743. Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."),
  6744. The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."),
  6745. _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."),
  6746. The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."),
  6747. The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."),
  6748. An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
  6749. Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."),
  6750. Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."),
  6751. Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."),
  6752. Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."),
  6753. _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."),
  6754. A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
  6755. A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
  6756. Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"),
  6757. The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."),
  6758. Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."),
  6759. Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."),
  6760. Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."),
  6761. Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
  6762. Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."),
  6763. Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"),
  6764. Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
  6765. Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
  6766. Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
  6767. Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
  6768. Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."),
  6769. Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
  6770. Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"),
  6771. _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
  6772. Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."),
  6773. An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."),
  6774. Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),
  6775. Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"),
  6776. Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
  6777. It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."),
  6778. Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"),
  6779. Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."),
  6780. BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."),
  6781. An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, ts.DiagnosticCategory.Message, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."),
  6782. Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
  6783. Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
  6784. Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
  6785. The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
  6786. No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."),
  6787. Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."),
  6788. This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
  6789. This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
  6790. _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
  6791. Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
  6792. _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
  6793. The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
  6794. Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
  6795. The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
  6796. Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
  6797. super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
  6798. No_constituent_of_type_0_is_callable: diag(2755, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_callable_2755", "No constituent of type '{0}' is callable."),
  6799. Not_all_constituents_of_type_0_are_callable: diag(2756, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_callable_2756", "Not all constituents of type '{0}' are callable."),
  6800. Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
  6801. Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2758, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758", "Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other."),
  6802. No_constituent_of_type_0_is_constructable: diag(2759, ts.DiagnosticCategory.Error, "No_constituent_of_type_0_is_constructable_2759", "No constituent of type '{0}' is constructable."),
  6803. Not_all_constituents_of_type_0_are_constructable: diag(2760, ts.DiagnosticCategory.Error, "Not_all_constituents_of_type_0_are_constructable_2760", "Not all constituents of type '{0}' are constructable."),
  6804. Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
  6805. Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2762, ts.DiagnosticCategory.Error, "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762", "Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other."),
  6806. Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0: diag(2763, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but for-of will always send '{0}'."),
  6807. Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0: diag(2764, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array spread will always send '{0}'."),
  6808. Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0: diag(2765, ts.DiagnosticCategory.Error, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array destructuring will always send '{0}'."),
  6809. Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0: diag(2766, ts.DiagnosticCategory.Error, "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766", "Cannot delegate iteration to value because the 'next' method of its iterator expects type '{1}', but the containing generator will always send '{0}'."),
  6810. The_0_property_of_an_iterator_must_be_a_method: diag(2767, ts.DiagnosticCategory.Error, "The_0_property_of_an_iterator_must_be_a_method_2767", "The '{0}' property of an iterator must be a method."),
  6811. The_0_property_of_an_async_iterator_must_be_a_method: diag(2768, ts.DiagnosticCategory.Error, "The_0_property_of_an_async_iterator_must_be_a_method_2768", "The '{0}' property of an async iterator must be a method."),
  6812. No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
  6813. The_last_overload_gave_the_following_error: diag(2770, ts.DiagnosticCategory.Error, "The_last_overload_gave_the_following_error_2770", "The last overload gave the following error."),
  6814. The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
  6815. Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."),
  6816. Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
  6817. This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"),
  6818. Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."),
  6819. Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."),
  6820. The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."),
  6821. The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access: diag(2778, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778", "The target of an object rest assignment may not be an optional property access."),
  6822. The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access: diag(2779, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779", "The left-hand side of an assignment expression may not be an optional property access."),
  6823. The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."),
  6824. The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."),
  6825. _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
  6826. Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
  6827. Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
  6828. Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
  6829. Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
  6830. Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
  6831. Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
  6832. Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."),
  6833. Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."),
  6834. Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."),
  6835. Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."),
  6836. extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."),
  6837. extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."),
  6838. Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."),
  6839. Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."),
  6840. Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."),
  6841. Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6842. Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
  6843. Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."),
  6844. Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6845. Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
  6846. Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."),
  6847. Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
  6848. Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."),
  6849. Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
  6850. Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."),
  6851. Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
  6852. Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."),
  6853. Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6854. Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
  6855. Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."),
  6856. Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6857. Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
  6858. Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."),
  6859. Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."),
  6860. Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."),
  6861. Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."),
  6862. Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."),
  6863. Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."),
  6864. Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."),
  6865. Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
  6866. Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."),
  6867. Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."),
  6868. Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
  6869. Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."),
  6870. Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."),
  6871. Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."),
  6872. Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."),
  6873. Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."),
  6874. Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."),
  6875. Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."),
  6876. Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6877. Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."),
  6878. Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."),
  6879. Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."),
  6880. Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
  6881. Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."),
  6882. Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
  6883. Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6884. Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."),
  6885. Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
  6886. Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6887. Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."),
  6888. Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."),
  6889. Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."),
  6890. Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."),
  6891. Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."),
  6892. Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."),
  6893. Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."),
  6894. Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."),
  6895. Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."),
  6896. Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."),
  6897. Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."),
  6898. Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."),
  6899. Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."),
  6900. Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
  6901. Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6902. Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
  6903. Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."),
  6904. Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
  6905. Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
  6906. Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
  6907. Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
  6908. Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
  6909. Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
  6910. The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1: diag(4104, ts.DiagnosticCategory.Error, "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104", "The type '{0}' is 'readonly' and cannot be assigned to the mutable type '{1}'."),
  6911. Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter: diag(4105, ts.DiagnosticCategory.Error, "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105", "Private or protected member '{0}' cannot be accessed on a type parameter."),
  6912. Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."),
  6913. Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."),
  6914. Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, ts.DiagnosticCategory.Error, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."),
  6915. Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."),
  6916. Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
  6917. The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
  6918. Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
  6919. File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
  6920. Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
  6921. Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."),
  6922. Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
  6923. Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."),
  6924. Unknown_compiler_option_0_Did_you_mean_1: diag(5025, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"),
  6925. Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."),
  6926. Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."),
  6927. Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."),
  6928. Option_0_cannot_be_specified_when_option_target_is_ES3: diag(5048, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_target_is_ES3_5048", "Option '{0}' cannot be specified when option 'target' is 'ES3'."),
  6929. Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."),
  6930. Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."),
  6931. Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."),
  6932. A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."),
  6933. Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."),
  6934. Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."),
  6935. Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."),
  6936. The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."),
  6937. Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."),
  6938. Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."),
  6939. Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."),
  6940. Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' can have at most one '*' character."),
  6941. Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."),
  6942. Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."),
  6943. File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."),
  6944. Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."),
  6945. Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
  6946. Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
  6947. Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
  6948. Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
  6949. Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),
  6950. Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
  6951. Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."),
  6952. Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."),
  6953. _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."),
  6954. _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."),
  6955. Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"),
  6956. Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
  6957. Unknown_watch_option_0_Did_you_mean_1: diag(5079, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"),
  6958. Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."),
  6959. Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."),
  6960. Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
  6961. Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
  6962. Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
  6963. Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."),
  6964. Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."),
  6965. Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
  6966. Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
  6967. Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."),
  6968. Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."),
  6969. Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
  6970. Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
  6971. Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."),
  6972. Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
  6973. Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
  6974. Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
  6975. Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."),
  6976. Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."),
  6977. Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
  6978. Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
  6979. Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."),
  6980. Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
  6981. options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
  6982. file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
  6983. Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
  6984. Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
  6985. Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
  6986. Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."),
  6987. Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
  6988. File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
  6989. KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
  6990. FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
  6991. VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
  6992. LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
  6993. DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
  6994. STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
  6995. FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
  6996. Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
  6997. Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
  6998. Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."),
  6999. Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."),
  7000. Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'."),
  7001. Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
  7002. Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
  7003. Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
  7004. Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."),
  7005. File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
  7006. File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."),
  7007. Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."),
  7008. Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."),
  7009. Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."),
  7010. File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."),
  7011. Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."),
  7012. NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
  7013. Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."),
  7014. Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
  7015. Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."),
  7016. Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."),
  7017. Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."),
  7018. Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."),
  7019. Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
  7020. Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."),
  7021. Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."),
  7022. Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."),
  7023. Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."),
  7024. Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."),
  7025. Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."),
  7026. Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."),
  7027. Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."),
  7028. Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."),
  7029. File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."),
  7030. Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."),
  7031. Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."),
  7032. Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"),
  7033. Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."),
  7034. Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
  7035. Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."),
  7036. Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."),
  7037. Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"),
  7038. Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
  7039. paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."),
  7040. Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
  7041. Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."),
  7042. Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."),
  7043. Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."),
  7044. File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
  7045. File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."),
  7046. Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."),
  7047. Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
  7048. package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."),
  7049. package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."),
  7050. Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
  7051. Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."),
  7052. Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),
  7053. Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),
  7054. baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),
  7055. rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."),
  7056. Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."),
  7057. Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."),
  7058. Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
  7059. Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
  7060. Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."),
  7061. Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
  7062. Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"),
  7063. Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."),
  7064. Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"),
  7065. Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
  7066. Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
  7067. Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"),
  7068. Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"),
  7069. Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
  7070. Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."),
  7071. Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"),
  7072. Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."),
  7073. Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."),
  7074. Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."),
  7075. Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"),
  7076. Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"),
  7077. Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."),
  7078. Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."),
  7079. File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."),
  7080. _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
  7081. Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
  7082. Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
  7083. The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."),
  7084. Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."),
  7085. Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
  7086. Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
  7087. Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."),
  7088. Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."),
  7089. Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."),
  7090. Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
  7091. Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
  7092. Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
  7093. Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
  7094. Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
  7095. Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
  7096. Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
  7097. Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."),
  7098. Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."),
  7099. Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."),
  7100. Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."),
  7101. Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."),
  7102. The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"),
  7103. Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."),
  7104. Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."),
  7105. Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."),
  7106. Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."),
  7107. List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."),
  7108. Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
  7109. The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."),
  7110. Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
  7111. Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
  7112. Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
  7113. A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."),
  7114. List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."),
  7115. Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
  7116. Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"),
  7117. Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
  7118. Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
  7119. Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
  7120. Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
  7121. Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
  7122. Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
  7123. Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
  7124. Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
  7125. Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."),
  7126. Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
  7127. List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
  7128. Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
  7129. Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."),
  7130. Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."),
  7131. Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."),
  7132. Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
  7133. Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."),
  7134. Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
  7135. Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
  7136. Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
  7137. All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true),
  7138. Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."),
  7139. Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
  7140. Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
  7141. _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
  7142. Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
  7143. All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
  7144. All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
  7145. Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"),
  7146. Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
  7147. Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
  7148. _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
  7149. and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
  7150. All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
  7151. package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."),
  7152. package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),
  7153. package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),
  7154. package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),
  7155. An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."),
  7156. An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."),
  7157. Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"),
  7158. Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"),
  7159. Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."),
  7160. Using_compiler_options_of_project_reference_redirect_0: diag(6215, ts.DiagnosticCategory.Message, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."),
  7161. Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
  7162. Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
  7163. Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2: diag(6218, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218", "======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========"),
  7164. Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3: diag(6219, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219", "======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========"),
  7165. package_json_had_a_falsy_0_field: diag(6220, ts.DiagnosticCategory.Message, "package_json_had_a_falsy_0_field_6220", "'package.json' had a falsy '{0}' field."),
  7166. Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects: diag(6221, ts.DiagnosticCategory.Message, "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221", "Disable use of source files instead of declaration files from referenced projects."),
  7167. Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."),
  7168. Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
  7169. Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
  7170. Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
  7171. Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."),
  7172. Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."),
  7173. Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."),
  7174. Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."),
  7175. Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
  7176. Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
  7177. Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
  7178. Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
  7179. Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
  7180. File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307", "File '{0}' is not listed within the file list of project '{1}'. Projects must list all files or use an 'include' pattern."),
  7181. Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
  7182. Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
  7183. Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"),
  7184. Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"),
  7185. Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"),
  7186. Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"),
  7187. Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"),
  7188. Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
  7189. A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"),
  7190. A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"),
  7191. Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
  7192. Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
  7193. delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"),
  7194. Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
  7195. Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"),
  7196. Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"),
  7197. Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"),
  7198. Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
  7199. Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
  7200. Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"),
  7201. Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"),
  7202. Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
  7203. Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
  7204. Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
  7205. Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
  7206. Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
  7207. A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
  7208. A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
  7209. Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
  7210. Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
  7211. Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
  7212. Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
  7213. Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
  7214. Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
  7215. Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"),
  7216. Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"),
  7217. Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."),
  7218. The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
  7219. The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
  7220. The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
  7221. Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."),
  7222. File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"),
  7223. Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
  7224. Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
  7225. Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
  7226. new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."),
  7227. _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."),
  7228. Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."),
  7229. Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."),
  7230. Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, ts.DiagnosticCategory.Error, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."),
  7231. Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."),
  7232. Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."),
  7233. Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."),
  7234. Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."),
  7235. Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."),
  7236. Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."),
  7237. _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."),
  7238. _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
  7239. Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
  7240. Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_retu_7025", "Generator implicitly has yield type '{0}' because it does not yield any values. Consider supplying a return type annotation."),
  7241. JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."),
  7242. Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
  7243. Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
  7244. Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
  7245. Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."),
  7246. Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."),
  7247. Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."),
  7248. Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."),
  7249. Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."),
  7250. Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
  7251. Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."),
  7252. Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."),
  7253. Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."),
  7254. Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."),
  7255. If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"),
  7256. The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
  7257. Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),
  7258. Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
  7259. Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
  7260. Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, ts.DiagnosticCategory.Suggestion, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
  7261. Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."),
  7262. Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, ts.DiagnosticCategory.Suggestion, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."),
  7263. Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
  7264. Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
  7265. _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
  7266. Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
  7267. Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1: diag(7052, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052", "Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?"),
  7268. Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1: diag(7053, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053", "Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'."),
  7269. No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1: diag(7054, ts.DiagnosticCategory.Error, "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054", "No index signature with a parameter of type '{0}' was found on type '{1}'."),
  7270. _0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type: diag(7055, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055", "'{0}', which lacks return-type annotation, implicitly has an '{1}' yield type."),
  7271. You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
  7272. You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."),
  7273. import_can_only_be_used_in_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."),
  7274. export_can_only_be_used_in_TypeScript_files: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_TypeScript_files_8003", "'export =' can only be used in TypeScript files."),
  7275. Type_parameter_declarations_can_only_be_used_in_TypeScript_files: diag(8004, ts.DiagnosticCategory.Error, "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004", "Type parameter declarations can only be used in TypeScript files."),
  7276. implements_clauses_can_only_be_used_in_TypeScript_files: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_TypeScript_files_8005", "'implements' clauses can only be used in TypeScript files."),
  7277. _0_declarations_can_only_be_used_in_TypeScript_files: diag(8006, ts.DiagnosticCategory.Error, "_0_declarations_can_only_be_used_in_TypeScript_files_8006", "'{0}' declarations can only be used in TypeScript files."),
  7278. Type_aliases_can_only_be_used_in_TypeScript_files: diag(8008, ts.DiagnosticCategory.Error, "Type_aliases_can_only_be_used_in_TypeScript_files_8008", "Type aliases can only be used in TypeScript files."),
  7279. The_0_modifier_can_only_be_used_in_TypeScript_files: diag(8009, ts.DiagnosticCategory.Error, "The_0_modifier_can_only_be_used_in_TypeScript_files_8009", "The '{0}' modifier can only be used in TypeScript files."),
  7280. Type_annotations_can_only_be_used_in_TypeScript_files: diag(8010, ts.DiagnosticCategory.Error, "Type_annotations_can_only_be_used_in_TypeScript_files_8010", "Type annotations can only be used in TypeScript files."),
  7281. Type_arguments_can_only_be_used_in_TypeScript_files: diag(8011, ts.DiagnosticCategory.Error, "Type_arguments_can_only_be_used_in_TypeScript_files_8011", "Type arguments can only be used in TypeScript files."),
  7282. Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, ts.DiagnosticCategory.Error, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."),
  7283. Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, ts.DiagnosticCategory.Error, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."),
  7284. Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, ts.DiagnosticCategory.Error, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."),
  7285. Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."),
  7286. Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."),
  7287. Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
  7288. JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."),
  7289. JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."),
  7290. JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."),
  7291. JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."),
  7292. JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."),
  7293. Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."),
  7294. Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."),
  7295. Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."),
  7296. JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."),
  7297. JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."),
  7298. The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."),
  7299. You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."),
  7300. Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."),
  7301. Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."),
  7302. class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
  7303. Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
  7304. Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."),
  7305. Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."),
  7306. JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."),
  7307. JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."),
  7308. Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."),
  7309. JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
  7310. Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."),
  7311. A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."),
  7312. An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
  7313. A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
  7314. JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."),
  7315. super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."),
  7316. Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
  7317. super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."),
  7318. _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"),
  7319. Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."),
  7320. JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
  7321. Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
  7322. JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
  7323. JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
  7324. Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"),
  7325. Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
  7326. A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
  7327. The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
  7328. No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
  7329. File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
  7330. This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
  7331. Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
  7332. JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
  7333. require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."),
  7334. This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."),
  7335. await_has_no_effect_on_the_type_of_this_expression: diag(80007, ts.DiagnosticCategory.Suggestion, "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."),
  7336. Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, ts.DiagnosticCategory.Suggestion, "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."),
  7337. Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
  7338. Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
  7339. Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
  7340. Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
  7341. Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
  7342. Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
  7343. Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
  7344. Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
  7345. Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
  7346. Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
  7347. Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
  7348. Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
  7349. Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
  7350. Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
  7351. Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
  7352. Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
  7353. Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
  7354. Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
  7355. Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
  7356. Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
  7357. Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
  7358. Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
  7359. Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
  7360. Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
  7361. Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
  7362. Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"),
  7363. Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
  7364. Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
  7365. Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
  7366. Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
  7367. Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
  7368. Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
  7369. Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
  7370. Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
  7371. Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
  7372. Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
  7373. Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
  7374. Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
  7375. Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
  7376. Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
  7377. Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
  7378. Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
  7379. Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
  7380. Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
  7381. Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
  7382. Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
  7383. Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
  7384. Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
  7385. Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
  7386. Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
  7387. Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
  7388. Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
  7389. Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
  7390. Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
  7391. Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
  7392. Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
  7393. Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
  7394. Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"),
  7395. Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
  7396. Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
  7397. Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"),
  7398. Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"),
  7399. Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"),
  7400. Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"),
  7401. Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
  7402. Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
  7403. Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
  7404. Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
  7405. Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"),
  7406. Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"),
  7407. Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
  7408. Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
  7409. Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
  7410. Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
  7411. Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"),
  7412. Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
  7413. Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
  7414. Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
  7415. Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
  7416. Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
  7417. Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
  7418. Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
  7419. Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
  7420. Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
  7421. Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
  7422. Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
  7423. Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
  7424. Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
  7425. Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
  7426. Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
  7427. Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"),
  7428. Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
  7429. Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
  7430. Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
  7431. Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
  7432. Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
  7433. Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
  7434. Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
  7435. Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
  7436. Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
  7437. Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
  7438. Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
  7439. Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
  7440. Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
  7441. Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
  7442. Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
  7443. Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
  7444. Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
  7445. Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
  7446. Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
  7447. Infer_this_type_of_0_from_usage: diag(95080, ts.DiagnosticCategory.Message, "Infer_this_type_of_0_from_usage_95080", "Infer 'this' type of '{0}' from usage"),
  7448. Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
  7449. Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
  7450. Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
  7451. Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
  7452. Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
  7453. Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
  7454. Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
  7455. Enable_the_jsx_flag_in_your_configuration_file: diag(95088, ts.DiagnosticCategory.Message, "Enable_the_jsx_flag_in_your_configuration_file_95088", "Enable the '--jsx' flag in your configuration file"),
  7456. Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
  7457. Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
  7458. Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
  7459. Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
  7460. Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
  7461. Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
  7462. Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"),
  7463. Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
  7464. Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"),
  7465. Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"),
  7466. Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"),
  7467. No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."),
  7468. Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."),
  7469. JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"),
  7470. Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"),
  7471. An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."),
  7472. The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."),
  7473. constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
  7474. Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier: diag(18013, ts.DiagnosticCategory.Error, "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013", "Property '{0}' is not accessible outside class '{1}' because it has a private identifier."),
  7475. The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling: diag(18014, ts.DiagnosticCategory.Error, "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014", "The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling."),
  7476. Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2: diag(18015, ts.DiagnosticCategory.Error, "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015", "Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'."),
  7477. Private_identifiers_are_not_allowed_outside_class_bodies: diag(18016, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_outside_class_bodies_18016", "Private identifiers are not allowed outside class bodies."),
  7478. The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"),
  7479. The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"),
  7480. _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier"),
  7481. A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."),
  7482. An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."),
  7483. An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."),
  7484. can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."),
  7485. Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."),
  7486. Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."),
  7487. Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."),
  7488. An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."),
  7489. };
  7490. })(ts || (ts = {}));
  7491. var ts;
  7492. (function (ts) {
  7493. var _a;
  7494. /* @internal */
  7495. function tokenIsIdentifierOrKeyword(token) {
  7496. return token >= 75 /* Identifier */;
  7497. }
  7498. ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
  7499. /* @internal */
  7500. function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
  7501. return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
  7502. }
  7503. ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
  7504. var textToKeywordObj = (_a = {
  7505. abstract: 122 /* AbstractKeyword */,
  7506. any: 125 /* AnyKeyword */,
  7507. as: 123 /* AsKeyword */,
  7508. asserts: 124 /* AssertsKeyword */,
  7509. bigint: 151 /* BigIntKeyword */,
  7510. boolean: 128 /* BooleanKeyword */,
  7511. break: 77 /* BreakKeyword */,
  7512. case: 78 /* CaseKeyword */,
  7513. catch: 79 /* CatchKeyword */,
  7514. class: 80 /* ClassKeyword */,
  7515. continue: 82 /* ContinueKeyword */,
  7516. const: 81 /* ConstKeyword */
  7517. },
  7518. _a["" + "constructor"] = 129 /* ConstructorKeyword */,
  7519. _a.debugger = 83 /* DebuggerKeyword */,
  7520. _a.declare = 130 /* DeclareKeyword */,
  7521. _a.default = 84 /* DefaultKeyword */,
  7522. _a.delete = 85 /* DeleteKeyword */,
  7523. _a.do = 86 /* DoKeyword */,
  7524. _a.else = 87 /* ElseKeyword */,
  7525. _a.enum = 88 /* EnumKeyword */,
  7526. _a.export = 89 /* ExportKeyword */,
  7527. _a.extends = 90 /* ExtendsKeyword */,
  7528. _a.false = 91 /* FalseKeyword */,
  7529. _a.finally = 92 /* FinallyKeyword */,
  7530. _a.for = 93 /* ForKeyword */,
  7531. _a.from = 149 /* FromKeyword */,
  7532. _a.function = 94 /* FunctionKeyword */,
  7533. _a.get = 131 /* GetKeyword */,
  7534. _a.if = 95 /* IfKeyword */,
  7535. _a.implements = 113 /* ImplementsKeyword */,
  7536. _a.import = 96 /* ImportKeyword */,
  7537. _a.in = 97 /* InKeyword */,
  7538. _a.infer = 132 /* InferKeyword */,
  7539. _a.instanceof = 98 /* InstanceOfKeyword */,
  7540. _a.interface = 114 /* InterfaceKeyword */,
  7541. _a.is = 133 /* IsKeyword */,
  7542. _a.keyof = 134 /* KeyOfKeyword */,
  7543. _a.let = 115 /* LetKeyword */,
  7544. _a.module = 135 /* ModuleKeyword */,
  7545. _a.namespace = 136 /* NamespaceKeyword */,
  7546. _a.never = 137 /* NeverKeyword */,
  7547. _a.new = 99 /* NewKeyword */,
  7548. _a.null = 100 /* NullKeyword */,
  7549. _a.number = 140 /* NumberKeyword */,
  7550. _a.object = 141 /* ObjectKeyword */,
  7551. _a.package = 116 /* PackageKeyword */,
  7552. _a.private = 117 /* PrivateKeyword */,
  7553. _a.protected = 118 /* ProtectedKeyword */,
  7554. _a.public = 119 /* PublicKeyword */,
  7555. _a.readonly = 138 /* ReadonlyKeyword */,
  7556. _a.require = 139 /* RequireKeyword */,
  7557. _a.global = 150 /* GlobalKeyword */,
  7558. _a.return = 101 /* ReturnKeyword */,
  7559. _a.set = 142 /* SetKeyword */,
  7560. _a.static = 120 /* StaticKeyword */,
  7561. _a.string = 143 /* StringKeyword */,
  7562. _a.super = 102 /* SuperKeyword */,
  7563. _a.switch = 103 /* SwitchKeyword */,
  7564. _a.symbol = 144 /* SymbolKeyword */,
  7565. _a.this = 104 /* ThisKeyword */,
  7566. _a.throw = 105 /* ThrowKeyword */,
  7567. _a.true = 106 /* TrueKeyword */,
  7568. _a.try = 107 /* TryKeyword */,
  7569. _a.type = 145 /* TypeKeyword */,
  7570. _a.typeof = 108 /* TypeOfKeyword */,
  7571. _a.undefined = 146 /* UndefinedKeyword */,
  7572. _a.unique = 147 /* UniqueKeyword */,
  7573. _a.unknown = 148 /* UnknownKeyword */,
  7574. _a.var = 109 /* VarKeyword */,
  7575. _a.void = 110 /* VoidKeyword */,
  7576. _a.while = 111 /* WhileKeyword */,
  7577. _a.with = 112 /* WithKeyword */,
  7578. _a.yield = 121 /* YieldKeyword */,
  7579. _a.async = 126 /* AsyncKeyword */,
  7580. _a.await = 127 /* AwaitKeyword */,
  7581. _a.of = 152 /* OfKeyword */,
  7582. _a);
  7583. var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
  7584. var textToToken = ts.createMapFromTemplate(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, "</": 30 /* LessThanSlashToken */, ">>": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 74 /* CaretEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }));
  7585. /*
  7586. As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
  7587. IdentifierStart ::
  7588. Can contain Unicode 3.0.0 categories:
  7589. Uppercase letter (Lu),
  7590. Lowercase letter (Ll),
  7591. Titlecase letter (Lt),
  7592. Modifier letter (Lm),
  7593. Other letter (Lo), or
  7594. Letter number (Nl).
  7595. IdentifierPart :: =
  7596. Can contain IdentifierStart + Unicode 3.0.0 categories:
  7597. Non-spacing mark (Mn),
  7598. Combining spacing mark (Mc),
  7599. Decimal number (Nd), or
  7600. Connector punctuation (Pc).
  7601. Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
  7602. http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
  7603. */
  7604. var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
  7605. var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
  7606. /*
  7607. As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
  7608. IdentifierStart ::
  7609. Can contain Unicode 6.2 categories:
  7610. Uppercase letter (Lu),
  7611. Lowercase letter (Ll),
  7612. Titlecase letter (Lt),
  7613. Modifier letter (Lm),
  7614. Other letter (Lo), or
  7615. Letter number (Nl).
  7616. IdentifierPart ::
  7617. Can contain IdentifierStart + Unicode 6.2 categories:
  7618. Non-spacing mark (Mn),
  7619. Combining spacing mark (Mc),
  7620. Decimal number (Nd),
  7621. Connector punctuation (Pc),
  7622. <ZWNJ>, or
  7623. <ZWJ>.
  7624. Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
  7625. http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
  7626. */
  7627. var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
  7628. var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
  7629. /**
  7630. * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
  7631. * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
  7632. * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
  7633. * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
  7634. */
  7635. var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101];
  7636. var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999];
  7637. function lookupInUnicodeMap(code, map) {
  7638. // Bail out quickly if it couldn't possibly be in the map.
  7639. if (code < map[0]) {
  7640. return false;
  7641. }
  7642. // Perform binary search in one of the Unicode range maps
  7643. var lo = 0;
  7644. var hi = map.length;
  7645. var mid;
  7646. while (lo + 1 < hi) {
  7647. mid = lo + (hi - lo) / 2;
  7648. // mid has to be even to catch a range's beginning
  7649. mid -= mid % 2;
  7650. if (map[mid] <= code && code <= map[mid + 1]) {
  7651. return true;
  7652. }
  7653. if (code < map[mid]) {
  7654. hi = mid;
  7655. }
  7656. else {
  7657. lo = mid + 2;
  7658. }
  7659. }
  7660. return false;
  7661. }
  7662. /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
  7663. return languageVersion >= 2 /* ES2015 */ ?
  7664. lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
  7665. languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
  7666. lookupInUnicodeMap(code, unicodeES3IdentifierStart);
  7667. }
  7668. ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
  7669. function isUnicodeIdentifierPart(code, languageVersion) {
  7670. return languageVersion >= 2 /* ES2015 */ ?
  7671. lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
  7672. languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
  7673. lookupInUnicodeMap(code, unicodeES3IdentifierPart);
  7674. }
  7675. function makeReverseMap(source) {
  7676. var result = [];
  7677. source.forEach(function (value, name) {
  7678. result[value] = name;
  7679. });
  7680. return result;
  7681. }
  7682. var tokenStrings = makeReverseMap(textToToken);
  7683. function tokenToString(t) {
  7684. return tokenStrings[t];
  7685. }
  7686. ts.tokenToString = tokenToString;
  7687. /* @internal */
  7688. function stringToToken(s) {
  7689. return textToToken.get(s);
  7690. }
  7691. ts.stringToToken = stringToToken;
  7692. /* @internal */
  7693. function computeLineStarts(text) {
  7694. var result = new Array();
  7695. var pos = 0;
  7696. var lineStart = 0;
  7697. while (pos < text.length) {
  7698. var ch = text.charCodeAt(pos);
  7699. pos++;
  7700. switch (ch) {
  7701. case 13 /* carriageReturn */:
  7702. if (text.charCodeAt(pos) === 10 /* lineFeed */) {
  7703. pos++;
  7704. }
  7705. // falls through
  7706. case 10 /* lineFeed */:
  7707. result.push(lineStart);
  7708. lineStart = pos;
  7709. break;
  7710. default:
  7711. if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
  7712. result.push(lineStart);
  7713. lineStart = pos;
  7714. }
  7715. break;
  7716. }
  7717. }
  7718. result.push(lineStart);
  7719. return result;
  7720. }
  7721. ts.computeLineStarts = computeLineStarts;
  7722. function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
  7723. return sourceFile.getPositionOfLineAndCharacter ?
  7724. sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
  7725. computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
  7726. }
  7727. ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
  7728. /* @internal */
  7729. function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
  7730. if (line < 0 || line >= lineStarts.length) {
  7731. if (allowEdits) {
  7732. // Clamp line to nearest allowable value
  7733. line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
  7734. }
  7735. else {
  7736. ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
  7737. }
  7738. }
  7739. var res = lineStarts[line] + character;
  7740. if (allowEdits) {
  7741. // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
  7742. // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
  7743. // apply them to the computed position to improve accuracy
  7744. return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
  7745. }
  7746. if (line < lineStarts.length - 1) {
  7747. ts.Debug.assert(res < lineStarts[line + 1]);
  7748. }
  7749. else if (debugText !== undefined) {
  7750. ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
  7751. }
  7752. return res;
  7753. }
  7754. ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
  7755. /* @internal */
  7756. function getLineStarts(sourceFile) {
  7757. return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
  7758. }
  7759. ts.getLineStarts = getLineStarts;
  7760. /* @internal */
  7761. /**
  7762. * We assume the first line starts at position 0 and 'position' is non-negative.
  7763. */
  7764. function computeLineAndCharacterOfPosition(lineStarts, position) {
  7765. var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues);
  7766. if (lineNumber < 0) {
  7767. // If the actual position was not found,
  7768. // the binary search returns the 2's-complement of the next line start
  7769. // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
  7770. // then the search will return -2.
  7771. //
  7772. // We want the index of the previous line start, so we subtract 1.
  7773. // Review 2's-complement if this is confusing.
  7774. lineNumber = ~lineNumber - 1;
  7775. ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
  7776. }
  7777. return {
  7778. line: lineNumber,
  7779. character: position - lineStarts[lineNumber]
  7780. };
  7781. }
  7782. ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
  7783. function getLineAndCharacterOfPosition(sourceFile, position) {
  7784. return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
  7785. }
  7786. ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
  7787. function isWhiteSpaceLike(ch) {
  7788. return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
  7789. }
  7790. ts.isWhiteSpaceLike = isWhiteSpaceLike;
  7791. /** Does not include line breaks. For that, see isWhiteSpaceLike. */
  7792. function isWhiteSpaceSingleLine(ch) {
  7793. // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
  7794. // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
  7795. return ch === 32 /* space */ ||
  7796. ch === 9 /* tab */ ||
  7797. ch === 11 /* verticalTab */ ||
  7798. ch === 12 /* formFeed */ ||
  7799. ch === 160 /* nonBreakingSpace */ ||
  7800. ch === 133 /* nextLine */ ||
  7801. ch === 5760 /* ogham */ ||
  7802. ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
  7803. ch === 8239 /* narrowNoBreakSpace */ ||
  7804. ch === 8287 /* mathematicalSpace */ ||
  7805. ch === 12288 /* ideographicSpace */ ||
  7806. ch === 65279 /* byteOrderMark */;
  7807. }
  7808. ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
  7809. function isLineBreak(ch) {
  7810. // ES5 7.3:
  7811. // The ECMAScript line terminator characters are listed in Table 3.
  7812. // Table 3: Line Terminator Characters
  7813. // Code Unit Value Name Formal Name
  7814. // \u000A Line Feed <LF>
  7815. // \u000D Carriage Return <CR>
  7816. // \u2028 Line separator <LS>
  7817. // \u2029 Paragraph separator <PS>
  7818. // Only the characters in Table 3 are treated as line terminators. Other new line or line
  7819. // breaking characters are treated as white space but not as line terminators.
  7820. return ch === 10 /* lineFeed */ ||
  7821. ch === 13 /* carriageReturn */ ||
  7822. ch === 8232 /* lineSeparator */ ||
  7823. ch === 8233 /* paragraphSeparator */;
  7824. }
  7825. ts.isLineBreak = isLineBreak;
  7826. function isDigit(ch) {
  7827. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  7828. }
  7829. /* @internal */
  7830. function isOctalDigit(ch) {
  7831. return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
  7832. }
  7833. ts.isOctalDigit = isOctalDigit;
  7834. function couldStartTrivia(text, pos) {
  7835. // Keep in sync with skipTrivia
  7836. var ch = text.charCodeAt(pos);
  7837. switch (ch) {
  7838. case 13 /* carriageReturn */:
  7839. case 10 /* lineFeed */:
  7840. case 9 /* tab */:
  7841. case 11 /* verticalTab */:
  7842. case 12 /* formFeed */:
  7843. case 32 /* space */:
  7844. case 47 /* slash */:
  7845. // starts of normal trivia
  7846. // falls through
  7847. case 60 /* lessThan */:
  7848. case 124 /* bar */:
  7849. case 61 /* equals */:
  7850. case 62 /* greaterThan */:
  7851. // Starts of conflict marker trivia
  7852. return true;
  7853. case 35 /* hash */:
  7854. // Only if its the beginning can we have #! trivia
  7855. return pos === 0;
  7856. default:
  7857. return ch > 127 /* maxAsciiCharacter */;
  7858. }
  7859. }
  7860. ts.couldStartTrivia = couldStartTrivia;
  7861. /* @internal */
  7862. function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
  7863. if (stopAtComments === void 0) { stopAtComments = false; }
  7864. if (ts.positionIsSynthesized(pos)) {
  7865. return pos;
  7866. }
  7867. // Keep in sync with couldStartTrivia
  7868. while (true) {
  7869. var ch = text.charCodeAt(pos);
  7870. switch (ch) {
  7871. case 13 /* carriageReturn */:
  7872. if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
  7873. pos++;
  7874. }
  7875. // falls through
  7876. case 10 /* lineFeed */:
  7877. pos++;
  7878. if (stopAfterLineBreak) {
  7879. return pos;
  7880. }
  7881. continue;
  7882. case 9 /* tab */:
  7883. case 11 /* verticalTab */:
  7884. case 12 /* formFeed */:
  7885. case 32 /* space */:
  7886. pos++;
  7887. continue;
  7888. case 47 /* slash */:
  7889. if (stopAtComments) {
  7890. break;
  7891. }
  7892. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  7893. pos += 2;
  7894. while (pos < text.length) {
  7895. if (isLineBreak(text.charCodeAt(pos))) {
  7896. break;
  7897. }
  7898. pos++;
  7899. }
  7900. continue;
  7901. }
  7902. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  7903. pos += 2;
  7904. while (pos < text.length) {
  7905. if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  7906. pos += 2;
  7907. break;
  7908. }
  7909. pos++;
  7910. }
  7911. continue;
  7912. }
  7913. break;
  7914. case 60 /* lessThan */:
  7915. case 124 /* bar */:
  7916. case 61 /* equals */:
  7917. case 62 /* greaterThan */:
  7918. if (isConflictMarkerTrivia(text, pos)) {
  7919. pos = scanConflictMarkerTrivia(text, pos);
  7920. continue;
  7921. }
  7922. break;
  7923. case 35 /* hash */:
  7924. if (pos === 0 && isShebangTrivia(text, pos)) {
  7925. pos = scanShebangTrivia(text, pos);
  7926. continue;
  7927. }
  7928. break;
  7929. default:
  7930. if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
  7931. pos++;
  7932. continue;
  7933. }
  7934. break;
  7935. }
  7936. return pos;
  7937. }
  7938. }
  7939. ts.skipTrivia = skipTrivia;
  7940. // All conflict markers consist of the same character repeated seven times. If it is
  7941. // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
  7942. var mergeConflictMarkerLength = "<<<<<<<".length;
  7943. function isConflictMarkerTrivia(text, pos) {
  7944. ts.Debug.assert(pos >= 0);
  7945. // Conflict markers must be at the start of a line.
  7946. if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
  7947. var ch = text.charCodeAt(pos);
  7948. if ((pos + mergeConflictMarkerLength) < text.length) {
  7949. for (var i = 0; i < mergeConflictMarkerLength; i++) {
  7950. if (text.charCodeAt(pos + i) !== ch) {
  7951. return false;
  7952. }
  7953. }
  7954. return ch === 61 /* equals */ ||
  7955. text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
  7956. }
  7957. }
  7958. return false;
  7959. }
  7960. function scanConflictMarkerTrivia(text, pos, error) {
  7961. if (error) {
  7962. error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
  7963. }
  7964. var ch = text.charCodeAt(pos);
  7965. var len = text.length;
  7966. if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
  7967. while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
  7968. pos++;
  7969. }
  7970. }
  7971. else {
  7972. ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
  7973. // Consume everything from the start of a ||||||| or ======= marker to the start
  7974. // of the next ======= or >>>>>>> marker.
  7975. while (pos < len) {
  7976. var currentChar = text.charCodeAt(pos);
  7977. if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
  7978. break;
  7979. }
  7980. pos++;
  7981. }
  7982. }
  7983. return pos;
  7984. }
  7985. var shebangTriviaRegex = /^#!.*/;
  7986. /*@internal*/
  7987. function isShebangTrivia(text, pos) {
  7988. // Shebangs check must only be done at the start of the file
  7989. ts.Debug.assert(pos === 0);
  7990. return shebangTriviaRegex.test(text);
  7991. }
  7992. ts.isShebangTrivia = isShebangTrivia;
  7993. /*@internal*/
  7994. function scanShebangTrivia(text, pos) {
  7995. var shebang = shebangTriviaRegex.exec(text)[0];
  7996. pos = pos + shebang.length;
  7997. return pos;
  7998. }
  7999. ts.scanShebangTrivia = scanShebangTrivia;
  8000. /**
  8001. * Invokes a callback for each comment range following the provided position.
  8002. *
  8003. * Single-line comment ranges include the leading double-slash characters but not the ending
  8004. * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
  8005. * asterisk-slash characters.
  8006. *
  8007. * @param reduce If true, accumulates the result of calling the callback in a fashion similar
  8008. * to reduceLeft. If false, iteration stops when the callback returns a truthy value.
  8009. * @param text The source text to scan.
  8010. * @param pos The position at which to start scanning.
  8011. * @param trailing If false, whitespace is skipped until the first line break and comments
  8012. * between that location and the next token are returned. If true, comments occurring
  8013. * between the given position and the next line break are returned.
  8014. * @param cb The callback to execute as each comment range is encountered.
  8015. * @param state A state value to pass to each iteration of the callback.
  8016. * @param initial An initial value to pass when accumulating results (when "reduce" is true).
  8017. * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
  8018. * return value of the callback.
  8019. */
  8020. function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
  8021. var pendingPos;
  8022. var pendingEnd;
  8023. var pendingKind;
  8024. var pendingHasTrailingNewLine;
  8025. var hasPendingCommentRange = false;
  8026. var collecting = trailing;
  8027. var accumulator = initial;
  8028. if (pos === 0) {
  8029. collecting = true;
  8030. var shebang = getShebang(text);
  8031. if (shebang) {
  8032. pos = shebang.length;
  8033. }
  8034. }
  8035. scan: while (pos >= 0 && pos < text.length) {
  8036. var ch = text.charCodeAt(pos);
  8037. switch (ch) {
  8038. case 13 /* carriageReturn */:
  8039. if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
  8040. pos++;
  8041. }
  8042. // falls through
  8043. case 10 /* lineFeed */:
  8044. pos++;
  8045. if (trailing) {
  8046. break scan;
  8047. }
  8048. collecting = true;
  8049. if (hasPendingCommentRange) {
  8050. pendingHasTrailingNewLine = true;
  8051. }
  8052. continue;
  8053. case 9 /* tab */:
  8054. case 11 /* verticalTab */:
  8055. case 12 /* formFeed */:
  8056. case 32 /* space */:
  8057. pos++;
  8058. continue;
  8059. case 47 /* slash */:
  8060. var nextChar = text.charCodeAt(pos + 1);
  8061. var hasTrailingNewLine = false;
  8062. if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
  8063. var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
  8064. var startPos = pos;
  8065. pos += 2;
  8066. if (nextChar === 47 /* slash */) {
  8067. while (pos < text.length) {
  8068. if (isLineBreak(text.charCodeAt(pos))) {
  8069. hasTrailingNewLine = true;
  8070. break;
  8071. }
  8072. pos++;
  8073. }
  8074. }
  8075. else {
  8076. while (pos < text.length) {
  8077. if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  8078. pos += 2;
  8079. break;
  8080. }
  8081. pos++;
  8082. }
  8083. }
  8084. if (collecting) {
  8085. if (hasPendingCommentRange) {
  8086. accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
  8087. if (!reduce && accumulator) {
  8088. // If we are not reducing and we have a truthy result, return it.
  8089. return accumulator;
  8090. }
  8091. }
  8092. pendingPos = startPos;
  8093. pendingEnd = pos;
  8094. pendingKind = kind;
  8095. pendingHasTrailingNewLine = hasTrailingNewLine;
  8096. hasPendingCommentRange = true;
  8097. }
  8098. continue;
  8099. }
  8100. break scan;
  8101. default:
  8102. if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
  8103. if (hasPendingCommentRange && isLineBreak(ch)) {
  8104. pendingHasTrailingNewLine = true;
  8105. }
  8106. pos++;
  8107. continue;
  8108. }
  8109. break scan;
  8110. }
  8111. }
  8112. if (hasPendingCommentRange) {
  8113. accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
  8114. }
  8115. return accumulator;
  8116. }
  8117. function forEachLeadingCommentRange(text, pos, cb, state) {
  8118. return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
  8119. }
  8120. ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
  8121. function forEachTrailingCommentRange(text, pos, cb, state) {
  8122. return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
  8123. }
  8124. ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
  8125. function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
  8126. return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
  8127. }
  8128. ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
  8129. function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
  8130. return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
  8131. }
  8132. ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
  8133. function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
  8134. if (!comments) {
  8135. comments = [];
  8136. }
  8137. comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
  8138. return comments;
  8139. }
  8140. function getLeadingCommentRanges(text, pos) {
  8141. return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
  8142. }
  8143. ts.getLeadingCommentRanges = getLeadingCommentRanges;
  8144. function getTrailingCommentRanges(text, pos) {
  8145. return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
  8146. }
  8147. ts.getTrailingCommentRanges = getTrailingCommentRanges;
  8148. /** Optionally, get the shebang */
  8149. function getShebang(text) {
  8150. var match = shebangTriviaRegex.exec(text);
  8151. if (match) {
  8152. return match[0];
  8153. }
  8154. }
  8155. ts.getShebang = getShebang;
  8156. function isIdentifierStart(ch, languageVersion) {
  8157. return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
  8158. ch === 36 /* $ */ || ch === 95 /* _ */ ||
  8159. ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
  8160. }
  8161. ts.isIdentifierStart = isIdentifierStart;
  8162. function isIdentifierPart(ch, languageVersion) {
  8163. return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
  8164. ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
  8165. ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
  8166. }
  8167. ts.isIdentifierPart = isIdentifierPart;
  8168. /* @internal */
  8169. function isIdentifierText(name, languageVersion) {
  8170. var ch = codePointAt(name, 0);
  8171. if (!isIdentifierStart(ch, languageVersion)) {
  8172. return false;
  8173. }
  8174. for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
  8175. if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion)) {
  8176. return false;
  8177. }
  8178. }
  8179. return true;
  8180. }
  8181. ts.isIdentifierText = isIdentifierText;
  8182. // Creates a scanner over a (possibly unspecified) range of a piece of text.
  8183. function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
  8184. if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
  8185. var text = textInitial;
  8186. // Current position (end position of text of current token)
  8187. var pos;
  8188. // end of text
  8189. var end;
  8190. // Start position of whitespace before current token
  8191. var startPos;
  8192. // Start position of text of current token
  8193. var tokenPos;
  8194. var token;
  8195. var tokenValue;
  8196. var tokenFlags;
  8197. var inJSDocType = 0;
  8198. setText(text, start, length);
  8199. var scanner = {
  8200. getStartPos: function () { return startPos; },
  8201. getTextPos: function () { return pos; },
  8202. getToken: function () { return token; },
  8203. getTokenPos: function () { return tokenPos; },
  8204. getTokenText: function () { return text.substring(tokenPos, pos); },
  8205. getTokenValue: function () { return tokenValue; },
  8206. hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
  8207. hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
  8208. hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
  8209. isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
  8210. isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
  8211. isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
  8212. getTokenFlags: function () { return tokenFlags; },
  8213. reScanGreaterToken: reScanGreaterToken,
  8214. reScanSlashToken: reScanSlashToken,
  8215. reScanTemplateToken: reScanTemplateToken,
  8216. scanJsxIdentifier: scanJsxIdentifier,
  8217. scanJsxAttributeValue: scanJsxAttributeValue,
  8218. reScanJsxAttributeValue: reScanJsxAttributeValue,
  8219. reScanJsxToken: reScanJsxToken,
  8220. reScanLessThanToken: reScanLessThanToken,
  8221. reScanQuestionToken: reScanQuestionToken,
  8222. scanJsxToken: scanJsxToken,
  8223. scanJsDocToken: scanJsDocToken,
  8224. scan: scan,
  8225. getText: getText,
  8226. setText: setText,
  8227. setScriptTarget: setScriptTarget,
  8228. setLanguageVariant: setLanguageVariant,
  8229. setOnError: setOnError,
  8230. setTextPos: setTextPos,
  8231. setInJSDocType: setInJSDocType,
  8232. tryScan: tryScan,
  8233. lookAhead: lookAhead,
  8234. scanRange: scanRange,
  8235. };
  8236. if (ts.Debug.isDebugging) {
  8237. Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
  8238. get: function () {
  8239. var text = scanner.getText();
  8240. return text.slice(0, scanner.getStartPos()) + "║" + text.slice(scanner.getStartPos());
  8241. },
  8242. });
  8243. }
  8244. return scanner;
  8245. function error(message, errPos, length) {
  8246. if (errPos === void 0) { errPos = pos; }
  8247. if (onError) {
  8248. var oldPos = pos;
  8249. pos = errPos;
  8250. onError(message, length || 0);
  8251. pos = oldPos;
  8252. }
  8253. }
  8254. function scanNumberFragment() {
  8255. var start = pos;
  8256. var allowSeparator = false;
  8257. var isPreviousTokenSeparator = false;
  8258. var result = "";
  8259. while (true) {
  8260. var ch = text.charCodeAt(pos);
  8261. if (ch === 95 /* _ */) {
  8262. tokenFlags |= 512 /* ContainsSeparator */;
  8263. if (allowSeparator) {
  8264. allowSeparator = false;
  8265. isPreviousTokenSeparator = true;
  8266. result += text.substring(start, pos);
  8267. }
  8268. else if (isPreviousTokenSeparator) {
  8269. error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
  8270. }
  8271. else {
  8272. error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
  8273. }
  8274. pos++;
  8275. start = pos;
  8276. continue;
  8277. }
  8278. if (isDigit(ch)) {
  8279. allowSeparator = true;
  8280. isPreviousTokenSeparator = false;
  8281. pos++;
  8282. continue;
  8283. }
  8284. break;
  8285. }
  8286. if (text.charCodeAt(pos - 1) === 95 /* _ */) {
  8287. error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
  8288. }
  8289. return result + text.substring(start, pos);
  8290. }
  8291. function scanNumber() {
  8292. var start = pos;
  8293. var mainFragment = scanNumberFragment();
  8294. var decimalFragment;
  8295. var scientificFragment;
  8296. if (text.charCodeAt(pos) === 46 /* dot */) {
  8297. pos++;
  8298. decimalFragment = scanNumberFragment();
  8299. }
  8300. var end = pos;
  8301. if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
  8302. pos++;
  8303. tokenFlags |= 16 /* Scientific */;
  8304. if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
  8305. pos++;
  8306. var preNumericPart = pos;
  8307. var finalFragment = scanNumberFragment();
  8308. if (!finalFragment) {
  8309. error(ts.Diagnostics.Digit_expected);
  8310. }
  8311. else {
  8312. scientificFragment = text.substring(end, preNumericPart) + finalFragment;
  8313. end = pos;
  8314. }
  8315. }
  8316. var result;
  8317. if (tokenFlags & 512 /* ContainsSeparator */) {
  8318. result = mainFragment;
  8319. if (decimalFragment) {
  8320. result += "." + decimalFragment;
  8321. }
  8322. if (scientificFragment) {
  8323. result += scientificFragment;
  8324. }
  8325. }
  8326. else {
  8327. result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
  8328. }
  8329. if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
  8330. checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
  8331. return {
  8332. type: 8 /* NumericLiteral */,
  8333. value: "" + +result // if value is not an integer, it can be safely coerced to a number
  8334. };
  8335. }
  8336. else {
  8337. tokenValue = result;
  8338. var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
  8339. checkForIdentifierStartAfterNumericLiteral(start);
  8340. return { type: type, value: tokenValue };
  8341. }
  8342. }
  8343. function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
  8344. if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
  8345. return;
  8346. }
  8347. var identifierStart = pos;
  8348. var length = scanIdentifierParts().length;
  8349. if (length === 1 && text[identifierStart] === "n") {
  8350. if (isScientific) {
  8351. error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
  8352. }
  8353. else {
  8354. error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
  8355. }
  8356. }
  8357. else {
  8358. error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
  8359. pos = identifierStart;
  8360. }
  8361. }
  8362. function scanOctalDigits() {
  8363. var start = pos;
  8364. while (isOctalDigit(text.charCodeAt(pos))) {
  8365. pos++;
  8366. }
  8367. return +(text.substring(start, pos));
  8368. }
  8369. /**
  8370. * Scans the given number of hexadecimal digits in the text,
  8371. * returning -1 if the given number is unavailable.
  8372. */
  8373. function scanExactNumberOfHexDigits(count, canHaveSeparators) {
  8374. var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
  8375. return valueString ? parseInt(valueString, 16) : -1;
  8376. }
  8377. /**
  8378. * Scans as many hexadecimal digits as are available in the text,
  8379. * returning "" if the given number of digits was unavailable.
  8380. */
  8381. function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
  8382. return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
  8383. }
  8384. function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
  8385. var valueChars = [];
  8386. var allowSeparator = false;
  8387. var isPreviousTokenSeparator = false;
  8388. while (valueChars.length < minCount || scanAsManyAsPossible) {
  8389. var ch = text.charCodeAt(pos);
  8390. if (canHaveSeparators && ch === 95 /* _ */) {
  8391. tokenFlags |= 512 /* ContainsSeparator */;
  8392. if (allowSeparator) {
  8393. allowSeparator = false;
  8394. isPreviousTokenSeparator = true;
  8395. }
  8396. else if (isPreviousTokenSeparator) {
  8397. error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
  8398. }
  8399. else {
  8400. error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
  8401. }
  8402. pos++;
  8403. continue;
  8404. }
  8405. allowSeparator = canHaveSeparators;
  8406. if (ch >= 65 /* A */ && ch <= 70 /* F */) {
  8407. ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
  8408. }
  8409. else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
  8410. (ch >= 97 /* a */ && ch <= 102 /* f */))) {
  8411. break;
  8412. }
  8413. valueChars.push(ch);
  8414. pos++;
  8415. isPreviousTokenSeparator = false;
  8416. }
  8417. if (valueChars.length < minCount) {
  8418. valueChars = [];
  8419. }
  8420. if (text.charCodeAt(pos - 1) === 95 /* _ */) {
  8421. error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
  8422. }
  8423. return String.fromCharCode.apply(String, valueChars);
  8424. }
  8425. function scanString(jsxAttributeString) {
  8426. if (jsxAttributeString === void 0) { jsxAttributeString = false; }
  8427. var quote = text.charCodeAt(pos);
  8428. pos++;
  8429. var result = "";
  8430. var start = pos;
  8431. while (true) {
  8432. if (pos >= end) {
  8433. result += text.substring(start, pos);
  8434. tokenFlags |= 4 /* Unterminated */;
  8435. error(ts.Diagnostics.Unterminated_string_literal);
  8436. break;
  8437. }
  8438. var ch = text.charCodeAt(pos);
  8439. if (ch === quote) {
  8440. result += text.substring(start, pos);
  8441. pos++;
  8442. break;
  8443. }
  8444. if (ch === 92 /* backslash */ && !jsxAttributeString) {
  8445. result += text.substring(start, pos);
  8446. result += scanEscapeSequence();
  8447. start = pos;
  8448. continue;
  8449. }
  8450. if (isLineBreak(ch) && !jsxAttributeString) {
  8451. result += text.substring(start, pos);
  8452. tokenFlags |= 4 /* Unterminated */;
  8453. error(ts.Diagnostics.Unterminated_string_literal);
  8454. break;
  8455. }
  8456. pos++;
  8457. }
  8458. return result;
  8459. }
  8460. /**
  8461. * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
  8462. * a literal component of a TemplateExpression.
  8463. */
  8464. function scanTemplateAndSetTokenValue() {
  8465. var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
  8466. pos++;
  8467. var start = pos;
  8468. var contents = "";
  8469. var resultingToken;
  8470. while (true) {
  8471. if (pos >= end) {
  8472. contents += text.substring(start, pos);
  8473. tokenFlags |= 4 /* Unterminated */;
  8474. error(ts.Diagnostics.Unterminated_template_literal);
  8475. resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
  8476. break;
  8477. }
  8478. var currChar = text.charCodeAt(pos);
  8479. // '`'
  8480. if (currChar === 96 /* backtick */) {
  8481. contents += text.substring(start, pos);
  8482. pos++;
  8483. resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
  8484. break;
  8485. }
  8486. // '${'
  8487. if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
  8488. contents += text.substring(start, pos);
  8489. pos += 2;
  8490. resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
  8491. break;
  8492. }
  8493. // Escape character
  8494. if (currChar === 92 /* backslash */) {
  8495. contents += text.substring(start, pos);
  8496. contents += scanEscapeSequence();
  8497. start = pos;
  8498. continue;
  8499. }
  8500. // Speculated ECMAScript 6 Spec 11.8.6.1:
  8501. // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
  8502. if (currChar === 13 /* carriageReturn */) {
  8503. contents += text.substring(start, pos);
  8504. pos++;
  8505. if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
  8506. pos++;
  8507. }
  8508. contents += "\n";
  8509. start = pos;
  8510. continue;
  8511. }
  8512. pos++;
  8513. }
  8514. ts.Debug.assert(resultingToken !== undefined);
  8515. tokenValue = contents;
  8516. return resultingToken;
  8517. }
  8518. function scanEscapeSequence() {
  8519. pos++;
  8520. if (pos >= end) {
  8521. error(ts.Diagnostics.Unexpected_end_of_text);
  8522. return "";
  8523. }
  8524. var ch = text.charCodeAt(pos);
  8525. pos++;
  8526. switch (ch) {
  8527. case 48 /* _0 */:
  8528. return "\0";
  8529. case 98 /* b */:
  8530. return "\b";
  8531. case 116 /* t */:
  8532. return "\t";
  8533. case 110 /* n */:
  8534. return "\n";
  8535. case 118 /* v */:
  8536. return "\v";
  8537. case 102 /* f */:
  8538. return "\f";
  8539. case 114 /* r */:
  8540. return "\r";
  8541. case 39 /* singleQuote */:
  8542. return "\'";
  8543. case 34 /* doubleQuote */:
  8544. return "\"";
  8545. case 117 /* u */:
  8546. // '\u{DDDDDDDD}'
  8547. if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
  8548. tokenFlags |= 8 /* ExtendedUnicodeEscape */;
  8549. pos++;
  8550. return scanExtendedUnicodeEscape();
  8551. }
  8552. tokenFlags |= 1024 /* UnicodeEscape */;
  8553. // '\uDDDD'
  8554. return scanHexadecimalEscape(/*numDigits*/ 4);
  8555. case 120 /* x */:
  8556. // '\xDD'
  8557. return scanHexadecimalEscape(/*numDigits*/ 2);
  8558. // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
  8559. // the line terminator is interpreted to be "the empty code unit sequence".
  8560. case 13 /* carriageReturn */:
  8561. if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
  8562. pos++;
  8563. }
  8564. // falls through
  8565. case 10 /* lineFeed */:
  8566. case 8232 /* lineSeparator */:
  8567. case 8233 /* paragraphSeparator */:
  8568. return "";
  8569. default:
  8570. return String.fromCharCode(ch);
  8571. }
  8572. }
  8573. function scanHexadecimalEscape(numDigits) {
  8574. var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
  8575. if (escapedValue >= 0) {
  8576. return String.fromCharCode(escapedValue);
  8577. }
  8578. else {
  8579. error(ts.Diagnostics.Hexadecimal_digit_expected);
  8580. return "";
  8581. }
  8582. }
  8583. function scanExtendedUnicodeEscape() {
  8584. var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
  8585. var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
  8586. var isInvalidExtendedEscape = false;
  8587. // Validate the value of the digit
  8588. if (escapedValue < 0) {
  8589. error(ts.Diagnostics.Hexadecimal_digit_expected);
  8590. isInvalidExtendedEscape = true;
  8591. }
  8592. else if (escapedValue > 0x10FFFF) {
  8593. error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
  8594. isInvalidExtendedEscape = true;
  8595. }
  8596. if (pos >= end) {
  8597. error(ts.Diagnostics.Unexpected_end_of_text);
  8598. isInvalidExtendedEscape = true;
  8599. }
  8600. else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
  8601. // Only swallow the following character up if it's a '}'.
  8602. pos++;
  8603. }
  8604. else {
  8605. error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
  8606. isInvalidExtendedEscape = true;
  8607. }
  8608. if (isInvalidExtendedEscape) {
  8609. return "";
  8610. }
  8611. return utf16EncodeAsString(escapedValue);
  8612. }
  8613. // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
  8614. // and return code point value if valid Unicode escape is found. Otherwise return -1.
  8615. function peekUnicodeEscape() {
  8616. if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
  8617. var start_1 = pos;
  8618. pos += 2;
  8619. var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
  8620. pos = start_1;
  8621. return value;
  8622. }
  8623. return -1;
  8624. }
  8625. function peekExtendedUnicodeEscape() {
  8626. if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
  8627. var start_2 = pos;
  8628. pos += 3;
  8629. var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
  8630. var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
  8631. pos = start_2;
  8632. return escapedValue;
  8633. }
  8634. return -1;
  8635. }
  8636. function scanIdentifierParts() {
  8637. var result = "";
  8638. var start = pos;
  8639. while (pos < end) {
  8640. var ch = codePointAt(text, pos);
  8641. if (isIdentifierPart(ch, languageVersion)) {
  8642. pos += charSize(ch);
  8643. }
  8644. else if (ch === 92 /* backslash */) {
  8645. ch = peekExtendedUnicodeEscape();
  8646. if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
  8647. pos += 3;
  8648. tokenFlags |= 8 /* ExtendedUnicodeEscape */;
  8649. result += scanExtendedUnicodeEscape();
  8650. start = pos;
  8651. continue;
  8652. }
  8653. ch = peekUnicodeEscape();
  8654. if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
  8655. break;
  8656. }
  8657. tokenFlags |= 1024 /* UnicodeEscape */;
  8658. result += text.substring(start, pos);
  8659. result += utf16EncodeAsString(ch);
  8660. // Valid Unicode escape is always six characters
  8661. pos += 6;
  8662. start = pos;
  8663. }
  8664. else {
  8665. break;
  8666. }
  8667. }
  8668. result += text.substring(start, pos);
  8669. return result;
  8670. }
  8671. function getIdentifierToken() {
  8672. // Reserved words are between 2 and 11 characters long and start with a lowercase letter
  8673. var len = tokenValue.length;
  8674. if (len >= 2 && len <= 11) {
  8675. var ch = tokenValue.charCodeAt(0);
  8676. if (ch >= 97 /* a */ && ch <= 122 /* z */) {
  8677. var keyword = textToKeyword.get(tokenValue);
  8678. if (keyword !== undefined) {
  8679. return token = keyword;
  8680. }
  8681. }
  8682. }
  8683. return token = 75 /* Identifier */;
  8684. }
  8685. function scanBinaryOrOctalDigits(base) {
  8686. var value = "";
  8687. // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
  8688. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
  8689. var separatorAllowed = false;
  8690. var isPreviousTokenSeparator = false;
  8691. while (true) {
  8692. var ch = text.charCodeAt(pos);
  8693. // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
  8694. if (ch === 95 /* _ */) {
  8695. tokenFlags |= 512 /* ContainsSeparator */;
  8696. if (separatorAllowed) {
  8697. separatorAllowed = false;
  8698. isPreviousTokenSeparator = true;
  8699. }
  8700. else if (isPreviousTokenSeparator) {
  8701. error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
  8702. }
  8703. else {
  8704. error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
  8705. }
  8706. pos++;
  8707. continue;
  8708. }
  8709. separatorAllowed = true;
  8710. if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
  8711. break;
  8712. }
  8713. value += text[pos];
  8714. pos++;
  8715. isPreviousTokenSeparator = false;
  8716. }
  8717. if (text.charCodeAt(pos - 1) === 95 /* _ */) {
  8718. // Literal ends with underscore - not allowed
  8719. error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
  8720. }
  8721. return value;
  8722. }
  8723. function checkBigIntSuffix() {
  8724. if (text.charCodeAt(pos) === 110 /* n */) {
  8725. tokenValue += "n";
  8726. // Use base 10 instead of base 2 or base 8 for shorter literals
  8727. if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
  8728. tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
  8729. }
  8730. pos++;
  8731. return 9 /* BigIntLiteral */;
  8732. }
  8733. else { // not a bigint, so can convert to number in simplified form
  8734. // Number() may not support 0b or 0o, so use parseInt() instead
  8735. var numericValue = tokenFlags & 128 /* BinarySpecifier */
  8736. ? parseInt(tokenValue.slice(2), 2) // skip "0b"
  8737. : tokenFlags & 256 /* OctalSpecifier */
  8738. ? parseInt(tokenValue.slice(2), 8) // skip "0o"
  8739. : +tokenValue;
  8740. tokenValue = "" + numericValue;
  8741. return 8 /* NumericLiteral */;
  8742. }
  8743. }
  8744. function scan() {
  8745. var _a;
  8746. startPos = pos;
  8747. tokenFlags = 0 /* None */;
  8748. var asteriskSeen = false;
  8749. while (true) {
  8750. tokenPos = pos;
  8751. if (pos >= end) {
  8752. return token = 1 /* EndOfFileToken */;
  8753. }
  8754. var ch = codePointAt(text, pos);
  8755. // Special handling for shebang
  8756. if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
  8757. pos = scanShebangTrivia(text, pos);
  8758. if (skipTrivia) {
  8759. continue;
  8760. }
  8761. else {
  8762. return token = 6 /* ShebangTrivia */;
  8763. }
  8764. }
  8765. switch (ch) {
  8766. case 10 /* lineFeed */:
  8767. case 13 /* carriageReturn */:
  8768. tokenFlags |= 1 /* PrecedingLineBreak */;
  8769. if (skipTrivia) {
  8770. pos++;
  8771. continue;
  8772. }
  8773. else {
  8774. if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
  8775. // consume both CR and LF
  8776. pos += 2;
  8777. }
  8778. else {
  8779. pos++;
  8780. }
  8781. return token = 4 /* NewLineTrivia */;
  8782. }
  8783. case 9 /* tab */:
  8784. case 11 /* verticalTab */:
  8785. case 12 /* formFeed */:
  8786. case 32 /* space */:
  8787. case 160 /* nonBreakingSpace */:
  8788. case 5760 /* ogham */:
  8789. case 8192 /* enQuad */:
  8790. case 8193 /* emQuad */:
  8791. case 8194 /* enSpace */:
  8792. case 8195 /* emSpace */:
  8793. case 8196 /* threePerEmSpace */:
  8794. case 8197 /* fourPerEmSpace */:
  8795. case 8198 /* sixPerEmSpace */:
  8796. case 8199 /* figureSpace */:
  8797. case 8200 /* punctuationSpace */:
  8798. case 8201 /* thinSpace */:
  8799. case 8202 /* hairSpace */:
  8800. case 8203 /* zeroWidthSpace */:
  8801. case 8239 /* narrowNoBreakSpace */:
  8802. case 8287 /* mathematicalSpace */:
  8803. case 12288 /* ideographicSpace */:
  8804. case 65279 /* byteOrderMark */:
  8805. if (skipTrivia) {
  8806. pos++;
  8807. continue;
  8808. }
  8809. else {
  8810. while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
  8811. pos++;
  8812. }
  8813. return token = 5 /* WhitespaceTrivia */;
  8814. }
  8815. case 33 /* exclamation */:
  8816. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8817. if (text.charCodeAt(pos + 2) === 61 /* equals */) {
  8818. return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
  8819. }
  8820. return pos += 2, token = 35 /* ExclamationEqualsToken */;
  8821. }
  8822. pos++;
  8823. return token = 53 /* ExclamationToken */;
  8824. case 34 /* doubleQuote */:
  8825. case 39 /* singleQuote */:
  8826. tokenValue = scanString();
  8827. return token = 10 /* StringLiteral */;
  8828. case 96 /* backtick */:
  8829. return token = scanTemplateAndSetTokenValue();
  8830. case 37 /* percent */:
  8831. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8832. return pos += 2, token = 68 /* PercentEqualsToken */;
  8833. }
  8834. pos++;
  8835. return token = 44 /* PercentToken */;
  8836. case 38 /* ampersand */:
  8837. if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
  8838. return pos += 2, token = 55 /* AmpersandAmpersandToken */;
  8839. }
  8840. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8841. return pos += 2, token = 72 /* AmpersandEqualsToken */;
  8842. }
  8843. pos++;
  8844. return token = 50 /* AmpersandToken */;
  8845. case 40 /* openParen */:
  8846. pos++;
  8847. return token = 20 /* OpenParenToken */;
  8848. case 41 /* closeParen */:
  8849. pos++;
  8850. return token = 21 /* CloseParenToken */;
  8851. case 42 /* asterisk */:
  8852. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8853. return pos += 2, token = 65 /* AsteriskEqualsToken */;
  8854. }
  8855. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  8856. if (text.charCodeAt(pos + 2) === 61 /* equals */) {
  8857. return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
  8858. }
  8859. return pos += 2, token = 42 /* AsteriskAsteriskToken */;
  8860. }
  8861. pos++;
  8862. if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
  8863. // decoration at the start of a JSDoc comment line
  8864. asteriskSeen = true;
  8865. continue;
  8866. }
  8867. return token = 41 /* AsteriskToken */;
  8868. case 43 /* plus */:
  8869. if (text.charCodeAt(pos + 1) === 43 /* plus */) {
  8870. return pos += 2, token = 45 /* PlusPlusToken */;
  8871. }
  8872. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8873. return pos += 2, token = 63 /* PlusEqualsToken */;
  8874. }
  8875. pos++;
  8876. return token = 39 /* PlusToken */;
  8877. case 44 /* comma */:
  8878. pos++;
  8879. return token = 27 /* CommaToken */;
  8880. case 45 /* minus */:
  8881. if (text.charCodeAt(pos + 1) === 45 /* minus */) {
  8882. return pos += 2, token = 46 /* MinusMinusToken */;
  8883. }
  8884. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8885. return pos += 2, token = 64 /* MinusEqualsToken */;
  8886. }
  8887. pos++;
  8888. return token = 40 /* MinusToken */;
  8889. case 46 /* dot */:
  8890. if (isDigit(text.charCodeAt(pos + 1))) {
  8891. tokenValue = scanNumber().value;
  8892. return token = 8 /* NumericLiteral */;
  8893. }
  8894. if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
  8895. return pos += 3, token = 25 /* DotDotDotToken */;
  8896. }
  8897. pos++;
  8898. return token = 24 /* DotToken */;
  8899. case 47 /* slash */:
  8900. // Single-line comment
  8901. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  8902. pos += 2;
  8903. while (pos < end) {
  8904. if (isLineBreak(text.charCodeAt(pos))) {
  8905. break;
  8906. }
  8907. pos++;
  8908. }
  8909. if (skipTrivia) {
  8910. continue;
  8911. }
  8912. else {
  8913. return token = 2 /* SingleLineCommentTrivia */;
  8914. }
  8915. }
  8916. // Multi-line comment
  8917. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  8918. pos += 2;
  8919. if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
  8920. tokenFlags |= 2 /* PrecedingJSDocComment */;
  8921. }
  8922. var commentClosed = false;
  8923. while (pos < end) {
  8924. var ch_1 = text.charCodeAt(pos);
  8925. if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  8926. pos += 2;
  8927. commentClosed = true;
  8928. break;
  8929. }
  8930. if (isLineBreak(ch_1)) {
  8931. tokenFlags |= 1 /* PrecedingLineBreak */;
  8932. }
  8933. pos++;
  8934. }
  8935. if (!commentClosed) {
  8936. error(ts.Diagnostics.Asterisk_Slash_expected);
  8937. }
  8938. if (skipTrivia) {
  8939. continue;
  8940. }
  8941. else {
  8942. if (!commentClosed) {
  8943. tokenFlags |= 4 /* Unterminated */;
  8944. }
  8945. return token = 3 /* MultiLineCommentTrivia */;
  8946. }
  8947. }
  8948. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  8949. return pos += 2, token = 67 /* SlashEqualsToken */;
  8950. }
  8951. pos++;
  8952. return token = 43 /* SlashToken */;
  8953. case 48 /* _0 */:
  8954. if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
  8955. pos += 2;
  8956. tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
  8957. if (!tokenValue) {
  8958. error(ts.Diagnostics.Hexadecimal_digit_expected);
  8959. tokenValue = "0";
  8960. }
  8961. tokenValue = "0x" + tokenValue;
  8962. tokenFlags |= 64 /* HexSpecifier */;
  8963. return token = checkBigIntSuffix();
  8964. }
  8965. else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
  8966. pos += 2;
  8967. tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
  8968. if (!tokenValue) {
  8969. error(ts.Diagnostics.Binary_digit_expected);
  8970. tokenValue = "0";
  8971. }
  8972. tokenValue = "0b" + tokenValue;
  8973. tokenFlags |= 128 /* BinarySpecifier */;
  8974. return token = checkBigIntSuffix();
  8975. }
  8976. else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
  8977. pos += 2;
  8978. tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
  8979. if (!tokenValue) {
  8980. error(ts.Diagnostics.Octal_digit_expected);
  8981. tokenValue = "0";
  8982. }
  8983. tokenValue = "0o" + tokenValue;
  8984. tokenFlags |= 256 /* OctalSpecifier */;
  8985. return token = checkBigIntSuffix();
  8986. }
  8987. // Try to parse as an octal
  8988. if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
  8989. tokenValue = "" + scanOctalDigits();
  8990. tokenFlags |= 32 /* Octal */;
  8991. return token = 8 /* NumericLiteral */;
  8992. }
  8993. // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
  8994. // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
  8995. // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
  8996. // falls through
  8997. case 49 /* _1 */:
  8998. case 50 /* _2 */:
  8999. case 51 /* _3 */:
  9000. case 52 /* _4 */:
  9001. case 53 /* _5 */:
  9002. case 54 /* _6 */:
  9003. case 55 /* _7 */:
  9004. case 56 /* _8 */:
  9005. case 57 /* _9 */:
  9006. (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
  9007. return token;
  9008. case 58 /* colon */:
  9009. pos++;
  9010. return token = 58 /* ColonToken */;
  9011. case 59 /* semicolon */:
  9012. pos++;
  9013. return token = 26 /* SemicolonToken */;
  9014. case 60 /* lessThan */:
  9015. if (isConflictMarkerTrivia(text, pos)) {
  9016. pos = scanConflictMarkerTrivia(text, pos, error);
  9017. if (skipTrivia) {
  9018. continue;
  9019. }
  9020. else {
  9021. return token = 7 /* ConflictMarkerTrivia */;
  9022. }
  9023. }
  9024. if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
  9025. if (text.charCodeAt(pos + 2) === 61 /* equals */) {
  9026. return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
  9027. }
  9028. return pos += 2, token = 47 /* LessThanLessThanToken */;
  9029. }
  9030. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  9031. return pos += 2, token = 32 /* LessThanEqualsToken */;
  9032. }
  9033. if (languageVariant === 1 /* JSX */ &&
  9034. text.charCodeAt(pos + 1) === 47 /* slash */ &&
  9035. text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
  9036. return pos += 2, token = 30 /* LessThanSlashToken */;
  9037. }
  9038. pos++;
  9039. return token = 29 /* LessThanToken */;
  9040. case 61 /* equals */:
  9041. if (isConflictMarkerTrivia(text, pos)) {
  9042. pos = scanConflictMarkerTrivia(text, pos, error);
  9043. if (skipTrivia) {
  9044. continue;
  9045. }
  9046. else {
  9047. return token = 7 /* ConflictMarkerTrivia */;
  9048. }
  9049. }
  9050. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  9051. if (text.charCodeAt(pos + 2) === 61 /* equals */) {
  9052. return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
  9053. }
  9054. return pos += 2, token = 34 /* EqualsEqualsToken */;
  9055. }
  9056. if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
  9057. return pos += 2, token = 38 /* EqualsGreaterThanToken */;
  9058. }
  9059. pos++;
  9060. return token = 62 /* EqualsToken */;
  9061. case 62 /* greaterThan */:
  9062. if (isConflictMarkerTrivia(text, pos)) {
  9063. pos = scanConflictMarkerTrivia(text, pos, error);
  9064. if (skipTrivia) {
  9065. continue;
  9066. }
  9067. else {
  9068. return token = 7 /* ConflictMarkerTrivia */;
  9069. }
  9070. }
  9071. pos++;
  9072. return token = 31 /* GreaterThanToken */;
  9073. case 63 /* question */:
  9074. pos++;
  9075. if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
  9076. pos++;
  9077. return token = 28 /* QuestionDotToken */;
  9078. }
  9079. if (text.charCodeAt(pos) === 63 /* question */) {
  9080. pos++;
  9081. return token = 60 /* QuestionQuestionToken */;
  9082. }
  9083. return token = 57 /* QuestionToken */;
  9084. case 91 /* openBracket */:
  9085. pos++;
  9086. return token = 22 /* OpenBracketToken */;
  9087. case 93 /* closeBracket */:
  9088. pos++;
  9089. return token = 23 /* CloseBracketToken */;
  9090. case 94 /* caret */:
  9091. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  9092. return pos += 2, token = 74 /* CaretEqualsToken */;
  9093. }
  9094. pos++;
  9095. return token = 52 /* CaretToken */;
  9096. case 123 /* openBrace */:
  9097. pos++;
  9098. return token = 18 /* OpenBraceToken */;
  9099. case 124 /* bar */:
  9100. if (isConflictMarkerTrivia(text, pos)) {
  9101. pos = scanConflictMarkerTrivia(text, pos, error);
  9102. if (skipTrivia) {
  9103. continue;
  9104. }
  9105. else {
  9106. return token = 7 /* ConflictMarkerTrivia */;
  9107. }
  9108. }
  9109. if (text.charCodeAt(pos + 1) === 124 /* bar */) {
  9110. return pos += 2, token = 56 /* BarBarToken */;
  9111. }
  9112. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  9113. return pos += 2, token = 73 /* BarEqualsToken */;
  9114. }
  9115. pos++;
  9116. return token = 51 /* BarToken */;
  9117. case 125 /* closeBrace */:
  9118. pos++;
  9119. return token = 19 /* CloseBraceToken */;
  9120. case 126 /* tilde */:
  9121. pos++;
  9122. return token = 54 /* TildeToken */;
  9123. case 64 /* at */:
  9124. pos++;
  9125. return token = 59 /* AtToken */;
  9126. case 92 /* backslash */:
  9127. var extendedCookedChar = peekExtendedUnicodeEscape();
  9128. if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
  9129. pos += 3;
  9130. tokenFlags |= 8 /* ExtendedUnicodeEscape */;
  9131. tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
  9132. return token = getIdentifierToken();
  9133. }
  9134. var cookedChar = peekUnicodeEscape();
  9135. if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
  9136. pos += 6;
  9137. tokenFlags |= 1024 /* UnicodeEscape */;
  9138. tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
  9139. return token = getIdentifierToken();
  9140. }
  9141. error(ts.Diagnostics.Invalid_character);
  9142. pos++;
  9143. return token = 0 /* Unknown */;
  9144. case 35 /* hash */:
  9145. if (pos !== 0 && text[pos + 1] === "!") {
  9146. error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
  9147. pos++;
  9148. return token = 0 /* Unknown */;
  9149. }
  9150. pos++;
  9151. if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
  9152. pos++;
  9153. while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
  9154. pos++;
  9155. tokenValue = text.substring(tokenPos, pos);
  9156. if (ch === 92 /* backslash */) {
  9157. tokenValue += scanIdentifierParts();
  9158. }
  9159. }
  9160. else {
  9161. tokenValue = "#";
  9162. error(ts.Diagnostics.Invalid_character);
  9163. }
  9164. return token = 76 /* PrivateIdentifier */;
  9165. default:
  9166. if (isIdentifierStart(ch, languageVersion)) {
  9167. pos += charSize(ch);
  9168. while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
  9169. pos += charSize(ch);
  9170. tokenValue = text.substring(tokenPos, pos);
  9171. if (ch === 92 /* backslash */) {
  9172. tokenValue += scanIdentifierParts();
  9173. }
  9174. return token = getIdentifierToken();
  9175. }
  9176. else if (isWhiteSpaceSingleLine(ch)) {
  9177. pos += charSize(ch);
  9178. continue;
  9179. }
  9180. else if (isLineBreak(ch)) {
  9181. tokenFlags |= 1 /* PrecedingLineBreak */;
  9182. pos += charSize(ch);
  9183. continue;
  9184. }
  9185. error(ts.Diagnostics.Invalid_character);
  9186. pos += charSize(ch);
  9187. return token = 0 /* Unknown */;
  9188. }
  9189. }
  9190. }
  9191. function reScanGreaterToken() {
  9192. if (token === 31 /* GreaterThanToken */) {
  9193. if (text.charCodeAt(pos) === 62 /* greaterThan */) {
  9194. if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
  9195. if (text.charCodeAt(pos + 2) === 61 /* equals */) {
  9196. return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
  9197. }
  9198. return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
  9199. }
  9200. if (text.charCodeAt(pos + 1) === 61 /* equals */) {
  9201. return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
  9202. }
  9203. pos++;
  9204. return token = 48 /* GreaterThanGreaterThanToken */;
  9205. }
  9206. if (text.charCodeAt(pos) === 61 /* equals */) {
  9207. pos++;
  9208. return token = 33 /* GreaterThanEqualsToken */;
  9209. }
  9210. }
  9211. return token;
  9212. }
  9213. function reScanSlashToken() {
  9214. if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
  9215. var p = tokenPos + 1;
  9216. var inEscape = false;
  9217. var inCharacterClass = false;
  9218. while (true) {
  9219. // If we reach the end of a file, or hit a newline, then this is an unterminated
  9220. // regex. Report error and return what we have so far.
  9221. if (p >= end) {
  9222. tokenFlags |= 4 /* Unterminated */;
  9223. error(ts.Diagnostics.Unterminated_regular_expression_literal);
  9224. break;
  9225. }
  9226. var ch = text.charCodeAt(p);
  9227. if (isLineBreak(ch)) {
  9228. tokenFlags |= 4 /* Unterminated */;
  9229. error(ts.Diagnostics.Unterminated_regular_expression_literal);
  9230. break;
  9231. }
  9232. if (inEscape) {
  9233. // Parsing an escape character;
  9234. // reset the flag and just advance to the next char.
  9235. inEscape = false;
  9236. }
  9237. else if (ch === 47 /* slash */ && !inCharacterClass) {
  9238. // A slash within a character class is permissible,
  9239. // but in general it signals the end of the regexp literal.
  9240. p++;
  9241. break;
  9242. }
  9243. else if (ch === 91 /* openBracket */) {
  9244. inCharacterClass = true;
  9245. }
  9246. else if (ch === 92 /* backslash */) {
  9247. inEscape = true;
  9248. }
  9249. else if (ch === 93 /* closeBracket */) {
  9250. inCharacterClass = false;
  9251. }
  9252. p++;
  9253. }
  9254. while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
  9255. p++;
  9256. }
  9257. pos = p;
  9258. tokenValue = text.substring(tokenPos, pos);
  9259. token = 13 /* RegularExpressionLiteral */;
  9260. }
  9261. return token;
  9262. }
  9263. /**
  9264. * Unconditionally back up and scan a template expression portion.
  9265. */
  9266. function reScanTemplateToken() {
  9267. ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
  9268. pos = tokenPos;
  9269. return token = scanTemplateAndSetTokenValue();
  9270. }
  9271. function reScanJsxToken() {
  9272. pos = tokenPos = startPos;
  9273. return token = scanJsxToken();
  9274. }
  9275. function reScanLessThanToken() {
  9276. if (token === 47 /* LessThanLessThanToken */) {
  9277. pos = tokenPos + 1;
  9278. return token = 29 /* LessThanToken */;
  9279. }
  9280. return token;
  9281. }
  9282. function reScanQuestionToken() {
  9283. ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
  9284. pos = tokenPos + 1;
  9285. return token = 57 /* QuestionToken */;
  9286. }
  9287. function scanJsxToken() {
  9288. startPos = tokenPos = pos;
  9289. if (pos >= end) {
  9290. return token = 1 /* EndOfFileToken */;
  9291. }
  9292. var char = text.charCodeAt(pos);
  9293. if (char === 60 /* lessThan */) {
  9294. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  9295. pos += 2;
  9296. return token = 30 /* LessThanSlashToken */;
  9297. }
  9298. pos++;
  9299. return token = 29 /* LessThanToken */;
  9300. }
  9301. if (char === 123 /* openBrace */) {
  9302. pos++;
  9303. return token = 18 /* OpenBraceToken */;
  9304. }
  9305. // First non-whitespace character on this line.
  9306. var firstNonWhitespace = 0;
  9307. var lastNonWhitespace = -1;
  9308. // These initial values are special because the first line is:
  9309. // firstNonWhitespace = 0 to indicate that we want leading whitespace,
  9310. while (pos < end) {
  9311. // We want to keep track of the last non-whitespace (but including
  9312. // newlines character for hitting the end of the JSX Text region)
  9313. if (!isWhiteSpaceSingleLine(char)) {
  9314. lastNonWhitespace = pos;
  9315. }
  9316. char = text.charCodeAt(pos);
  9317. if (char === 123 /* openBrace */) {
  9318. break;
  9319. }
  9320. if (char === 60 /* lessThan */) {
  9321. if (isConflictMarkerTrivia(text, pos)) {
  9322. pos = scanConflictMarkerTrivia(text, pos, error);
  9323. return token = 7 /* ConflictMarkerTrivia */;
  9324. }
  9325. break;
  9326. }
  9327. if (lastNonWhitespace > 0)
  9328. lastNonWhitespace++;
  9329. // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
  9330. // i.e (- : whitespace)
  9331. // <div>----
  9332. // </div> becomes <div></div>
  9333. //
  9334. // <div>----</div> becomes <div>----</div>
  9335. if (isLineBreak(char) && firstNonWhitespace === 0) {
  9336. firstNonWhitespace = -1;
  9337. }
  9338. else if (!isWhiteSpaceLike(char)) {
  9339. firstNonWhitespace = pos;
  9340. }
  9341. pos++;
  9342. }
  9343. var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
  9344. tokenValue = text.substring(startPos, endPosition);
  9345. return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
  9346. }
  9347. // Scans a JSX identifier; these differ from normal identifiers in that
  9348. // they allow dashes
  9349. function scanJsxIdentifier() {
  9350. if (tokenIsIdentifierOrKeyword(token)) {
  9351. // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
  9352. // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
  9353. // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
  9354. while (pos < end) {
  9355. var ch = text.charCodeAt(pos);
  9356. if (ch === 45 /* minus */) {
  9357. tokenValue += "-";
  9358. pos++;
  9359. continue;
  9360. }
  9361. var oldPos = pos;
  9362. tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
  9363. if (pos === oldPos) {
  9364. break;
  9365. }
  9366. }
  9367. }
  9368. return token;
  9369. }
  9370. function scanJsxAttributeValue() {
  9371. startPos = pos;
  9372. switch (text.charCodeAt(pos)) {
  9373. case 34 /* doubleQuote */:
  9374. case 39 /* singleQuote */:
  9375. tokenValue = scanString(/*jsxAttributeString*/ true);
  9376. return token = 10 /* StringLiteral */;
  9377. default:
  9378. // If this scans anything other than `{`, it's a parse error.
  9379. return scan();
  9380. }
  9381. }
  9382. function reScanJsxAttributeValue() {
  9383. pos = tokenPos = startPos;
  9384. return scanJsxAttributeValue();
  9385. }
  9386. function scanJsDocToken() {
  9387. startPos = tokenPos = pos;
  9388. tokenFlags = 0 /* None */;
  9389. if (pos >= end) {
  9390. return token = 1 /* EndOfFileToken */;
  9391. }
  9392. var ch = codePointAt(text, pos);
  9393. pos += charSize(ch);
  9394. switch (ch) {
  9395. case 9 /* tab */:
  9396. case 11 /* verticalTab */:
  9397. case 12 /* formFeed */:
  9398. case 32 /* space */:
  9399. while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
  9400. pos++;
  9401. }
  9402. return token = 5 /* WhitespaceTrivia */;
  9403. case 64 /* at */:
  9404. return token = 59 /* AtToken */;
  9405. case 10 /* lineFeed */:
  9406. case 13 /* carriageReturn */:
  9407. tokenFlags |= 1 /* PrecedingLineBreak */;
  9408. return token = 4 /* NewLineTrivia */;
  9409. case 42 /* asterisk */:
  9410. return token = 41 /* AsteriskToken */;
  9411. case 123 /* openBrace */:
  9412. return token = 18 /* OpenBraceToken */;
  9413. case 125 /* closeBrace */:
  9414. return token = 19 /* CloseBraceToken */;
  9415. case 91 /* openBracket */:
  9416. return token = 22 /* OpenBracketToken */;
  9417. case 93 /* closeBracket */:
  9418. return token = 23 /* CloseBracketToken */;
  9419. case 60 /* lessThan */:
  9420. return token = 29 /* LessThanToken */;
  9421. case 62 /* greaterThan */:
  9422. return token = 31 /* GreaterThanToken */;
  9423. case 61 /* equals */:
  9424. return token = 62 /* EqualsToken */;
  9425. case 44 /* comma */:
  9426. return token = 27 /* CommaToken */;
  9427. case 46 /* dot */:
  9428. return token = 24 /* DotToken */;
  9429. case 96 /* backtick */:
  9430. return token = 61 /* BacktickToken */;
  9431. case 92 /* backslash */:
  9432. pos--;
  9433. var extendedCookedChar = peekExtendedUnicodeEscape();
  9434. if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
  9435. pos += 3;
  9436. tokenFlags |= 8 /* ExtendedUnicodeEscape */;
  9437. tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
  9438. return token = getIdentifierToken();
  9439. }
  9440. var cookedChar = peekUnicodeEscape();
  9441. if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
  9442. pos += 6;
  9443. tokenFlags |= 1024 /* UnicodeEscape */;
  9444. tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
  9445. return token = getIdentifierToken();
  9446. }
  9447. pos++;
  9448. return token = 0 /* Unknown */;
  9449. }
  9450. if (isIdentifierStart(ch, languageVersion)) {
  9451. var char = ch;
  9452. while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
  9453. pos += charSize(char);
  9454. tokenValue = text.substring(tokenPos, pos);
  9455. if (char === 92 /* backslash */) {
  9456. tokenValue += scanIdentifierParts();
  9457. }
  9458. return token = getIdentifierToken();
  9459. }
  9460. else {
  9461. return token = 0 /* Unknown */;
  9462. }
  9463. }
  9464. function speculationHelper(callback, isLookahead) {
  9465. var savePos = pos;
  9466. var saveStartPos = startPos;
  9467. var saveTokenPos = tokenPos;
  9468. var saveToken = token;
  9469. var saveTokenValue = tokenValue;
  9470. var saveTokenFlags = tokenFlags;
  9471. var result = callback();
  9472. // If our callback returned something 'falsy' or we're just looking ahead,
  9473. // then unconditionally restore us to where we were.
  9474. if (!result || isLookahead) {
  9475. pos = savePos;
  9476. startPos = saveStartPos;
  9477. tokenPos = saveTokenPos;
  9478. token = saveToken;
  9479. tokenValue = saveTokenValue;
  9480. tokenFlags = saveTokenFlags;
  9481. }
  9482. return result;
  9483. }
  9484. function scanRange(start, length, callback) {
  9485. var saveEnd = end;
  9486. var savePos = pos;
  9487. var saveStartPos = startPos;
  9488. var saveTokenPos = tokenPos;
  9489. var saveToken = token;
  9490. var saveTokenValue = tokenValue;
  9491. var saveTokenFlags = tokenFlags;
  9492. setText(text, start, length);
  9493. var result = callback();
  9494. end = saveEnd;
  9495. pos = savePos;
  9496. startPos = saveStartPos;
  9497. tokenPos = saveTokenPos;
  9498. token = saveToken;
  9499. tokenValue = saveTokenValue;
  9500. tokenFlags = saveTokenFlags;
  9501. return result;
  9502. }
  9503. function lookAhead(callback) {
  9504. return speculationHelper(callback, /*isLookahead*/ true);
  9505. }
  9506. function tryScan(callback) {
  9507. return speculationHelper(callback, /*isLookahead*/ false);
  9508. }
  9509. function getText() {
  9510. return text;
  9511. }
  9512. function setText(newText, start, length) {
  9513. text = newText || "";
  9514. end = length === undefined ? text.length : start + length;
  9515. setTextPos(start || 0);
  9516. }
  9517. function setOnError(errorCallback) {
  9518. onError = errorCallback;
  9519. }
  9520. function setScriptTarget(scriptTarget) {
  9521. languageVersion = scriptTarget;
  9522. }
  9523. function setLanguageVariant(variant) {
  9524. languageVariant = variant;
  9525. }
  9526. function setTextPos(textPos) {
  9527. ts.Debug.assert(textPos >= 0);
  9528. pos = textPos;
  9529. startPos = textPos;
  9530. tokenPos = textPos;
  9531. token = 0 /* Unknown */;
  9532. tokenValue = undefined;
  9533. tokenFlags = 0 /* None */;
  9534. }
  9535. function setInJSDocType(inType) {
  9536. inJSDocType += inType ? 1 : -1;
  9537. }
  9538. }
  9539. ts.createScanner = createScanner;
  9540. /* @internal */
  9541. var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
  9542. // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
  9543. var size = str.length;
  9544. // Account for out-of-bounds indices:
  9545. if (i < 0 || i >= size) {
  9546. return undefined; // String.codePointAt returns `undefined` for OOB indexes
  9547. }
  9548. // Get the first code unit
  9549. var first = str.charCodeAt(i);
  9550. // check if it’s the start of a surrogate pair
  9551. if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
  9552. var second = str.charCodeAt(i + 1);
  9553. if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
  9554. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  9555. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  9556. }
  9557. }
  9558. return first;
  9559. };
  9560. /* @internal */
  9561. function charSize(ch) {
  9562. if (ch >= 0x10000) {
  9563. return 2;
  9564. }
  9565. return 1;
  9566. }
  9567. // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
  9568. function utf16EncodeAsStringFallback(codePoint) {
  9569. ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
  9570. if (codePoint <= 65535) {
  9571. return String.fromCharCode(codePoint);
  9572. }
  9573. var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
  9574. var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
  9575. return String.fromCharCode(codeUnit1, codeUnit2);
  9576. }
  9577. var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
  9578. /* @internal */
  9579. function utf16EncodeAsString(codePoint) {
  9580. return utf16EncodeAsStringWorker(codePoint);
  9581. }
  9582. ts.utf16EncodeAsString = utf16EncodeAsString;
  9583. })(ts || (ts = {}));
  9584. var ts;
  9585. (function (ts) {
  9586. function isExternalModuleNameRelative(moduleName) {
  9587. // TypeScript 1.0 spec (April 2014): 11.2.1
  9588. // An external module name is "relative" if the first term is "." or "..".
  9589. // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module.
  9590. return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
  9591. }
  9592. ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
  9593. function sortAndDeduplicateDiagnostics(diagnostics) {
  9594. return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
  9595. }
  9596. ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
  9597. function getDefaultLibFileName(options) {
  9598. switch (options.target) {
  9599. case 99 /* ESNext */:
  9600. return "lib.esnext.full.d.ts";
  9601. case 7 /* ES2020 */:
  9602. return "lib.es2020.full.d.ts";
  9603. case 6 /* ES2019 */:
  9604. return "lib.es2019.full.d.ts";
  9605. case 5 /* ES2018 */:
  9606. return "lib.es2018.full.d.ts";
  9607. case 4 /* ES2017 */:
  9608. return "lib.es2017.full.d.ts";
  9609. case 3 /* ES2016 */:
  9610. return "lib.es2016.full.d.ts";
  9611. case 2 /* ES2015 */:
  9612. return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
  9613. default:
  9614. return "lib.d.ts";
  9615. }
  9616. }
  9617. ts.getDefaultLibFileName = getDefaultLibFileName;
  9618. function textSpanEnd(span) {
  9619. return span.start + span.length;
  9620. }
  9621. ts.textSpanEnd = textSpanEnd;
  9622. function textSpanIsEmpty(span) {
  9623. return span.length === 0;
  9624. }
  9625. ts.textSpanIsEmpty = textSpanIsEmpty;
  9626. function textSpanContainsPosition(span, position) {
  9627. return position >= span.start && position < textSpanEnd(span);
  9628. }
  9629. ts.textSpanContainsPosition = textSpanContainsPosition;
  9630. /* @internal */
  9631. function textRangeContainsPositionInclusive(span, position) {
  9632. return position >= span.pos && position <= span.end;
  9633. }
  9634. ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
  9635. // Returns true if 'span' contains 'other'.
  9636. function textSpanContainsTextSpan(span, other) {
  9637. return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
  9638. }
  9639. ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
  9640. function textSpanOverlapsWith(span, other) {
  9641. return textSpanOverlap(span, other) !== undefined;
  9642. }
  9643. ts.textSpanOverlapsWith = textSpanOverlapsWith;
  9644. function textSpanOverlap(span1, span2) {
  9645. var overlap = textSpanIntersection(span1, span2);
  9646. return overlap && overlap.length === 0 ? undefined : overlap;
  9647. }
  9648. ts.textSpanOverlap = textSpanOverlap;
  9649. function textSpanIntersectsWithTextSpan(span, other) {
  9650. return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
  9651. }
  9652. ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
  9653. function textSpanIntersectsWith(span, start, length) {
  9654. return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
  9655. }
  9656. ts.textSpanIntersectsWith = textSpanIntersectsWith;
  9657. function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
  9658. var end1 = start1 + length1;
  9659. var end2 = start2 + length2;
  9660. return start2 <= end1 && end2 >= start1;
  9661. }
  9662. ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
  9663. function textSpanIntersectsWithPosition(span, position) {
  9664. return position <= textSpanEnd(span) && position >= span.start;
  9665. }
  9666. ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
  9667. function textSpanIntersection(span1, span2) {
  9668. var start = Math.max(span1.start, span2.start);
  9669. var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
  9670. return start <= end ? createTextSpanFromBounds(start, end) : undefined;
  9671. }
  9672. ts.textSpanIntersection = textSpanIntersection;
  9673. function createTextSpan(start, length) {
  9674. if (start < 0) {
  9675. throw new Error("start < 0");
  9676. }
  9677. if (length < 0) {
  9678. throw new Error("length < 0");
  9679. }
  9680. return { start: start, length: length };
  9681. }
  9682. ts.createTextSpan = createTextSpan;
  9683. function createTextSpanFromBounds(start, end) {
  9684. return createTextSpan(start, end - start);
  9685. }
  9686. ts.createTextSpanFromBounds = createTextSpanFromBounds;
  9687. function textChangeRangeNewSpan(range) {
  9688. return createTextSpan(range.span.start, range.newLength);
  9689. }
  9690. ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
  9691. function textChangeRangeIsUnchanged(range) {
  9692. return textSpanIsEmpty(range.span) && range.newLength === 0;
  9693. }
  9694. ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
  9695. function createTextChangeRange(span, newLength) {
  9696. if (newLength < 0) {
  9697. throw new Error("newLength < 0");
  9698. }
  9699. return { span: span, newLength: newLength };
  9700. }
  9701. ts.createTextChangeRange = createTextChangeRange;
  9702. ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
  9703. /**
  9704. * Called to merge all the changes that occurred across several versions of a script snapshot
  9705. * into a single change. i.e. if a user keeps making successive edits to a script we will
  9706. * have a text change from V1 to V2, V2 to V3, ..., Vn.
  9707. *
  9708. * This function will then merge those changes into a single change range valid between V1 and
  9709. * Vn.
  9710. */
  9711. function collapseTextChangeRangesAcrossMultipleVersions(changes) {
  9712. if (changes.length === 0) {
  9713. return ts.unchangedTextChangeRange;
  9714. }
  9715. if (changes.length === 1) {
  9716. return changes[0];
  9717. }
  9718. // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
  9719. // as it makes things much easier to reason about.
  9720. var change0 = changes[0];
  9721. var oldStartN = change0.span.start;
  9722. var oldEndN = textSpanEnd(change0.span);
  9723. var newEndN = oldStartN + change0.newLength;
  9724. for (var i = 1; i < changes.length; i++) {
  9725. var nextChange = changes[i];
  9726. // Consider the following case:
  9727. // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
  9728. // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
  9729. // i.e. the span starting at 30 with length 30 is increased to length 40.
  9730. //
  9731. // 0 10 20 30 40 50 60 70 80 90 100
  9732. // -------------------------------------------------------------------------------------------------------
  9733. // | /
  9734. // | /----
  9735. // T1 | /----
  9736. // | /----
  9737. // | /----
  9738. // -------------------------------------------------------------------------------------------------------
  9739. // | \
  9740. // | \
  9741. // T2 | \
  9742. // | \
  9743. // | \
  9744. // -------------------------------------------------------------------------------------------------------
  9745. //
  9746. // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
  9747. // it's just the min of the old and new starts. i.e.:
  9748. //
  9749. // 0 10 20 30 40 50 60 70 80 90 100
  9750. // ------------------------------------------------------------*------------------------------------------
  9751. // | /
  9752. // | /----
  9753. // T1 | /----
  9754. // | /----
  9755. // | /----
  9756. // ----------------------------------------$-------------------$------------------------------------------
  9757. // . | \
  9758. // . | \
  9759. // T2 . | \
  9760. // . | \
  9761. // . | \
  9762. // ----------------------------------------------------------------------*--------------------------------
  9763. //
  9764. // (Note the dots represent the newly inferred start.
  9765. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
  9766. // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
  9767. // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
  9768. // means:
  9769. //
  9770. // 0 10 20 30 40 50 60 70 80 90 100
  9771. // --------------------------------------------------------------------------------*----------------------
  9772. // | /
  9773. // | /----
  9774. // T1 | /----
  9775. // | /----
  9776. // | /----
  9777. // ------------------------------------------------------------$------------------------------------------
  9778. // . | \
  9779. // . | \
  9780. // T2 . | \
  9781. // . | \
  9782. // . | \
  9783. // ----------------------------------------------------------------------*--------------------------------
  9784. //
  9785. // In other words (in this case), we're recognizing that the second edit happened after where the first edit
  9786. // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
  9787. // that's the same as if we started at char 80 instead of 60.
  9788. //
  9789. // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather
  9790. // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
  9791. // first.
  9792. //
  9793. // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
  9794. // semantics: { { start: 10, length: 70 }, newLength: 60 }
  9795. //
  9796. // The math then works out as follows.
  9797. // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
  9798. // final result like so:
  9799. //
  9800. // {
  9801. // oldStart3: Min(oldStart1, oldStart2),
  9802. // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
  9803. // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
  9804. // }
  9805. var oldStart1 = oldStartN;
  9806. var oldEnd1 = oldEndN;
  9807. var newEnd1 = newEndN;
  9808. var oldStart2 = nextChange.span.start;
  9809. var oldEnd2 = textSpanEnd(nextChange.span);
  9810. var newEnd2 = oldStart2 + nextChange.newLength;
  9811. oldStartN = Math.min(oldStart1, oldStart2);
  9812. oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
  9813. newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
  9814. }
  9815. return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
  9816. }
  9817. ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
  9818. function getTypeParameterOwner(d) {
  9819. if (d && d.kind === 155 /* TypeParameter */) {
  9820. for (var current = d; current; current = current.parent) {
  9821. if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
  9822. return current;
  9823. }
  9824. }
  9825. }
  9826. }
  9827. ts.getTypeParameterOwner = getTypeParameterOwner;
  9828. function isParameterPropertyDeclaration(node, parent) {
  9829. return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
  9830. }
  9831. ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
  9832. function isEmptyBindingPattern(node) {
  9833. if (isBindingPattern(node)) {
  9834. return ts.every(node.elements, isEmptyBindingElement);
  9835. }
  9836. return false;
  9837. }
  9838. ts.isEmptyBindingPattern = isEmptyBindingPattern;
  9839. function isEmptyBindingElement(node) {
  9840. if (isOmittedExpression(node)) {
  9841. return true;
  9842. }
  9843. return isEmptyBindingPattern(node.name);
  9844. }
  9845. ts.isEmptyBindingElement = isEmptyBindingElement;
  9846. function walkUpBindingElementsAndPatterns(binding) {
  9847. var node = binding.parent;
  9848. while (isBindingElement(node.parent)) {
  9849. node = node.parent.parent;
  9850. }
  9851. return node.parent;
  9852. }
  9853. ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
  9854. function getCombinedFlags(node, getFlags) {
  9855. if (isBindingElement(node)) {
  9856. node = walkUpBindingElementsAndPatterns(node);
  9857. }
  9858. var flags = getFlags(node);
  9859. if (node.kind === 242 /* VariableDeclaration */) {
  9860. node = node.parent;
  9861. }
  9862. if (node && node.kind === 243 /* VariableDeclarationList */) {
  9863. flags |= getFlags(node);
  9864. node = node.parent;
  9865. }
  9866. if (node && node.kind === 225 /* VariableStatement */) {
  9867. flags |= getFlags(node);
  9868. }
  9869. return flags;
  9870. }
  9871. function getCombinedModifierFlags(node) {
  9872. return getCombinedFlags(node, ts.getModifierFlags);
  9873. }
  9874. ts.getCombinedModifierFlags = getCombinedModifierFlags;
  9875. // Returns the node flags for this node and all relevant parent nodes. This is done so that
  9876. // nodes like variable declarations and binding elements can returned a view of their flags
  9877. // that includes the modifiers from their container. i.e. flags like export/declare aren't
  9878. // stored on the variable declaration directly, but on the containing variable statement
  9879. // (if it has one). Similarly, flags for let/const are store on the variable declaration
  9880. // list. By calling this function, all those flags are combined so that the client can treat
  9881. // the node as if it actually had those flags.
  9882. function getCombinedNodeFlags(node) {
  9883. return getCombinedFlags(node, function (n) { return n.flags; });
  9884. }
  9885. ts.getCombinedNodeFlags = getCombinedNodeFlags;
  9886. /**
  9887. * Checks to see if the locale is in the appropriate format,
  9888. * and if it is, attempts to set the appropriate language.
  9889. */
  9890. function validateLocaleAndSetLanguage(locale, sys, errors) {
  9891. var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
  9892. if (!matchResult) {
  9893. if (errors) {
  9894. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
  9895. }
  9896. return;
  9897. }
  9898. var language = matchResult[1];
  9899. var territory = matchResult[3];
  9900. // First try the entire locale, then fall back to just language if that's all we have.
  9901. // Either ways do not fail, and fallback to the English diagnostic strings.
  9902. if (!trySetLanguageAndTerritory(language, territory, errors)) {
  9903. trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
  9904. }
  9905. // Set the UI locale for string collation
  9906. ts.setUILocale(locale);
  9907. function trySetLanguageAndTerritory(language, territory, errors) {
  9908. var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
  9909. var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
  9910. var filePath = ts.combinePaths(containingDirectoryPath, language);
  9911. if (territory) {
  9912. filePath = filePath + "-" + territory;
  9913. }
  9914. filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
  9915. if (!sys.fileExists(filePath)) {
  9916. return false;
  9917. }
  9918. // TODO: Add codePage support for readFile?
  9919. var fileContents = "";
  9920. try {
  9921. fileContents = sys.readFile(filePath);
  9922. }
  9923. catch (e) {
  9924. if (errors) {
  9925. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
  9926. }
  9927. return false;
  9928. }
  9929. try {
  9930. // this is a global mutation (or live binding update)!
  9931. ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
  9932. }
  9933. catch (_a) {
  9934. if (errors) {
  9935. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
  9936. }
  9937. return false;
  9938. }
  9939. return true;
  9940. }
  9941. }
  9942. ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
  9943. function getOriginalNode(node, nodeTest) {
  9944. if (node) {
  9945. while (node.original !== undefined) {
  9946. node = node.original;
  9947. }
  9948. }
  9949. return !nodeTest || nodeTest(node) ? node : undefined;
  9950. }
  9951. ts.getOriginalNode = getOriginalNode;
  9952. /**
  9953. * Gets a value indicating whether a node originated in the parse tree.
  9954. *
  9955. * @param node The node to test.
  9956. */
  9957. function isParseTreeNode(node) {
  9958. return (node.flags & 8 /* Synthesized */) === 0;
  9959. }
  9960. ts.isParseTreeNode = isParseTreeNode;
  9961. function getParseTreeNode(node, nodeTest) {
  9962. if (node === undefined || isParseTreeNode(node)) {
  9963. return node;
  9964. }
  9965. node = getOriginalNode(node);
  9966. if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
  9967. return node;
  9968. }
  9969. return undefined;
  9970. }
  9971. ts.getParseTreeNode = getParseTreeNode;
  9972. /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
  9973. function escapeLeadingUnderscores(identifier) {
  9974. return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
  9975. }
  9976. ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
  9977. /**
  9978. * Remove extra underscore from escaped identifier text content.
  9979. *
  9980. * @param identifier The escaped identifier text.
  9981. * @returns The unescaped identifier text.
  9982. */
  9983. function unescapeLeadingUnderscores(identifier) {
  9984. var id = identifier;
  9985. return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
  9986. }
  9987. ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
  9988. function idText(identifierOrPrivateName) {
  9989. return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
  9990. }
  9991. ts.idText = idText;
  9992. function symbolName(symbol) {
  9993. if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
  9994. return idText(symbol.valueDeclaration.name);
  9995. }
  9996. return unescapeLeadingUnderscores(symbol.escapedName);
  9997. }
  9998. ts.symbolName = symbolName;
  9999. /**
  10000. * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
  10001. * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
  10002. * will be merged with)
  10003. */
  10004. function nameForNamelessJSDocTypedef(declaration) {
  10005. var hostNode = declaration.parent.parent;
  10006. if (!hostNode) {
  10007. return undefined;
  10008. }
  10009. // Covers classes, functions - any named declaration host node
  10010. if (isDeclaration(hostNode)) {
  10011. return getDeclarationIdentifier(hostNode);
  10012. }
  10013. // Covers remaining cases (returning undefined if none match).
  10014. switch (hostNode.kind) {
  10015. case 225 /* VariableStatement */:
  10016. if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
  10017. return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
  10018. }
  10019. break;
  10020. case 226 /* ExpressionStatement */:
  10021. var expr = hostNode.expression;
  10022. if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
  10023. expr = expr.left;
  10024. }
  10025. switch (expr.kind) {
  10026. case 194 /* PropertyAccessExpression */:
  10027. return expr.name;
  10028. case 195 /* ElementAccessExpression */:
  10029. var arg = expr.argumentExpression;
  10030. if (isIdentifier(arg)) {
  10031. return arg;
  10032. }
  10033. }
  10034. break;
  10035. case 200 /* ParenthesizedExpression */: {
  10036. return getDeclarationIdentifier(hostNode.expression);
  10037. }
  10038. case 238 /* LabeledStatement */: {
  10039. if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
  10040. return getDeclarationIdentifier(hostNode.statement);
  10041. }
  10042. break;
  10043. }
  10044. }
  10045. }
  10046. function getDeclarationIdentifier(node) {
  10047. var name = getNameOfDeclaration(node);
  10048. return name && isIdentifier(name) ? name : undefined;
  10049. }
  10050. /** @internal */
  10051. function nodeHasName(statement, name) {
  10052. if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
  10053. return true;
  10054. }
  10055. if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
  10056. return true;
  10057. }
  10058. return false;
  10059. }
  10060. ts.nodeHasName = nodeHasName;
  10061. function getNameOfJSDocTypedef(declaration) {
  10062. return declaration.name || nameForNamelessJSDocTypedef(declaration);
  10063. }
  10064. ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
  10065. /** @internal */
  10066. function isNamedDeclaration(node) {
  10067. return !!node.name; // A 'name' property should always be a DeclarationName.
  10068. }
  10069. ts.isNamedDeclaration = isNamedDeclaration;
  10070. /** @internal */
  10071. function getNonAssignedNameOfDeclaration(declaration) {
  10072. switch (declaration.kind) {
  10073. case 75 /* Identifier */:
  10074. return declaration;
  10075. case 322 /* JSDocPropertyTag */:
  10076. case 316 /* JSDocParameterTag */: {
  10077. var name = declaration.name;
  10078. if (name.kind === 153 /* QualifiedName */) {
  10079. return name.right;
  10080. }
  10081. break;
  10082. }
  10083. case 196 /* CallExpression */:
  10084. case 209 /* BinaryExpression */: {
  10085. var expr_1 = declaration;
  10086. switch (ts.getAssignmentDeclarationKind(expr_1)) {
  10087. case 1 /* ExportsProperty */:
  10088. case 4 /* ThisProperty */:
  10089. case 5 /* Property */:
  10090. case 3 /* PrototypeProperty */:
  10091. return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
  10092. case 7 /* ObjectDefinePropertyValue */:
  10093. case 8 /* ObjectDefinePropertyExports */:
  10094. case 9 /* ObjectDefinePrototypeProperty */:
  10095. return expr_1.arguments[1];
  10096. default:
  10097. return undefined;
  10098. }
  10099. }
  10100. case 321 /* JSDocTypedefTag */:
  10101. return getNameOfJSDocTypedef(declaration);
  10102. case 315 /* JSDocEnumTag */:
  10103. return nameForNamelessJSDocTypedef(declaration);
  10104. case 259 /* ExportAssignment */: {
  10105. var expression = declaration.expression;
  10106. return isIdentifier(expression) ? expression : undefined;
  10107. }
  10108. case 195 /* ElementAccessExpression */:
  10109. var expr = declaration;
  10110. if (ts.isBindableStaticElementAccessExpression(expr)) {
  10111. return expr.argumentExpression;
  10112. }
  10113. }
  10114. return declaration.name;
  10115. }
  10116. ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
  10117. function getNameOfDeclaration(declaration) {
  10118. if (declaration === undefined)
  10119. return undefined;
  10120. return getNonAssignedNameOfDeclaration(declaration) ||
  10121. (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
  10122. }
  10123. ts.getNameOfDeclaration = getNameOfDeclaration;
  10124. function getAssignedName(node) {
  10125. if (!node.parent) {
  10126. return undefined;
  10127. }
  10128. else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
  10129. return node.parent.name;
  10130. }
  10131. else if (isBinaryExpression(node.parent) && node === node.parent.right) {
  10132. if (isIdentifier(node.parent.left)) {
  10133. return node.parent.left;
  10134. }
  10135. else if (ts.isAccessExpression(node.parent.left)) {
  10136. return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
  10137. }
  10138. }
  10139. else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
  10140. return node.parent.name;
  10141. }
  10142. }
  10143. /**
  10144. * Gets the JSDoc parameter tags for the node if present.
  10145. *
  10146. * @remarks Returns any JSDoc param tag whose name matches the provided
  10147. * parameter, whether a param tag on a containing function
  10148. * expression, or a param tag on a variable declaration whose
  10149. * initializer is the containing function. The tags closest to the
  10150. * node are returned first, so in the previous example, the param
  10151. * tag on the containing function expression would be first.
  10152. *
  10153. * For binding patterns, parameter tags are matched by position.
  10154. */
  10155. function getJSDocParameterTags(param) {
  10156. if (param.name) {
  10157. if (isIdentifier(param.name)) {
  10158. var name_1 = param.name.escapedText;
  10159. return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
  10160. }
  10161. else {
  10162. var i = param.parent.parameters.indexOf(param);
  10163. ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
  10164. var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
  10165. if (i < paramTags.length) {
  10166. return [paramTags[i]];
  10167. }
  10168. }
  10169. }
  10170. // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
  10171. return ts.emptyArray;
  10172. }
  10173. ts.getJSDocParameterTags = getJSDocParameterTags;
  10174. /**
  10175. * Gets the JSDoc type parameter tags for the node if present.
  10176. *
  10177. * @remarks Returns any JSDoc template tag whose names match the provided
  10178. * parameter, whether a template tag on a containing function
  10179. * expression, or a template tag on a variable declaration whose
  10180. * initializer is the containing function. The tags closest to the
  10181. * node are returned first, so in the previous example, the template
  10182. * tag on the containing function expression would be first.
  10183. */
  10184. function getJSDocTypeParameterTags(param) {
  10185. var name = param.name.escapedText;
  10186. return getJSDocTags(param.parent).filter(function (tag) {
  10187. return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
  10188. });
  10189. }
  10190. ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
  10191. /**
  10192. * Return true if the node has JSDoc parameter tags.
  10193. *
  10194. * @remarks Includes parameter tags that are not directly on the node,
  10195. * for example on a variable declaration whose initializer is a function expression.
  10196. */
  10197. function hasJSDocParameterTags(node) {
  10198. return !!getFirstJSDocTag(node, isJSDocParameterTag);
  10199. }
  10200. ts.hasJSDocParameterTags = hasJSDocParameterTags;
  10201. /** Gets the JSDoc augments tag for the node if present */
  10202. function getJSDocAugmentsTag(node) {
  10203. return getFirstJSDocTag(node, isJSDocAugmentsTag);
  10204. }
  10205. ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
  10206. /** Gets the JSDoc class tag for the node if present */
  10207. function getJSDocClassTag(node) {
  10208. return getFirstJSDocTag(node, isJSDocClassTag);
  10209. }
  10210. ts.getJSDocClassTag = getJSDocClassTag;
  10211. /** Gets the JSDoc public tag for the node if present */
  10212. function getJSDocPublicTag(node) {
  10213. return getFirstJSDocTag(node, isJSDocPublicTag);
  10214. }
  10215. ts.getJSDocPublicTag = getJSDocPublicTag;
  10216. /** Gets the JSDoc private tag for the node if present */
  10217. function getJSDocPrivateTag(node) {
  10218. return getFirstJSDocTag(node, isJSDocPrivateTag);
  10219. }
  10220. ts.getJSDocPrivateTag = getJSDocPrivateTag;
  10221. /** Gets the JSDoc protected tag for the node if present */
  10222. function getJSDocProtectedTag(node) {
  10223. return getFirstJSDocTag(node, isJSDocProtectedTag);
  10224. }
  10225. ts.getJSDocProtectedTag = getJSDocProtectedTag;
  10226. /** Gets the JSDoc protected tag for the node if present */
  10227. function getJSDocReadonlyTag(node) {
  10228. return getFirstJSDocTag(node, isJSDocReadonlyTag);
  10229. }
  10230. ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
  10231. /** Gets the JSDoc enum tag for the node if present */
  10232. function getJSDocEnumTag(node) {
  10233. return getFirstJSDocTag(node, isJSDocEnumTag);
  10234. }
  10235. ts.getJSDocEnumTag = getJSDocEnumTag;
  10236. /** Gets the JSDoc this tag for the node if present */
  10237. function getJSDocThisTag(node) {
  10238. return getFirstJSDocTag(node, isJSDocThisTag);
  10239. }
  10240. ts.getJSDocThisTag = getJSDocThisTag;
  10241. /** Gets the JSDoc return tag for the node if present */
  10242. function getJSDocReturnTag(node) {
  10243. return getFirstJSDocTag(node, isJSDocReturnTag);
  10244. }
  10245. ts.getJSDocReturnTag = getJSDocReturnTag;
  10246. /** Gets the JSDoc template tag for the node if present */
  10247. function getJSDocTemplateTag(node) {
  10248. return getFirstJSDocTag(node, isJSDocTemplateTag);
  10249. }
  10250. ts.getJSDocTemplateTag = getJSDocTemplateTag;
  10251. /** Gets the JSDoc type tag for the node if present and valid */
  10252. function getJSDocTypeTag(node) {
  10253. // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
  10254. var tag = getFirstJSDocTag(node, isJSDocTypeTag);
  10255. if (tag && tag.typeExpression && tag.typeExpression.type) {
  10256. return tag;
  10257. }
  10258. return undefined;
  10259. }
  10260. ts.getJSDocTypeTag = getJSDocTypeTag;
  10261. /**
  10262. * Gets the type node for the node if provided via JSDoc.
  10263. *
  10264. * @remarks The search includes any JSDoc param tag that relates
  10265. * to the provided parameter, for example a type tag on the
  10266. * parameter itself, or a param tag on a containing function
  10267. * expression, or a param tag on a variable declaration whose
  10268. * initializer is the containing function. The tags closest to the
  10269. * node are examined first, so in the previous example, the type
  10270. * tag directly on the node would be returned.
  10271. */
  10272. function getJSDocType(node) {
  10273. var tag = getFirstJSDocTag(node, isJSDocTypeTag);
  10274. if (!tag && isParameter(node)) {
  10275. tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
  10276. }
  10277. return tag && tag.typeExpression && tag.typeExpression.type;
  10278. }
  10279. ts.getJSDocType = getJSDocType;
  10280. /**
  10281. * Gets the return type node for the node if provided via JSDoc return tag or type tag.
  10282. *
  10283. * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
  10284. * gets the type from inside the braces, after the fat arrow, etc.
  10285. */
  10286. function getJSDocReturnType(node) {
  10287. var returnTag = getJSDocReturnTag(node);
  10288. if (returnTag && returnTag.typeExpression) {
  10289. return returnTag.typeExpression.type;
  10290. }
  10291. var typeTag = getJSDocTypeTag(node);
  10292. if (typeTag && typeTag.typeExpression) {
  10293. var type = typeTag.typeExpression.type;
  10294. if (isTypeLiteralNode(type)) {
  10295. var sig = ts.find(type.members, isCallSignatureDeclaration);
  10296. return sig && sig.type;
  10297. }
  10298. if (isFunctionTypeNode(type)) {
  10299. return type.type;
  10300. }
  10301. }
  10302. }
  10303. ts.getJSDocReturnType = getJSDocReturnType;
  10304. /** Get all JSDoc tags related to a node, including those on parent nodes. */
  10305. function getJSDocTags(node) {
  10306. var tags = node.jsDocCache;
  10307. // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
  10308. if (tags === undefined) {
  10309. var comments = ts.getJSDocCommentsAndTags(node);
  10310. ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
  10311. node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
  10312. }
  10313. return tags;
  10314. }
  10315. ts.getJSDocTags = getJSDocTags;
  10316. /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
  10317. function getFirstJSDocTag(node, predicate) {
  10318. return ts.find(getJSDocTags(node), predicate);
  10319. }
  10320. /** Gets all JSDoc tags of a specified kind, or undefined if not present. */
  10321. function getAllJSDocTagsOfKind(node, kind) {
  10322. return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
  10323. }
  10324. ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
  10325. /**
  10326. * Gets the effective type parameters. If the node was parsed in a
  10327. * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
  10328. */
  10329. function getEffectiveTypeParameterDeclarations(node) {
  10330. if (isJSDocSignature(node)) {
  10331. return ts.emptyArray;
  10332. }
  10333. if (ts.isJSDocTypeAlias(node)) {
  10334. ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
  10335. return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
  10336. }
  10337. if (node.typeParameters) {
  10338. return node.typeParameters;
  10339. }
  10340. if (ts.isInJSFile(node)) {
  10341. var decls = ts.getJSDocTypeParameterDeclarations(node);
  10342. if (decls.length) {
  10343. return decls;
  10344. }
  10345. var typeTag = getJSDocType(node);
  10346. if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
  10347. return typeTag.typeParameters;
  10348. }
  10349. }
  10350. return ts.emptyArray;
  10351. }
  10352. ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
  10353. function getEffectiveConstraintOfTypeParameter(node) {
  10354. return node.constraint ? node.constraint :
  10355. isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
  10356. undefined;
  10357. }
  10358. ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
  10359. // #region
  10360. // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
  10361. // Literals
  10362. function isNumericLiteral(node) {
  10363. return node.kind === 8 /* NumericLiteral */;
  10364. }
  10365. ts.isNumericLiteral = isNumericLiteral;
  10366. function isBigIntLiteral(node) {
  10367. return node.kind === 9 /* BigIntLiteral */;
  10368. }
  10369. ts.isBigIntLiteral = isBigIntLiteral;
  10370. function isStringLiteral(node) {
  10371. return node.kind === 10 /* StringLiteral */;
  10372. }
  10373. ts.isStringLiteral = isStringLiteral;
  10374. function isJsxText(node) {
  10375. return node.kind === 11 /* JsxText */;
  10376. }
  10377. ts.isJsxText = isJsxText;
  10378. function isRegularExpressionLiteral(node) {
  10379. return node.kind === 13 /* RegularExpressionLiteral */;
  10380. }
  10381. ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
  10382. function isNoSubstitutionTemplateLiteral(node) {
  10383. return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
  10384. }
  10385. ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
  10386. // Pseudo-literals
  10387. function isTemplateHead(node) {
  10388. return node.kind === 15 /* TemplateHead */;
  10389. }
  10390. ts.isTemplateHead = isTemplateHead;
  10391. function isTemplateMiddle(node) {
  10392. return node.kind === 16 /* TemplateMiddle */;
  10393. }
  10394. ts.isTemplateMiddle = isTemplateMiddle;
  10395. function isTemplateTail(node) {
  10396. return node.kind === 17 /* TemplateTail */;
  10397. }
  10398. ts.isTemplateTail = isTemplateTail;
  10399. function isIdentifier(node) {
  10400. return node.kind === 75 /* Identifier */;
  10401. }
  10402. ts.isIdentifier = isIdentifier;
  10403. // Names
  10404. function isQualifiedName(node) {
  10405. return node.kind === 153 /* QualifiedName */;
  10406. }
  10407. ts.isQualifiedName = isQualifiedName;
  10408. function isComputedPropertyName(node) {
  10409. return node.kind === 154 /* ComputedPropertyName */;
  10410. }
  10411. ts.isComputedPropertyName = isComputedPropertyName;
  10412. function isPrivateIdentifier(node) {
  10413. return node.kind === 76 /* PrivateIdentifier */;
  10414. }
  10415. ts.isPrivateIdentifier = isPrivateIdentifier;
  10416. function isIdentifierOrPrivateIdentifier(node) {
  10417. return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
  10418. }
  10419. ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
  10420. // Signature elements
  10421. function isTypeParameterDeclaration(node) {
  10422. return node.kind === 155 /* TypeParameter */;
  10423. }
  10424. ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
  10425. function isParameter(node) {
  10426. return node.kind === 156 /* Parameter */;
  10427. }
  10428. ts.isParameter = isParameter;
  10429. function isDecorator(node) {
  10430. return node.kind === 157 /* Decorator */;
  10431. }
  10432. ts.isDecorator = isDecorator;
  10433. // TypeMember
  10434. function isPropertySignature(node) {
  10435. return node.kind === 158 /* PropertySignature */;
  10436. }
  10437. ts.isPropertySignature = isPropertySignature;
  10438. function isPropertyDeclaration(node) {
  10439. return node.kind === 159 /* PropertyDeclaration */;
  10440. }
  10441. ts.isPropertyDeclaration = isPropertyDeclaration;
  10442. function isMethodSignature(node) {
  10443. return node.kind === 160 /* MethodSignature */;
  10444. }
  10445. ts.isMethodSignature = isMethodSignature;
  10446. function isMethodDeclaration(node) {
  10447. return node.kind === 161 /* MethodDeclaration */;
  10448. }
  10449. ts.isMethodDeclaration = isMethodDeclaration;
  10450. function isConstructorDeclaration(node) {
  10451. return node.kind === 162 /* Constructor */;
  10452. }
  10453. ts.isConstructorDeclaration = isConstructorDeclaration;
  10454. function isGetAccessorDeclaration(node) {
  10455. return node.kind === 163 /* GetAccessor */;
  10456. }
  10457. ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
  10458. function isSetAccessorDeclaration(node) {
  10459. return node.kind === 164 /* SetAccessor */;
  10460. }
  10461. ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
  10462. function isCallSignatureDeclaration(node) {
  10463. return node.kind === 165 /* CallSignature */;
  10464. }
  10465. ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
  10466. function isConstructSignatureDeclaration(node) {
  10467. return node.kind === 166 /* ConstructSignature */;
  10468. }
  10469. ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
  10470. function isIndexSignatureDeclaration(node) {
  10471. return node.kind === 167 /* IndexSignature */;
  10472. }
  10473. ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
  10474. /* @internal */
  10475. function isGetOrSetAccessorDeclaration(node) {
  10476. return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
  10477. }
  10478. ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
  10479. // Type
  10480. function isTypePredicateNode(node) {
  10481. return node.kind === 168 /* TypePredicate */;
  10482. }
  10483. ts.isTypePredicateNode = isTypePredicateNode;
  10484. function isTypeReferenceNode(node) {
  10485. return node.kind === 169 /* TypeReference */;
  10486. }
  10487. ts.isTypeReferenceNode = isTypeReferenceNode;
  10488. function isFunctionTypeNode(node) {
  10489. return node.kind === 170 /* FunctionType */;
  10490. }
  10491. ts.isFunctionTypeNode = isFunctionTypeNode;
  10492. function isConstructorTypeNode(node) {
  10493. return node.kind === 171 /* ConstructorType */;
  10494. }
  10495. ts.isConstructorTypeNode = isConstructorTypeNode;
  10496. function isTypeQueryNode(node) {
  10497. return node.kind === 172 /* TypeQuery */;
  10498. }
  10499. ts.isTypeQueryNode = isTypeQueryNode;
  10500. function isTypeLiteralNode(node) {
  10501. return node.kind === 173 /* TypeLiteral */;
  10502. }
  10503. ts.isTypeLiteralNode = isTypeLiteralNode;
  10504. function isArrayTypeNode(node) {
  10505. return node.kind === 174 /* ArrayType */;
  10506. }
  10507. ts.isArrayTypeNode = isArrayTypeNode;
  10508. function isTupleTypeNode(node) {
  10509. return node.kind === 175 /* TupleType */;
  10510. }
  10511. ts.isTupleTypeNode = isTupleTypeNode;
  10512. function isUnionTypeNode(node) {
  10513. return node.kind === 178 /* UnionType */;
  10514. }
  10515. ts.isUnionTypeNode = isUnionTypeNode;
  10516. function isIntersectionTypeNode(node) {
  10517. return node.kind === 179 /* IntersectionType */;
  10518. }
  10519. ts.isIntersectionTypeNode = isIntersectionTypeNode;
  10520. function isConditionalTypeNode(node) {
  10521. return node.kind === 180 /* ConditionalType */;
  10522. }
  10523. ts.isConditionalTypeNode = isConditionalTypeNode;
  10524. function isInferTypeNode(node) {
  10525. return node.kind === 181 /* InferType */;
  10526. }
  10527. ts.isInferTypeNode = isInferTypeNode;
  10528. function isParenthesizedTypeNode(node) {
  10529. return node.kind === 182 /* ParenthesizedType */;
  10530. }
  10531. ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
  10532. function isThisTypeNode(node) {
  10533. return node.kind === 183 /* ThisType */;
  10534. }
  10535. ts.isThisTypeNode = isThisTypeNode;
  10536. function isTypeOperatorNode(node) {
  10537. return node.kind === 184 /* TypeOperator */;
  10538. }
  10539. ts.isTypeOperatorNode = isTypeOperatorNode;
  10540. function isIndexedAccessTypeNode(node) {
  10541. return node.kind === 185 /* IndexedAccessType */;
  10542. }
  10543. ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
  10544. function isMappedTypeNode(node) {
  10545. return node.kind === 186 /* MappedType */;
  10546. }
  10547. ts.isMappedTypeNode = isMappedTypeNode;
  10548. function isLiteralTypeNode(node) {
  10549. return node.kind === 187 /* LiteralType */;
  10550. }
  10551. ts.isLiteralTypeNode = isLiteralTypeNode;
  10552. function isImportTypeNode(node) {
  10553. return node.kind === 188 /* ImportType */;
  10554. }
  10555. ts.isImportTypeNode = isImportTypeNode;
  10556. // Binding patterns
  10557. function isObjectBindingPattern(node) {
  10558. return node.kind === 189 /* ObjectBindingPattern */;
  10559. }
  10560. ts.isObjectBindingPattern = isObjectBindingPattern;
  10561. function isArrayBindingPattern(node) {
  10562. return node.kind === 190 /* ArrayBindingPattern */;
  10563. }
  10564. ts.isArrayBindingPattern = isArrayBindingPattern;
  10565. function isBindingElement(node) {
  10566. return node.kind === 191 /* BindingElement */;
  10567. }
  10568. ts.isBindingElement = isBindingElement;
  10569. // Expression
  10570. function isArrayLiteralExpression(node) {
  10571. return node.kind === 192 /* ArrayLiteralExpression */;
  10572. }
  10573. ts.isArrayLiteralExpression = isArrayLiteralExpression;
  10574. function isObjectLiteralExpression(node) {
  10575. return node.kind === 193 /* ObjectLiteralExpression */;
  10576. }
  10577. ts.isObjectLiteralExpression = isObjectLiteralExpression;
  10578. function isPropertyAccessExpression(node) {
  10579. return node.kind === 194 /* PropertyAccessExpression */;
  10580. }
  10581. ts.isPropertyAccessExpression = isPropertyAccessExpression;
  10582. function isPropertyAccessChain(node) {
  10583. return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
  10584. }
  10585. ts.isPropertyAccessChain = isPropertyAccessChain;
  10586. function isElementAccessExpression(node) {
  10587. return node.kind === 195 /* ElementAccessExpression */;
  10588. }
  10589. ts.isElementAccessExpression = isElementAccessExpression;
  10590. function isElementAccessChain(node) {
  10591. return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
  10592. }
  10593. ts.isElementAccessChain = isElementAccessChain;
  10594. function isCallExpression(node) {
  10595. return node.kind === 196 /* CallExpression */;
  10596. }
  10597. ts.isCallExpression = isCallExpression;
  10598. function isCallChain(node) {
  10599. return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
  10600. }
  10601. ts.isCallChain = isCallChain;
  10602. function isOptionalChain(node) {
  10603. var kind = node.kind;
  10604. return !!(node.flags & 32 /* OptionalChain */) &&
  10605. (kind === 194 /* PropertyAccessExpression */
  10606. || kind === 195 /* ElementAccessExpression */
  10607. || kind === 196 /* CallExpression */);
  10608. }
  10609. ts.isOptionalChain = isOptionalChain;
  10610. /* @internal */
  10611. function isOptionalChainRoot(node) {
  10612. return isOptionalChain(node) && !!node.questionDotToken;
  10613. }
  10614. ts.isOptionalChainRoot = isOptionalChainRoot;
  10615. /**
  10616. * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
  10617. */
  10618. /* @internal */
  10619. function isExpressionOfOptionalChainRoot(node) {
  10620. return isOptionalChainRoot(node.parent) && node.parent.expression === node;
  10621. }
  10622. ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
  10623. /**
  10624. * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
  10625. *
  10626. * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
  10627. * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain)
  10628. * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is
  10629. * the end of the chain starting at `c?.`)
  10630. * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is
  10631. * the end of the chain starting at `a?.`)
  10632. */
  10633. /* @internal */
  10634. function isOutermostOptionalChain(node) {
  10635. return !isOptionalChain(node.parent) // cases 1 and 2
  10636. || isOptionalChainRoot(node.parent) // case 3
  10637. || node !== node.parent.expression; // case 4
  10638. }
  10639. ts.isOutermostOptionalChain = isOutermostOptionalChain;
  10640. function isNullishCoalesce(node) {
  10641. return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
  10642. }
  10643. ts.isNullishCoalesce = isNullishCoalesce;
  10644. function isNewExpression(node) {
  10645. return node.kind === 197 /* NewExpression */;
  10646. }
  10647. ts.isNewExpression = isNewExpression;
  10648. function isTaggedTemplateExpression(node) {
  10649. return node.kind === 198 /* TaggedTemplateExpression */;
  10650. }
  10651. ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
  10652. function isTypeAssertion(node) {
  10653. return node.kind === 199 /* TypeAssertionExpression */;
  10654. }
  10655. ts.isTypeAssertion = isTypeAssertion;
  10656. function isConstTypeReference(node) {
  10657. return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
  10658. node.typeName.escapedText === "const" && !node.typeArguments;
  10659. }
  10660. ts.isConstTypeReference = isConstTypeReference;
  10661. function isParenthesizedExpression(node) {
  10662. return node.kind === 200 /* ParenthesizedExpression */;
  10663. }
  10664. ts.isParenthesizedExpression = isParenthesizedExpression;
  10665. function skipPartiallyEmittedExpressions(node) {
  10666. while (node.kind === 325 /* PartiallyEmittedExpression */) {
  10667. node = node.expression;
  10668. }
  10669. return node;
  10670. }
  10671. ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
  10672. function isFunctionExpression(node) {
  10673. return node.kind === 201 /* FunctionExpression */;
  10674. }
  10675. ts.isFunctionExpression = isFunctionExpression;
  10676. function isArrowFunction(node) {
  10677. return node.kind === 202 /* ArrowFunction */;
  10678. }
  10679. ts.isArrowFunction = isArrowFunction;
  10680. function isDeleteExpression(node) {
  10681. return node.kind === 203 /* DeleteExpression */;
  10682. }
  10683. ts.isDeleteExpression = isDeleteExpression;
  10684. function isTypeOfExpression(node) {
  10685. return node.kind === 204 /* TypeOfExpression */;
  10686. }
  10687. ts.isTypeOfExpression = isTypeOfExpression;
  10688. function isVoidExpression(node) {
  10689. return node.kind === 205 /* VoidExpression */;
  10690. }
  10691. ts.isVoidExpression = isVoidExpression;
  10692. function isAwaitExpression(node) {
  10693. return node.kind === 206 /* AwaitExpression */;
  10694. }
  10695. ts.isAwaitExpression = isAwaitExpression;
  10696. function isPrefixUnaryExpression(node) {
  10697. return node.kind === 207 /* PrefixUnaryExpression */;
  10698. }
  10699. ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
  10700. function isPostfixUnaryExpression(node) {
  10701. return node.kind === 208 /* PostfixUnaryExpression */;
  10702. }
  10703. ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
  10704. function isBinaryExpression(node) {
  10705. return node.kind === 209 /* BinaryExpression */;
  10706. }
  10707. ts.isBinaryExpression = isBinaryExpression;
  10708. function isConditionalExpression(node) {
  10709. return node.kind === 210 /* ConditionalExpression */;
  10710. }
  10711. ts.isConditionalExpression = isConditionalExpression;
  10712. function isTemplateExpression(node) {
  10713. return node.kind === 211 /* TemplateExpression */;
  10714. }
  10715. ts.isTemplateExpression = isTemplateExpression;
  10716. function isYieldExpression(node) {
  10717. return node.kind === 212 /* YieldExpression */;
  10718. }
  10719. ts.isYieldExpression = isYieldExpression;
  10720. function isSpreadElement(node) {
  10721. return node.kind === 213 /* SpreadElement */;
  10722. }
  10723. ts.isSpreadElement = isSpreadElement;
  10724. function isClassExpression(node) {
  10725. return node.kind === 214 /* ClassExpression */;
  10726. }
  10727. ts.isClassExpression = isClassExpression;
  10728. function isOmittedExpression(node) {
  10729. return node.kind === 215 /* OmittedExpression */;
  10730. }
  10731. ts.isOmittedExpression = isOmittedExpression;
  10732. function isExpressionWithTypeArguments(node) {
  10733. return node.kind === 216 /* ExpressionWithTypeArguments */;
  10734. }
  10735. ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
  10736. function isAsExpression(node) {
  10737. return node.kind === 217 /* AsExpression */;
  10738. }
  10739. ts.isAsExpression = isAsExpression;
  10740. function isNonNullExpression(node) {
  10741. return node.kind === 218 /* NonNullExpression */;
  10742. }
  10743. ts.isNonNullExpression = isNonNullExpression;
  10744. function isMetaProperty(node) {
  10745. return node.kind === 219 /* MetaProperty */;
  10746. }
  10747. ts.isMetaProperty = isMetaProperty;
  10748. // Misc
  10749. function isTemplateSpan(node) {
  10750. return node.kind === 221 /* TemplateSpan */;
  10751. }
  10752. ts.isTemplateSpan = isTemplateSpan;
  10753. function isSemicolonClassElement(node) {
  10754. return node.kind === 222 /* SemicolonClassElement */;
  10755. }
  10756. ts.isSemicolonClassElement = isSemicolonClassElement;
  10757. // Block
  10758. function isBlock(node) {
  10759. return node.kind === 223 /* Block */;
  10760. }
  10761. ts.isBlock = isBlock;
  10762. function isVariableStatement(node) {
  10763. return node.kind === 225 /* VariableStatement */;
  10764. }
  10765. ts.isVariableStatement = isVariableStatement;
  10766. function isEmptyStatement(node) {
  10767. return node.kind === 224 /* EmptyStatement */;
  10768. }
  10769. ts.isEmptyStatement = isEmptyStatement;
  10770. function isExpressionStatement(node) {
  10771. return node.kind === 226 /* ExpressionStatement */;
  10772. }
  10773. ts.isExpressionStatement = isExpressionStatement;
  10774. function isIfStatement(node) {
  10775. return node.kind === 227 /* IfStatement */;
  10776. }
  10777. ts.isIfStatement = isIfStatement;
  10778. function isDoStatement(node) {
  10779. return node.kind === 228 /* DoStatement */;
  10780. }
  10781. ts.isDoStatement = isDoStatement;
  10782. function isWhileStatement(node) {
  10783. return node.kind === 229 /* WhileStatement */;
  10784. }
  10785. ts.isWhileStatement = isWhileStatement;
  10786. function isForStatement(node) {
  10787. return node.kind === 230 /* ForStatement */;
  10788. }
  10789. ts.isForStatement = isForStatement;
  10790. function isForInStatement(node) {
  10791. return node.kind === 231 /* ForInStatement */;
  10792. }
  10793. ts.isForInStatement = isForInStatement;
  10794. function isForOfStatement(node) {
  10795. return node.kind === 232 /* ForOfStatement */;
  10796. }
  10797. ts.isForOfStatement = isForOfStatement;
  10798. function isContinueStatement(node) {
  10799. return node.kind === 233 /* ContinueStatement */;
  10800. }
  10801. ts.isContinueStatement = isContinueStatement;
  10802. function isBreakStatement(node) {
  10803. return node.kind === 234 /* BreakStatement */;
  10804. }
  10805. ts.isBreakStatement = isBreakStatement;
  10806. function isBreakOrContinueStatement(node) {
  10807. return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
  10808. }
  10809. ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
  10810. function isReturnStatement(node) {
  10811. return node.kind === 235 /* ReturnStatement */;
  10812. }
  10813. ts.isReturnStatement = isReturnStatement;
  10814. function isWithStatement(node) {
  10815. return node.kind === 236 /* WithStatement */;
  10816. }
  10817. ts.isWithStatement = isWithStatement;
  10818. function isSwitchStatement(node) {
  10819. return node.kind === 237 /* SwitchStatement */;
  10820. }
  10821. ts.isSwitchStatement = isSwitchStatement;
  10822. function isLabeledStatement(node) {
  10823. return node.kind === 238 /* LabeledStatement */;
  10824. }
  10825. ts.isLabeledStatement = isLabeledStatement;
  10826. function isThrowStatement(node) {
  10827. return node.kind === 239 /* ThrowStatement */;
  10828. }
  10829. ts.isThrowStatement = isThrowStatement;
  10830. function isTryStatement(node) {
  10831. return node.kind === 240 /* TryStatement */;
  10832. }
  10833. ts.isTryStatement = isTryStatement;
  10834. function isDebuggerStatement(node) {
  10835. return node.kind === 241 /* DebuggerStatement */;
  10836. }
  10837. ts.isDebuggerStatement = isDebuggerStatement;
  10838. function isVariableDeclaration(node) {
  10839. return node.kind === 242 /* VariableDeclaration */;
  10840. }
  10841. ts.isVariableDeclaration = isVariableDeclaration;
  10842. function isVariableDeclarationList(node) {
  10843. return node.kind === 243 /* VariableDeclarationList */;
  10844. }
  10845. ts.isVariableDeclarationList = isVariableDeclarationList;
  10846. function isFunctionDeclaration(node) {
  10847. return node.kind === 244 /* FunctionDeclaration */;
  10848. }
  10849. ts.isFunctionDeclaration = isFunctionDeclaration;
  10850. function isClassDeclaration(node) {
  10851. return node.kind === 245 /* ClassDeclaration */;
  10852. }
  10853. ts.isClassDeclaration = isClassDeclaration;
  10854. function isInterfaceDeclaration(node) {
  10855. return node.kind === 246 /* InterfaceDeclaration */;
  10856. }
  10857. ts.isInterfaceDeclaration = isInterfaceDeclaration;
  10858. function isTypeAliasDeclaration(node) {
  10859. return node.kind === 247 /* TypeAliasDeclaration */;
  10860. }
  10861. ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
  10862. function isEnumDeclaration(node) {
  10863. return node.kind === 248 /* EnumDeclaration */;
  10864. }
  10865. ts.isEnumDeclaration = isEnumDeclaration;
  10866. function isModuleDeclaration(node) {
  10867. return node.kind === 249 /* ModuleDeclaration */;
  10868. }
  10869. ts.isModuleDeclaration = isModuleDeclaration;
  10870. function isModuleBlock(node) {
  10871. return node.kind === 250 /* ModuleBlock */;
  10872. }
  10873. ts.isModuleBlock = isModuleBlock;
  10874. function isCaseBlock(node) {
  10875. return node.kind === 251 /* CaseBlock */;
  10876. }
  10877. ts.isCaseBlock = isCaseBlock;
  10878. function isNamespaceExportDeclaration(node) {
  10879. return node.kind === 252 /* NamespaceExportDeclaration */;
  10880. }
  10881. ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
  10882. function isImportEqualsDeclaration(node) {
  10883. return node.kind === 253 /* ImportEqualsDeclaration */;
  10884. }
  10885. ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
  10886. function isImportDeclaration(node) {
  10887. return node.kind === 254 /* ImportDeclaration */;
  10888. }
  10889. ts.isImportDeclaration = isImportDeclaration;
  10890. function isImportClause(node) {
  10891. return node.kind === 255 /* ImportClause */;
  10892. }
  10893. ts.isImportClause = isImportClause;
  10894. function isNamespaceImport(node) {
  10895. return node.kind === 256 /* NamespaceImport */;
  10896. }
  10897. ts.isNamespaceImport = isNamespaceImport;
  10898. function isNamespaceExport(node) {
  10899. return node.kind === 262 /* NamespaceExport */;
  10900. }
  10901. ts.isNamespaceExport = isNamespaceExport;
  10902. function isNamedExportBindings(node) {
  10903. return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
  10904. }
  10905. ts.isNamedExportBindings = isNamedExportBindings;
  10906. function isNamedImports(node) {
  10907. return node.kind === 257 /* NamedImports */;
  10908. }
  10909. ts.isNamedImports = isNamedImports;
  10910. function isImportSpecifier(node) {
  10911. return node.kind === 258 /* ImportSpecifier */;
  10912. }
  10913. ts.isImportSpecifier = isImportSpecifier;
  10914. function isExportAssignment(node) {
  10915. return node.kind === 259 /* ExportAssignment */;
  10916. }
  10917. ts.isExportAssignment = isExportAssignment;
  10918. function isExportDeclaration(node) {
  10919. return node.kind === 260 /* ExportDeclaration */;
  10920. }
  10921. ts.isExportDeclaration = isExportDeclaration;
  10922. function isNamedExports(node) {
  10923. return node.kind === 261 /* NamedExports */;
  10924. }
  10925. ts.isNamedExports = isNamedExports;
  10926. function isExportSpecifier(node) {
  10927. return node.kind === 263 /* ExportSpecifier */;
  10928. }
  10929. ts.isExportSpecifier = isExportSpecifier;
  10930. function isMissingDeclaration(node) {
  10931. return node.kind === 264 /* MissingDeclaration */;
  10932. }
  10933. ts.isMissingDeclaration = isMissingDeclaration;
  10934. // Module References
  10935. function isExternalModuleReference(node) {
  10936. return node.kind === 265 /* ExternalModuleReference */;
  10937. }
  10938. ts.isExternalModuleReference = isExternalModuleReference;
  10939. // JSX
  10940. function isJsxElement(node) {
  10941. return node.kind === 266 /* JsxElement */;
  10942. }
  10943. ts.isJsxElement = isJsxElement;
  10944. function isJsxSelfClosingElement(node) {
  10945. return node.kind === 267 /* JsxSelfClosingElement */;
  10946. }
  10947. ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
  10948. function isJsxOpeningElement(node) {
  10949. return node.kind === 268 /* JsxOpeningElement */;
  10950. }
  10951. ts.isJsxOpeningElement = isJsxOpeningElement;
  10952. function isJsxClosingElement(node) {
  10953. return node.kind === 269 /* JsxClosingElement */;
  10954. }
  10955. ts.isJsxClosingElement = isJsxClosingElement;
  10956. function isJsxFragment(node) {
  10957. return node.kind === 270 /* JsxFragment */;
  10958. }
  10959. ts.isJsxFragment = isJsxFragment;
  10960. function isJsxOpeningFragment(node) {
  10961. return node.kind === 271 /* JsxOpeningFragment */;
  10962. }
  10963. ts.isJsxOpeningFragment = isJsxOpeningFragment;
  10964. function isJsxClosingFragment(node) {
  10965. return node.kind === 272 /* JsxClosingFragment */;
  10966. }
  10967. ts.isJsxClosingFragment = isJsxClosingFragment;
  10968. function isJsxAttribute(node) {
  10969. return node.kind === 273 /* JsxAttribute */;
  10970. }
  10971. ts.isJsxAttribute = isJsxAttribute;
  10972. function isJsxAttributes(node) {
  10973. return node.kind === 274 /* JsxAttributes */;
  10974. }
  10975. ts.isJsxAttributes = isJsxAttributes;
  10976. function isJsxSpreadAttribute(node) {
  10977. return node.kind === 275 /* JsxSpreadAttribute */;
  10978. }
  10979. ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
  10980. function isJsxExpression(node) {
  10981. return node.kind === 276 /* JsxExpression */;
  10982. }
  10983. ts.isJsxExpression = isJsxExpression;
  10984. // Clauses
  10985. function isCaseClause(node) {
  10986. return node.kind === 277 /* CaseClause */;
  10987. }
  10988. ts.isCaseClause = isCaseClause;
  10989. function isDefaultClause(node) {
  10990. return node.kind === 278 /* DefaultClause */;
  10991. }
  10992. ts.isDefaultClause = isDefaultClause;
  10993. function isHeritageClause(node) {
  10994. return node.kind === 279 /* HeritageClause */;
  10995. }
  10996. ts.isHeritageClause = isHeritageClause;
  10997. function isCatchClause(node) {
  10998. return node.kind === 280 /* CatchClause */;
  10999. }
  11000. ts.isCatchClause = isCatchClause;
  11001. // Property assignments
  11002. function isPropertyAssignment(node) {
  11003. return node.kind === 281 /* PropertyAssignment */;
  11004. }
  11005. ts.isPropertyAssignment = isPropertyAssignment;
  11006. function isShorthandPropertyAssignment(node) {
  11007. return node.kind === 282 /* ShorthandPropertyAssignment */;
  11008. }
  11009. ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
  11010. function isSpreadAssignment(node) {
  11011. return node.kind === 283 /* SpreadAssignment */;
  11012. }
  11013. ts.isSpreadAssignment = isSpreadAssignment;
  11014. // Enum
  11015. function isEnumMember(node) {
  11016. return node.kind === 284 /* EnumMember */;
  11017. }
  11018. ts.isEnumMember = isEnumMember;
  11019. // Top-level nodes
  11020. function isSourceFile(node) {
  11021. return node.kind === 290 /* SourceFile */;
  11022. }
  11023. ts.isSourceFile = isSourceFile;
  11024. function isBundle(node) {
  11025. return node.kind === 291 /* Bundle */;
  11026. }
  11027. ts.isBundle = isBundle;
  11028. function isUnparsedSource(node) {
  11029. return node.kind === 292 /* UnparsedSource */;
  11030. }
  11031. ts.isUnparsedSource = isUnparsedSource;
  11032. function isUnparsedPrepend(node) {
  11033. return node.kind === 286 /* UnparsedPrepend */;
  11034. }
  11035. ts.isUnparsedPrepend = isUnparsedPrepend;
  11036. function isUnparsedTextLike(node) {
  11037. switch (node.kind) {
  11038. case 287 /* UnparsedText */:
  11039. case 288 /* UnparsedInternalText */:
  11040. return true;
  11041. default:
  11042. return false;
  11043. }
  11044. }
  11045. ts.isUnparsedTextLike = isUnparsedTextLike;
  11046. function isUnparsedNode(node) {
  11047. return isUnparsedTextLike(node) ||
  11048. node.kind === 285 /* UnparsedPrologue */ ||
  11049. node.kind === 289 /* UnparsedSyntheticReference */;
  11050. }
  11051. ts.isUnparsedNode = isUnparsedNode;
  11052. // JSDoc
  11053. function isJSDocTypeExpression(node) {
  11054. return node.kind === 294 /* JSDocTypeExpression */;
  11055. }
  11056. ts.isJSDocTypeExpression = isJSDocTypeExpression;
  11057. function isJSDocAllType(node) {
  11058. return node.kind === 295 /* JSDocAllType */;
  11059. }
  11060. ts.isJSDocAllType = isJSDocAllType;
  11061. function isJSDocUnknownType(node) {
  11062. return node.kind === 296 /* JSDocUnknownType */;
  11063. }
  11064. ts.isJSDocUnknownType = isJSDocUnknownType;
  11065. function isJSDocNullableType(node) {
  11066. return node.kind === 297 /* JSDocNullableType */;
  11067. }
  11068. ts.isJSDocNullableType = isJSDocNullableType;
  11069. function isJSDocNonNullableType(node) {
  11070. return node.kind === 298 /* JSDocNonNullableType */;
  11071. }
  11072. ts.isJSDocNonNullableType = isJSDocNonNullableType;
  11073. function isJSDocOptionalType(node) {
  11074. return node.kind === 299 /* JSDocOptionalType */;
  11075. }
  11076. ts.isJSDocOptionalType = isJSDocOptionalType;
  11077. function isJSDocFunctionType(node) {
  11078. return node.kind === 300 /* JSDocFunctionType */;
  11079. }
  11080. ts.isJSDocFunctionType = isJSDocFunctionType;
  11081. function isJSDocVariadicType(node) {
  11082. return node.kind === 301 /* JSDocVariadicType */;
  11083. }
  11084. ts.isJSDocVariadicType = isJSDocVariadicType;
  11085. function isJSDoc(node) {
  11086. return node.kind === 303 /* JSDocComment */;
  11087. }
  11088. ts.isJSDoc = isJSDoc;
  11089. function isJSDocAuthorTag(node) {
  11090. return node.kind === 308 /* JSDocAuthorTag */;
  11091. }
  11092. ts.isJSDocAuthorTag = isJSDocAuthorTag;
  11093. function isJSDocAugmentsTag(node) {
  11094. return node.kind === 307 /* JSDocAugmentsTag */;
  11095. }
  11096. ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
  11097. function isJSDocClassTag(node) {
  11098. return node.kind === 309 /* JSDocClassTag */;
  11099. }
  11100. ts.isJSDocClassTag = isJSDocClassTag;
  11101. function isJSDocPublicTag(node) {
  11102. return node.kind === 310 /* JSDocPublicTag */;
  11103. }
  11104. ts.isJSDocPublicTag = isJSDocPublicTag;
  11105. function isJSDocPrivateTag(node) {
  11106. return node.kind === 311 /* JSDocPrivateTag */;
  11107. }
  11108. ts.isJSDocPrivateTag = isJSDocPrivateTag;
  11109. function isJSDocProtectedTag(node) {
  11110. return node.kind === 312 /* JSDocProtectedTag */;
  11111. }
  11112. ts.isJSDocProtectedTag = isJSDocProtectedTag;
  11113. function isJSDocReadonlyTag(node) {
  11114. return node.kind === 313 /* JSDocReadonlyTag */;
  11115. }
  11116. ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
  11117. function isJSDocEnumTag(node) {
  11118. return node.kind === 315 /* JSDocEnumTag */;
  11119. }
  11120. ts.isJSDocEnumTag = isJSDocEnumTag;
  11121. function isJSDocThisTag(node) {
  11122. return node.kind === 318 /* JSDocThisTag */;
  11123. }
  11124. ts.isJSDocThisTag = isJSDocThisTag;
  11125. function isJSDocParameterTag(node) {
  11126. return node.kind === 316 /* JSDocParameterTag */;
  11127. }
  11128. ts.isJSDocParameterTag = isJSDocParameterTag;
  11129. function isJSDocReturnTag(node) {
  11130. return node.kind === 317 /* JSDocReturnTag */;
  11131. }
  11132. ts.isJSDocReturnTag = isJSDocReturnTag;
  11133. function isJSDocTypeTag(node) {
  11134. return node.kind === 319 /* JSDocTypeTag */;
  11135. }
  11136. ts.isJSDocTypeTag = isJSDocTypeTag;
  11137. function isJSDocTemplateTag(node) {
  11138. return node.kind === 320 /* JSDocTemplateTag */;
  11139. }
  11140. ts.isJSDocTemplateTag = isJSDocTemplateTag;
  11141. function isJSDocTypedefTag(node) {
  11142. return node.kind === 321 /* JSDocTypedefTag */;
  11143. }
  11144. ts.isJSDocTypedefTag = isJSDocTypedefTag;
  11145. function isJSDocPropertyTag(node) {
  11146. return node.kind === 322 /* JSDocPropertyTag */;
  11147. }
  11148. ts.isJSDocPropertyTag = isJSDocPropertyTag;
  11149. function isJSDocPropertyLikeTag(node) {
  11150. return node.kind === 322 /* JSDocPropertyTag */ || node.kind === 316 /* JSDocParameterTag */;
  11151. }
  11152. ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
  11153. function isJSDocTypeLiteral(node) {
  11154. return node.kind === 304 /* JSDocTypeLiteral */;
  11155. }
  11156. ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
  11157. function isJSDocCallbackTag(node) {
  11158. return node.kind === 314 /* JSDocCallbackTag */;
  11159. }
  11160. ts.isJSDocCallbackTag = isJSDocCallbackTag;
  11161. function isJSDocSignature(node) {
  11162. return node.kind === 305 /* JSDocSignature */;
  11163. }
  11164. ts.isJSDocSignature = isJSDocSignature;
  11165. // #endregion
  11166. // #region
  11167. // Node tests
  11168. //
  11169. // All node tests in the following list should *not* reference parent pointers so that
  11170. // they may be used with transformations.
  11171. /* @internal */
  11172. function isSyntaxList(n) {
  11173. return n.kind === 323 /* SyntaxList */;
  11174. }
  11175. ts.isSyntaxList = isSyntaxList;
  11176. /* @internal */
  11177. function isNode(node) {
  11178. return isNodeKind(node.kind);
  11179. }
  11180. ts.isNode = isNode;
  11181. /* @internal */
  11182. function isNodeKind(kind) {
  11183. return kind >= 153 /* FirstNode */;
  11184. }
  11185. ts.isNodeKind = isNodeKind;
  11186. /**
  11187. * True if node is of some token syntax kind.
  11188. * For example, this is true for an IfKeyword but not for an IfStatement.
  11189. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
  11190. */
  11191. function isToken(n) {
  11192. return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
  11193. }
  11194. ts.isToken = isToken;
  11195. // Node Arrays
  11196. /* @internal */
  11197. function isNodeArray(array) {
  11198. return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
  11199. }
  11200. ts.isNodeArray = isNodeArray;
  11201. // Literals
  11202. /* @internal */
  11203. function isLiteralKind(kind) {
  11204. return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
  11205. }
  11206. ts.isLiteralKind = isLiteralKind;
  11207. function isLiteralExpression(node) {
  11208. return isLiteralKind(node.kind);
  11209. }
  11210. ts.isLiteralExpression = isLiteralExpression;
  11211. // Pseudo-literals
  11212. /* @internal */
  11213. function isTemplateLiteralKind(kind) {
  11214. return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
  11215. }
  11216. ts.isTemplateLiteralKind = isTemplateLiteralKind;
  11217. function isTemplateLiteralToken(node) {
  11218. return isTemplateLiteralKind(node.kind);
  11219. }
  11220. ts.isTemplateLiteralToken = isTemplateLiteralToken;
  11221. function isTemplateMiddleOrTemplateTail(node) {
  11222. var kind = node.kind;
  11223. return kind === 16 /* TemplateMiddle */
  11224. || kind === 17 /* TemplateTail */;
  11225. }
  11226. ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
  11227. function isImportOrExportSpecifier(node) {
  11228. return isImportSpecifier(node) || isExportSpecifier(node);
  11229. }
  11230. ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
  11231. function isTypeOnlyImportOrExportDeclaration(node) {
  11232. switch (node.kind) {
  11233. case 258 /* ImportSpecifier */:
  11234. case 263 /* ExportSpecifier */:
  11235. return node.parent.parent.isTypeOnly;
  11236. case 256 /* NamespaceImport */:
  11237. return node.parent.isTypeOnly;
  11238. case 255 /* ImportClause */:
  11239. return node.isTypeOnly;
  11240. default:
  11241. return false;
  11242. }
  11243. }
  11244. ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
  11245. function isStringTextContainingNode(node) {
  11246. return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
  11247. }
  11248. ts.isStringTextContainingNode = isStringTextContainingNode;
  11249. // Identifiers
  11250. /* @internal */
  11251. function isGeneratedIdentifier(node) {
  11252. return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
  11253. }
  11254. ts.isGeneratedIdentifier = isGeneratedIdentifier;
  11255. // Private Identifiers
  11256. /*@internal*/
  11257. function isPrivateIdentifierPropertyDeclaration(node) {
  11258. return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
  11259. }
  11260. ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
  11261. /*@internal*/
  11262. function isPrivateIdentifierPropertyAccessExpression(node) {
  11263. return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
  11264. }
  11265. ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
  11266. // Keywords
  11267. /* @internal */
  11268. function isModifierKind(token) {
  11269. switch (token) {
  11270. case 122 /* AbstractKeyword */:
  11271. case 126 /* AsyncKeyword */:
  11272. case 81 /* ConstKeyword */:
  11273. case 130 /* DeclareKeyword */:
  11274. case 84 /* DefaultKeyword */:
  11275. case 89 /* ExportKeyword */:
  11276. case 119 /* PublicKeyword */:
  11277. case 117 /* PrivateKeyword */:
  11278. case 118 /* ProtectedKeyword */:
  11279. case 138 /* ReadonlyKeyword */:
  11280. case 120 /* StaticKeyword */:
  11281. return true;
  11282. }
  11283. return false;
  11284. }
  11285. ts.isModifierKind = isModifierKind;
  11286. /* @internal */
  11287. function isParameterPropertyModifier(kind) {
  11288. return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
  11289. }
  11290. ts.isParameterPropertyModifier = isParameterPropertyModifier;
  11291. /* @internal */
  11292. function isClassMemberModifier(idToken) {
  11293. return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
  11294. }
  11295. ts.isClassMemberModifier = isClassMemberModifier;
  11296. function isModifier(node) {
  11297. return isModifierKind(node.kind);
  11298. }
  11299. ts.isModifier = isModifier;
  11300. function isEntityName(node) {
  11301. var kind = node.kind;
  11302. return kind === 153 /* QualifiedName */
  11303. || kind === 75 /* Identifier */;
  11304. }
  11305. ts.isEntityName = isEntityName;
  11306. function isPropertyName(node) {
  11307. var kind = node.kind;
  11308. return kind === 75 /* Identifier */
  11309. || kind === 10 /* StringLiteral */
  11310. || kind === 8 /* NumericLiteral */
  11311. || kind === 154 /* ComputedPropertyName */;
  11312. }
  11313. ts.isPropertyName = isPropertyName;
  11314. function isBindingName(node) {
  11315. var kind = node.kind;
  11316. return kind === 75 /* Identifier */
  11317. || kind === 189 /* ObjectBindingPattern */
  11318. || kind === 190 /* ArrayBindingPattern */;
  11319. }
  11320. ts.isBindingName = isBindingName;
  11321. // Functions
  11322. function isFunctionLike(node) {
  11323. return node && isFunctionLikeKind(node.kind);
  11324. }
  11325. ts.isFunctionLike = isFunctionLike;
  11326. /* @internal */
  11327. function isFunctionLikeDeclaration(node) {
  11328. return node && isFunctionLikeDeclarationKind(node.kind);
  11329. }
  11330. ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
  11331. function isFunctionLikeDeclarationKind(kind) {
  11332. switch (kind) {
  11333. case 244 /* FunctionDeclaration */:
  11334. case 161 /* MethodDeclaration */:
  11335. case 162 /* Constructor */:
  11336. case 163 /* GetAccessor */:
  11337. case 164 /* SetAccessor */:
  11338. case 201 /* FunctionExpression */:
  11339. case 202 /* ArrowFunction */:
  11340. return true;
  11341. default:
  11342. return false;
  11343. }
  11344. }
  11345. /* @internal */
  11346. function isFunctionLikeKind(kind) {
  11347. switch (kind) {
  11348. case 160 /* MethodSignature */:
  11349. case 165 /* CallSignature */:
  11350. case 305 /* JSDocSignature */:
  11351. case 166 /* ConstructSignature */:
  11352. case 167 /* IndexSignature */:
  11353. case 170 /* FunctionType */:
  11354. case 300 /* JSDocFunctionType */:
  11355. case 171 /* ConstructorType */:
  11356. return true;
  11357. default:
  11358. return isFunctionLikeDeclarationKind(kind);
  11359. }
  11360. }
  11361. ts.isFunctionLikeKind = isFunctionLikeKind;
  11362. /* @internal */
  11363. function isFunctionOrModuleBlock(node) {
  11364. return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
  11365. }
  11366. ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
  11367. // Classes
  11368. function isClassElement(node) {
  11369. var kind = node.kind;
  11370. return kind === 162 /* Constructor */
  11371. || kind === 159 /* PropertyDeclaration */
  11372. || kind === 161 /* MethodDeclaration */
  11373. || kind === 163 /* GetAccessor */
  11374. || kind === 164 /* SetAccessor */
  11375. || kind === 167 /* IndexSignature */
  11376. || kind === 222 /* SemicolonClassElement */;
  11377. }
  11378. ts.isClassElement = isClassElement;
  11379. function isClassLike(node) {
  11380. return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
  11381. }
  11382. ts.isClassLike = isClassLike;
  11383. function isAccessor(node) {
  11384. return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
  11385. }
  11386. ts.isAccessor = isAccessor;
  11387. /* @internal */
  11388. function isMethodOrAccessor(node) {
  11389. switch (node.kind) {
  11390. case 161 /* MethodDeclaration */:
  11391. case 163 /* GetAccessor */:
  11392. case 164 /* SetAccessor */:
  11393. return true;
  11394. default:
  11395. return false;
  11396. }
  11397. }
  11398. ts.isMethodOrAccessor = isMethodOrAccessor;
  11399. // Type members
  11400. function isTypeElement(node) {
  11401. var kind = node.kind;
  11402. return kind === 166 /* ConstructSignature */
  11403. || kind === 165 /* CallSignature */
  11404. || kind === 158 /* PropertySignature */
  11405. || kind === 160 /* MethodSignature */
  11406. || kind === 167 /* IndexSignature */;
  11407. }
  11408. ts.isTypeElement = isTypeElement;
  11409. function isClassOrTypeElement(node) {
  11410. return isTypeElement(node) || isClassElement(node);
  11411. }
  11412. ts.isClassOrTypeElement = isClassOrTypeElement;
  11413. function isObjectLiteralElementLike(node) {
  11414. var kind = node.kind;
  11415. return kind === 281 /* PropertyAssignment */
  11416. || kind === 282 /* ShorthandPropertyAssignment */
  11417. || kind === 283 /* SpreadAssignment */
  11418. || kind === 161 /* MethodDeclaration */
  11419. || kind === 163 /* GetAccessor */
  11420. || kind === 164 /* SetAccessor */;
  11421. }
  11422. ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
  11423. // Type
  11424. /**
  11425. * Node test that determines whether a node is a valid type node.
  11426. * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
  11427. * of a TypeNode.
  11428. */
  11429. function isTypeNode(node) {
  11430. return ts.isTypeNodeKind(node.kind);
  11431. }
  11432. ts.isTypeNode = isTypeNode;
  11433. function isFunctionOrConstructorTypeNode(node) {
  11434. switch (node.kind) {
  11435. case 170 /* FunctionType */:
  11436. case 171 /* ConstructorType */:
  11437. return true;
  11438. }
  11439. return false;
  11440. }
  11441. ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
  11442. // Binding patterns
  11443. /* @internal */
  11444. function isBindingPattern(node) {
  11445. if (node) {
  11446. var kind = node.kind;
  11447. return kind === 190 /* ArrayBindingPattern */
  11448. || kind === 189 /* ObjectBindingPattern */;
  11449. }
  11450. return false;
  11451. }
  11452. ts.isBindingPattern = isBindingPattern;
  11453. /* @internal */
  11454. function isAssignmentPattern(node) {
  11455. var kind = node.kind;
  11456. return kind === 192 /* ArrayLiteralExpression */
  11457. || kind === 193 /* ObjectLiteralExpression */;
  11458. }
  11459. ts.isAssignmentPattern = isAssignmentPattern;
  11460. /* @internal */
  11461. function isArrayBindingElement(node) {
  11462. var kind = node.kind;
  11463. return kind === 191 /* BindingElement */
  11464. || kind === 215 /* OmittedExpression */;
  11465. }
  11466. ts.isArrayBindingElement = isArrayBindingElement;
  11467. /**
  11468. * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
  11469. */
  11470. /* @internal */
  11471. function isDeclarationBindingElement(bindingElement) {
  11472. switch (bindingElement.kind) {
  11473. case 242 /* VariableDeclaration */:
  11474. case 156 /* Parameter */:
  11475. case 191 /* BindingElement */:
  11476. return true;
  11477. }
  11478. return false;
  11479. }
  11480. ts.isDeclarationBindingElement = isDeclarationBindingElement;
  11481. /**
  11482. * Determines whether a node is a BindingOrAssignmentPattern
  11483. */
  11484. /* @internal */
  11485. function isBindingOrAssignmentPattern(node) {
  11486. return isObjectBindingOrAssignmentPattern(node)
  11487. || isArrayBindingOrAssignmentPattern(node);
  11488. }
  11489. ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
  11490. /**
  11491. * Determines whether a node is an ObjectBindingOrAssignmentPattern
  11492. */
  11493. /* @internal */
  11494. function isObjectBindingOrAssignmentPattern(node) {
  11495. switch (node.kind) {
  11496. case 189 /* ObjectBindingPattern */:
  11497. case 193 /* ObjectLiteralExpression */:
  11498. return true;
  11499. }
  11500. return false;
  11501. }
  11502. ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
  11503. /**
  11504. * Determines whether a node is an ArrayBindingOrAssignmentPattern
  11505. */
  11506. /* @internal */
  11507. function isArrayBindingOrAssignmentPattern(node) {
  11508. switch (node.kind) {
  11509. case 190 /* ArrayBindingPattern */:
  11510. case 192 /* ArrayLiteralExpression */:
  11511. return true;
  11512. }
  11513. return false;
  11514. }
  11515. ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
  11516. /* @internal */
  11517. function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
  11518. var kind = node.kind;
  11519. return kind === 194 /* PropertyAccessExpression */
  11520. || kind === 153 /* QualifiedName */
  11521. || kind === 188 /* ImportType */;
  11522. }
  11523. ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
  11524. // Expression
  11525. function isPropertyAccessOrQualifiedName(node) {
  11526. var kind = node.kind;
  11527. return kind === 194 /* PropertyAccessExpression */
  11528. || kind === 153 /* QualifiedName */;
  11529. }
  11530. ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
  11531. function isCallLikeExpression(node) {
  11532. switch (node.kind) {
  11533. case 268 /* JsxOpeningElement */:
  11534. case 267 /* JsxSelfClosingElement */:
  11535. case 196 /* CallExpression */:
  11536. case 197 /* NewExpression */:
  11537. case 198 /* TaggedTemplateExpression */:
  11538. case 157 /* Decorator */:
  11539. return true;
  11540. default:
  11541. return false;
  11542. }
  11543. }
  11544. ts.isCallLikeExpression = isCallLikeExpression;
  11545. function isCallOrNewExpression(node) {
  11546. return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
  11547. }
  11548. ts.isCallOrNewExpression = isCallOrNewExpression;
  11549. function isTemplateLiteral(node) {
  11550. var kind = node.kind;
  11551. return kind === 211 /* TemplateExpression */
  11552. || kind === 14 /* NoSubstitutionTemplateLiteral */;
  11553. }
  11554. ts.isTemplateLiteral = isTemplateLiteral;
  11555. /* @internal */
  11556. function isLeftHandSideExpression(node) {
  11557. return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
  11558. }
  11559. ts.isLeftHandSideExpression = isLeftHandSideExpression;
  11560. function isLeftHandSideExpressionKind(kind) {
  11561. switch (kind) {
  11562. case 194 /* PropertyAccessExpression */:
  11563. case 195 /* ElementAccessExpression */:
  11564. case 197 /* NewExpression */:
  11565. case 196 /* CallExpression */:
  11566. case 266 /* JsxElement */:
  11567. case 267 /* JsxSelfClosingElement */:
  11568. case 270 /* JsxFragment */:
  11569. case 198 /* TaggedTemplateExpression */:
  11570. case 192 /* ArrayLiteralExpression */:
  11571. case 200 /* ParenthesizedExpression */:
  11572. case 193 /* ObjectLiteralExpression */:
  11573. case 214 /* ClassExpression */:
  11574. case 201 /* FunctionExpression */:
  11575. case 75 /* Identifier */:
  11576. case 13 /* RegularExpressionLiteral */:
  11577. case 8 /* NumericLiteral */:
  11578. case 9 /* BigIntLiteral */:
  11579. case 10 /* StringLiteral */:
  11580. case 14 /* NoSubstitutionTemplateLiteral */:
  11581. case 211 /* TemplateExpression */:
  11582. case 91 /* FalseKeyword */:
  11583. case 100 /* NullKeyword */:
  11584. case 104 /* ThisKeyword */:
  11585. case 106 /* TrueKeyword */:
  11586. case 102 /* SuperKeyword */:
  11587. case 218 /* NonNullExpression */:
  11588. case 219 /* MetaProperty */:
  11589. case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
  11590. return true;
  11591. default:
  11592. return false;
  11593. }
  11594. }
  11595. /* @internal */
  11596. function isUnaryExpression(node) {
  11597. return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
  11598. }
  11599. ts.isUnaryExpression = isUnaryExpression;
  11600. function isUnaryExpressionKind(kind) {
  11601. switch (kind) {
  11602. case 207 /* PrefixUnaryExpression */:
  11603. case 208 /* PostfixUnaryExpression */:
  11604. case 203 /* DeleteExpression */:
  11605. case 204 /* TypeOfExpression */:
  11606. case 205 /* VoidExpression */:
  11607. case 206 /* AwaitExpression */:
  11608. case 199 /* TypeAssertionExpression */:
  11609. return true;
  11610. default:
  11611. return isLeftHandSideExpressionKind(kind);
  11612. }
  11613. }
  11614. /* @internal */
  11615. function isUnaryExpressionWithWrite(expr) {
  11616. switch (expr.kind) {
  11617. case 208 /* PostfixUnaryExpression */:
  11618. return true;
  11619. case 207 /* PrefixUnaryExpression */:
  11620. return expr.operator === 45 /* PlusPlusToken */ ||
  11621. expr.operator === 46 /* MinusMinusToken */;
  11622. default:
  11623. return false;
  11624. }
  11625. }
  11626. ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
  11627. /* @internal */
  11628. /**
  11629. * Determines whether a node is an expression based only on its kind.
  11630. * Use `isExpressionNode` if not in transforms.
  11631. */
  11632. function isExpression(node) {
  11633. return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
  11634. }
  11635. ts.isExpression = isExpression;
  11636. function isExpressionKind(kind) {
  11637. switch (kind) {
  11638. case 210 /* ConditionalExpression */:
  11639. case 212 /* YieldExpression */:
  11640. case 202 /* ArrowFunction */:
  11641. case 209 /* BinaryExpression */:
  11642. case 213 /* SpreadElement */:
  11643. case 217 /* AsExpression */:
  11644. case 215 /* OmittedExpression */:
  11645. case 326 /* CommaListExpression */:
  11646. case 325 /* PartiallyEmittedExpression */:
  11647. return true;
  11648. default:
  11649. return isUnaryExpressionKind(kind);
  11650. }
  11651. }
  11652. function isAssertionExpression(node) {
  11653. var kind = node.kind;
  11654. return kind === 199 /* TypeAssertionExpression */
  11655. || kind === 217 /* AsExpression */;
  11656. }
  11657. ts.isAssertionExpression = isAssertionExpression;
  11658. /* @internal */
  11659. function isPartiallyEmittedExpression(node) {
  11660. return node.kind === 325 /* PartiallyEmittedExpression */;
  11661. }
  11662. ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
  11663. /* @internal */
  11664. function isNotEmittedStatement(node) {
  11665. return node.kind === 324 /* NotEmittedStatement */;
  11666. }
  11667. ts.isNotEmittedStatement = isNotEmittedStatement;
  11668. /* @internal */
  11669. function isSyntheticReference(node) {
  11670. return node.kind === 329 /* SyntheticReferenceExpression */;
  11671. }
  11672. ts.isSyntheticReference = isSyntheticReference;
  11673. /* @internal */
  11674. function isNotEmittedOrPartiallyEmittedNode(node) {
  11675. return isNotEmittedStatement(node)
  11676. || isPartiallyEmittedExpression(node);
  11677. }
  11678. ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
  11679. function isIterationStatement(node, lookInLabeledStatements) {
  11680. switch (node.kind) {
  11681. case 230 /* ForStatement */:
  11682. case 231 /* ForInStatement */:
  11683. case 232 /* ForOfStatement */:
  11684. case 228 /* DoStatement */:
  11685. case 229 /* WhileStatement */:
  11686. return true;
  11687. case 238 /* LabeledStatement */:
  11688. return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
  11689. }
  11690. return false;
  11691. }
  11692. ts.isIterationStatement = isIterationStatement;
  11693. /* @internal */
  11694. function isScopeMarker(node) {
  11695. return isExportAssignment(node) || isExportDeclaration(node);
  11696. }
  11697. ts.isScopeMarker = isScopeMarker;
  11698. /* @internal */
  11699. function hasScopeMarker(statements) {
  11700. return ts.some(statements, isScopeMarker);
  11701. }
  11702. ts.hasScopeMarker = hasScopeMarker;
  11703. /* @internal */
  11704. function needsScopeMarker(result) {
  11705. return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
  11706. }
  11707. ts.needsScopeMarker = needsScopeMarker;
  11708. /* @internal */
  11709. function isExternalModuleIndicator(result) {
  11710. // Exported top-level member indicates moduleness
  11711. return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
  11712. }
  11713. ts.isExternalModuleIndicator = isExternalModuleIndicator;
  11714. /* @internal */
  11715. function isForInOrOfStatement(node) {
  11716. return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
  11717. }
  11718. ts.isForInOrOfStatement = isForInOrOfStatement;
  11719. // Element
  11720. /* @internal */
  11721. function isConciseBody(node) {
  11722. return isBlock(node)
  11723. || isExpression(node);
  11724. }
  11725. ts.isConciseBody = isConciseBody;
  11726. /* @internal */
  11727. function isFunctionBody(node) {
  11728. return isBlock(node);
  11729. }
  11730. ts.isFunctionBody = isFunctionBody;
  11731. /* @internal */
  11732. function isForInitializer(node) {
  11733. return isVariableDeclarationList(node)
  11734. || isExpression(node);
  11735. }
  11736. ts.isForInitializer = isForInitializer;
  11737. /* @internal */
  11738. function isModuleBody(node) {
  11739. var kind = node.kind;
  11740. return kind === 250 /* ModuleBlock */
  11741. || kind === 249 /* ModuleDeclaration */
  11742. || kind === 75 /* Identifier */;
  11743. }
  11744. ts.isModuleBody = isModuleBody;
  11745. /* @internal */
  11746. function isNamespaceBody(node) {
  11747. var kind = node.kind;
  11748. return kind === 250 /* ModuleBlock */
  11749. || kind === 249 /* ModuleDeclaration */;
  11750. }
  11751. ts.isNamespaceBody = isNamespaceBody;
  11752. /* @internal */
  11753. function isJSDocNamespaceBody(node) {
  11754. var kind = node.kind;
  11755. return kind === 75 /* Identifier */
  11756. || kind === 249 /* ModuleDeclaration */;
  11757. }
  11758. ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
  11759. /* @internal */
  11760. function isNamedImportBindings(node) {
  11761. var kind = node.kind;
  11762. return kind === 257 /* NamedImports */
  11763. || kind === 256 /* NamespaceImport */;
  11764. }
  11765. ts.isNamedImportBindings = isNamedImportBindings;
  11766. /* @internal */
  11767. function isModuleOrEnumDeclaration(node) {
  11768. return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
  11769. }
  11770. ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
  11771. function isDeclarationKind(kind) {
  11772. return kind === 202 /* ArrowFunction */
  11773. || kind === 191 /* BindingElement */
  11774. || kind === 245 /* ClassDeclaration */
  11775. || kind === 214 /* ClassExpression */
  11776. || kind === 162 /* Constructor */
  11777. || kind === 248 /* EnumDeclaration */
  11778. || kind === 284 /* EnumMember */
  11779. || kind === 263 /* ExportSpecifier */
  11780. || kind === 244 /* FunctionDeclaration */
  11781. || kind === 201 /* FunctionExpression */
  11782. || kind === 163 /* GetAccessor */
  11783. || kind === 255 /* ImportClause */
  11784. || kind === 253 /* ImportEqualsDeclaration */
  11785. || kind === 258 /* ImportSpecifier */
  11786. || kind === 246 /* InterfaceDeclaration */
  11787. || kind === 273 /* JsxAttribute */
  11788. || kind === 161 /* MethodDeclaration */
  11789. || kind === 160 /* MethodSignature */
  11790. || kind === 249 /* ModuleDeclaration */
  11791. || kind === 252 /* NamespaceExportDeclaration */
  11792. || kind === 256 /* NamespaceImport */
  11793. || kind === 262 /* NamespaceExport */
  11794. || kind === 156 /* Parameter */
  11795. || kind === 281 /* PropertyAssignment */
  11796. || kind === 159 /* PropertyDeclaration */
  11797. || kind === 158 /* PropertySignature */
  11798. || kind === 164 /* SetAccessor */
  11799. || kind === 282 /* ShorthandPropertyAssignment */
  11800. || kind === 247 /* TypeAliasDeclaration */
  11801. || kind === 155 /* TypeParameter */
  11802. || kind === 242 /* VariableDeclaration */
  11803. || kind === 321 /* JSDocTypedefTag */
  11804. || kind === 314 /* JSDocCallbackTag */
  11805. || kind === 322 /* JSDocPropertyTag */;
  11806. }
  11807. function isDeclarationStatementKind(kind) {
  11808. return kind === 244 /* FunctionDeclaration */
  11809. || kind === 264 /* MissingDeclaration */
  11810. || kind === 245 /* ClassDeclaration */
  11811. || kind === 246 /* InterfaceDeclaration */
  11812. || kind === 247 /* TypeAliasDeclaration */
  11813. || kind === 248 /* EnumDeclaration */
  11814. || kind === 249 /* ModuleDeclaration */
  11815. || kind === 254 /* ImportDeclaration */
  11816. || kind === 253 /* ImportEqualsDeclaration */
  11817. || kind === 260 /* ExportDeclaration */
  11818. || kind === 259 /* ExportAssignment */
  11819. || kind === 252 /* NamespaceExportDeclaration */;
  11820. }
  11821. function isStatementKindButNotDeclarationKind(kind) {
  11822. return kind === 234 /* BreakStatement */
  11823. || kind === 233 /* ContinueStatement */
  11824. || kind === 241 /* DebuggerStatement */
  11825. || kind === 228 /* DoStatement */
  11826. || kind === 226 /* ExpressionStatement */
  11827. || kind === 224 /* EmptyStatement */
  11828. || kind === 231 /* ForInStatement */
  11829. || kind === 232 /* ForOfStatement */
  11830. || kind === 230 /* ForStatement */
  11831. || kind === 227 /* IfStatement */
  11832. || kind === 238 /* LabeledStatement */
  11833. || kind === 235 /* ReturnStatement */
  11834. || kind === 237 /* SwitchStatement */
  11835. || kind === 239 /* ThrowStatement */
  11836. || kind === 240 /* TryStatement */
  11837. || kind === 225 /* VariableStatement */
  11838. || kind === 229 /* WhileStatement */
  11839. || kind === 236 /* WithStatement */
  11840. || kind === 324 /* NotEmittedStatement */
  11841. || kind === 328 /* EndOfDeclarationMarker */
  11842. || kind === 327 /* MergeDeclarationMarker */;
  11843. }
  11844. /* @internal */
  11845. function isDeclaration(node) {
  11846. if (node.kind === 155 /* TypeParameter */) {
  11847. return (node.parent && node.parent.kind !== 320 /* JSDocTemplateTag */) || ts.isInJSFile(node);
  11848. }
  11849. return isDeclarationKind(node.kind);
  11850. }
  11851. ts.isDeclaration = isDeclaration;
  11852. /* @internal */
  11853. function isDeclarationStatement(node) {
  11854. return isDeclarationStatementKind(node.kind);
  11855. }
  11856. ts.isDeclarationStatement = isDeclarationStatement;
  11857. /**
  11858. * Determines whether the node is a statement that is not also a declaration
  11859. */
  11860. /* @internal */
  11861. function isStatementButNotDeclaration(node) {
  11862. return isStatementKindButNotDeclarationKind(node.kind);
  11863. }
  11864. ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
  11865. /* @internal */
  11866. function isStatement(node) {
  11867. var kind = node.kind;
  11868. return isStatementKindButNotDeclarationKind(kind)
  11869. || isDeclarationStatementKind(kind)
  11870. || isBlockStatement(node);
  11871. }
  11872. ts.isStatement = isStatement;
  11873. function isBlockStatement(node) {
  11874. if (node.kind !== 223 /* Block */)
  11875. return false;
  11876. if (node.parent !== undefined) {
  11877. if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
  11878. return false;
  11879. }
  11880. }
  11881. return !ts.isFunctionBlock(node);
  11882. }
  11883. // Module references
  11884. /* @internal */
  11885. function isModuleReference(node) {
  11886. var kind = node.kind;
  11887. return kind === 265 /* ExternalModuleReference */
  11888. || kind === 153 /* QualifiedName */
  11889. || kind === 75 /* Identifier */;
  11890. }
  11891. ts.isModuleReference = isModuleReference;
  11892. // JSX
  11893. /* @internal */
  11894. function isJsxTagNameExpression(node) {
  11895. var kind = node.kind;
  11896. return kind === 104 /* ThisKeyword */
  11897. || kind === 75 /* Identifier */
  11898. || kind === 194 /* PropertyAccessExpression */;
  11899. }
  11900. ts.isJsxTagNameExpression = isJsxTagNameExpression;
  11901. /* @internal */
  11902. function isJsxChild(node) {
  11903. var kind = node.kind;
  11904. return kind === 266 /* JsxElement */
  11905. || kind === 276 /* JsxExpression */
  11906. || kind === 267 /* JsxSelfClosingElement */
  11907. || kind === 11 /* JsxText */
  11908. || kind === 270 /* JsxFragment */;
  11909. }
  11910. ts.isJsxChild = isJsxChild;
  11911. /* @internal */
  11912. function isJsxAttributeLike(node) {
  11913. var kind = node.kind;
  11914. return kind === 273 /* JsxAttribute */
  11915. || kind === 275 /* JsxSpreadAttribute */;
  11916. }
  11917. ts.isJsxAttributeLike = isJsxAttributeLike;
  11918. /* @internal */
  11919. function isStringLiteralOrJsxExpression(node) {
  11920. var kind = node.kind;
  11921. return kind === 10 /* StringLiteral */
  11922. || kind === 276 /* JsxExpression */;
  11923. }
  11924. ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
  11925. function isJsxOpeningLikeElement(node) {
  11926. var kind = node.kind;
  11927. return kind === 268 /* JsxOpeningElement */
  11928. || kind === 267 /* JsxSelfClosingElement */;
  11929. }
  11930. ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
  11931. // Clauses
  11932. function isCaseOrDefaultClause(node) {
  11933. var kind = node.kind;
  11934. return kind === 277 /* CaseClause */
  11935. || kind === 278 /* DefaultClause */;
  11936. }
  11937. ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
  11938. // JSDoc
  11939. /** True if node is of some JSDoc syntax kind. */
  11940. /* @internal */
  11941. function isJSDocNode(node) {
  11942. return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 322 /* LastJSDocNode */;
  11943. }
  11944. ts.isJSDocNode = isJSDocNode;
  11945. /** True if node is of a kind that may contain comment text. */
  11946. function isJSDocCommentContainingNode(node) {
  11947. return node.kind === 303 /* JSDocComment */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
  11948. }
  11949. ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
  11950. // TODO: determine what this does before making it public.
  11951. /* @internal */
  11952. function isJSDocTag(node) {
  11953. return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 322 /* LastJSDocTagNode */;
  11954. }
  11955. ts.isJSDocTag = isJSDocTag;
  11956. function isSetAccessor(node) {
  11957. return node.kind === 164 /* SetAccessor */;
  11958. }
  11959. ts.isSetAccessor = isSetAccessor;
  11960. function isGetAccessor(node) {
  11961. return node.kind === 163 /* GetAccessor */;
  11962. }
  11963. ts.isGetAccessor = isGetAccessor;
  11964. /** True if has jsdoc nodes attached to it. */
  11965. /* @internal */
  11966. // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
  11967. function hasJSDocNodes(node) {
  11968. var jsDoc = node.jsDoc;
  11969. return !!jsDoc && jsDoc.length > 0;
  11970. }
  11971. ts.hasJSDocNodes = hasJSDocNodes;
  11972. /** True if has type node attached to it. */
  11973. /* @internal */
  11974. function hasType(node) {
  11975. return !!node.type;
  11976. }
  11977. ts.hasType = hasType;
  11978. /** True if has initializer node attached to it. */
  11979. /* @internal */
  11980. function hasInitializer(node) {
  11981. return !!node.initializer;
  11982. }
  11983. ts.hasInitializer = hasInitializer;
  11984. /** True if has initializer node attached to it. */
  11985. /* @internal */
  11986. function hasOnlyExpressionInitializer(node) {
  11987. return hasInitializer(node) && !isForStatement(node) && !isForInStatement(node) && !isForOfStatement(node) && !isJsxAttribute(node);
  11988. }
  11989. ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
  11990. function isObjectLiteralElement(node) {
  11991. return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
  11992. }
  11993. ts.isObjectLiteralElement = isObjectLiteralElement;
  11994. /* @internal */
  11995. function isTypeReferenceType(node) {
  11996. return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
  11997. }
  11998. ts.isTypeReferenceType = isTypeReferenceType;
  11999. var MAX_SMI_X86 = 1073741823;
  12000. /* @internal */
  12001. function guessIndentation(lines) {
  12002. var indentation = MAX_SMI_X86;
  12003. for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
  12004. var line = lines_1[_i];
  12005. if (!line.length) {
  12006. continue;
  12007. }
  12008. var i = 0;
  12009. for (; i < line.length && i < indentation; i++) {
  12010. if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
  12011. break;
  12012. }
  12013. }
  12014. if (i < indentation) {
  12015. indentation = i;
  12016. }
  12017. if (indentation === 0) {
  12018. return 0;
  12019. }
  12020. }
  12021. return indentation === MAX_SMI_X86 ? undefined : indentation;
  12022. }
  12023. ts.guessIndentation = guessIndentation;
  12024. function isStringLiteralLike(node) {
  12025. return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
  12026. }
  12027. ts.isStringLiteralLike = isStringLiteralLike;
  12028. // #endregion
  12029. })(ts || (ts = {}));
  12030. /* @internal */
  12031. var ts;
  12032. (function (ts) {
  12033. ts.resolvingEmptyArray = [];
  12034. ts.emptyMap = ts.createMap();
  12035. ts.emptyUnderscoreEscapedMap = ts.emptyMap;
  12036. ts.externalHelpersModuleNameText = "tslib";
  12037. ts.defaultMaximumTruncationLength = 160;
  12038. function getDeclarationOfKind(symbol, kind) {
  12039. var declarations = symbol.declarations;
  12040. if (declarations) {
  12041. for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
  12042. var declaration = declarations_1[_i];
  12043. if (declaration.kind === kind) {
  12044. return declaration;
  12045. }
  12046. }
  12047. }
  12048. return undefined;
  12049. }
  12050. ts.getDeclarationOfKind = getDeclarationOfKind;
  12051. /** Create a new escaped identifier map. */
  12052. function createUnderscoreEscapedMap() {
  12053. return new ts.Map();
  12054. }
  12055. ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
  12056. function hasEntries(map) {
  12057. return !!map && !!map.size;
  12058. }
  12059. ts.hasEntries = hasEntries;
  12060. function createSymbolTable(symbols) {
  12061. var result = ts.createMap();
  12062. if (symbols) {
  12063. for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
  12064. var symbol = symbols_1[_i];
  12065. result.set(symbol.escapedName, symbol);
  12066. }
  12067. }
  12068. return result;
  12069. }
  12070. ts.createSymbolTable = createSymbolTable;
  12071. function isTransientSymbol(symbol) {
  12072. return (symbol.flags & 33554432 /* Transient */) !== 0;
  12073. }
  12074. ts.isTransientSymbol = isTransientSymbol;
  12075. var stringWriter = createSingleLineStringWriter();
  12076. function createSingleLineStringWriter() {
  12077. var str = "";
  12078. var writeText = function (text) { return str += text; };
  12079. return {
  12080. getText: function () { return str; },
  12081. write: writeText,
  12082. rawWrite: writeText,
  12083. writeKeyword: writeText,
  12084. writeOperator: writeText,
  12085. writePunctuation: writeText,
  12086. writeSpace: writeText,
  12087. writeStringLiteral: writeText,
  12088. writeLiteral: writeText,
  12089. writeParameter: writeText,
  12090. writeProperty: writeText,
  12091. writeSymbol: function (s, _) { return writeText(s); },
  12092. writeTrailingSemicolon: writeText,
  12093. writeComment: writeText,
  12094. getTextPos: function () { return str.length; },
  12095. getLine: function () { return 0; },
  12096. getColumn: function () { return 0; },
  12097. getIndent: function () { return 0; },
  12098. isAtStartOfLine: function () { return false; },
  12099. hasTrailingComment: function () { return false; },
  12100. hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
  12101. // Completely ignore indentation for string writers. And map newlines to
  12102. // a single space.
  12103. writeLine: function () { return str += " "; },
  12104. increaseIndent: ts.noop,
  12105. decreaseIndent: ts.noop,
  12106. clear: function () { return str = ""; },
  12107. trackSymbol: ts.noop,
  12108. reportInaccessibleThisError: ts.noop,
  12109. reportInaccessibleUniqueSymbolError: ts.noop,
  12110. reportPrivateInBaseOfClassExpression: ts.noop,
  12111. };
  12112. }
  12113. function changesAffectModuleResolution(oldOptions, newOptions) {
  12114. return oldOptions.configFilePath !== newOptions.configFilePath ||
  12115. optionsHaveModuleResolutionChanges(oldOptions, newOptions);
  12116. }
  12117. ts.changesAffectModuleResolution = changesAffectModuleResolution;
  12118. function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
  12119. return ts.moduleResolutionOptionDeclarations.some(function (o) {
  12120. return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
  12121. });
  12122. }
  12123. ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
  12124. function findAncestor(node, callback) {
  12125. while (node) {
  12126. var result = callback(node);
  12127. if (result === "quit") {
  12128. return undefined;
  12129. }
  12130. else if (result) {
  12131. return node;
  12132. }
  12133. node = node.parent;
  12134. }
  12135. return undefined;
  12136. }
  12137. ts.findAncestor = findAncestor;
  12138. function forEachAncestor(node, callback) {
  12139. while (true) {
  12140. var res = callback(node);
  12141. if (res === "quit")
  12142. return undefined;
  12143. if (res !== undefined)
  12144. return res;
  12145. if (ts.isSourceFile(node))
  12146. return undefined;
  12147. node = node.parent;
  12148. }
  12149. }
  12150. ts.forEachAncestor = forEachAncestor;
  12151. function forEachEntry(map, callback) {
  12152. var iterator = map.entries();
  12153. for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
  12154. var _a = iterResult.value, key = _a[0], value = _a[1];
  12155. var result = callback(value, key);
  12156. if (result) {
  12157. return result;
  12158. }
  12159. }
  12160. return undefined;
  12161. }
  12162. ts.forEachEntry = forEachEntry;
  12163. function forEachKey(map, callback) {
  12164. var iterator = map.keys();
  12165. for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
  12166. var result = callback(iterResult.value);
  12167. if (result) {
  12168. return result;
  12169. }
  12170. }
  12171. return undefined;
  12172. }
  12173. ts.forEachKey = forEachKey;
  12174. function copyEntries(source, target) {
  12175. source.forEach(function (value, key) {
  12176. target.set(key, value);
  12177. });
  12178. }
  12179. ts.copyEntries = copyEntries;
  12180. function arrayToSet(array, makeKey) {
  12181. return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
  12182. }
  12183. ts.arrayToSet = arrayToSet;
  12184. function cloneMap(map) {
  12185. var clone = ts.createMap();
  12186. copyEntries(map, clone);
  12187. return clone;
  12188. }
  12189. ts.cloneMap = cloneMap;
  12190. function usingSingleLineStringWriter(action) {
  12191. var oldString = stringWriter.getText();
  12192. try {
  12193. action(stringWriter);
  12194. return stringWriter.getText();
  12195. }
  12196. finally {
  12197. stringWriter.clear();
  12198. stringWriter.writeKeyword(oldString);
  12199. }
  12200. }
  12201. ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
  12202. function getFullWidth(node) {
  12203. return node.end - node.pos;
  12204. }
  12205. ts.getFullWidth = getFullWidth;
  12206. function getResolvedModule(sourceFile, moduleNameText) {
  12207. return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
  12208. }
  12209. ts.getResolvedModule = getResolvedModule;
  12210. function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
  12211. if (!sourceFile.resolvedModules) {
  12212. sourceFile.resolvedModules = ts.createMap();
  12213. }
  12214. sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
  12215. }
  12216. ts.setResolvedModule = setResolvedModule;
  12217. function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
  12218. if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
  12219. sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
  12220. }
  12221. sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
  12222. }
  12223. ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
  12224. function projectReferenceIsEqualTo(oldRef, newRef) {
  12225. return oldRef.path === newRef.path &&
  12226. !oldRef.prepend === !newRef.prepend &&
  12227. !oldRef.circular === !newRef.circular;
  12228. }
  12229. ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
  12230. function moduleResolutionIsEqualTo(oldResolution, newResolution) {
  12231. return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
  12232. oldResolution.extension === newResolution.extension &&
  12233. oldResolution.resolvedFileName === newResolution.resolvedFileName &&
  12234. oldResolution.originalPath === newResolution.originalPath &&
  12235. packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
  12236. }
  12237. ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
  12238. function packageIdIsEqual(a, b) {
  12239. return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
  12240. }
  12241. function packageIdToString(_a) {
  12242. var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
  12243. var fullName = subModuleName ? name + "/" + subModuleName : name;
  12244. return fullName + "@" + version;
  12245. }
  12246. ts.packageIdToString = packageIdToString;
  12247. function typeDirectiveIsEqualTo(oldResolution, newResolution) {
  12248. return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
  12249. }
  12250. ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
  12251. function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
  12252. ts.Debug.assert(names.length === newResolutions.length);
  12253. for (var i = 0; i < names.length; i++) {
  12254. var newResolution = newResolutions[i];
  12255. var oldResolution = oldResolutions && oldResolutions.get(names[i]);
  12256. var changed = oldResolution
  12257. ? !newResolution || !comparer(oldResolution, newResolution)
  12258. : newResolution;
  12259. if (changed) {
  12260. return true;
  12261. }
  12262. }
  12263. return false;
  12264. }
  12265. ts.hasChangesInResolutions = hasChangesInResolutions;
  12266. // Returns true if this node contains a parse error anywhere underneath it.
  12267. function containsParseError(node) {
  12268. aggregateChildData(node);
  12269. return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
  12270. }
  12271. ts.containsParseError = containsParseError;
  12272. function aggregateChildData(node) {
  12273. if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
  12274. // A node is considered to contain a parse error if:
  12275. // a) the parser explicitly marked that it had an error
  12276. // b) any of it's children reported that it had an error.
  12277. var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
  12278. ts.forEachChild(node, containsParseError);
  12279. // If so, mark ourselves accordingly.
  12280. if (thisNodeOrAnySubNodesHasError) {
  12281. node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
  12282. }
  12283. // Also mark that we've propagated the child information to this node. This way we can
  12284. // always consult the bit directly on this node without needing to check its children
  12285. // again.
  12286. node.flags |= 524288 /* HasAggregatedChildData */;
  12287. }
  12288. }
  12289. function getSourceFileOfNode(node) {
  12290. while (node && node.kind !== 290 /* SourceFile */) {
  12291. node = node.parent;
  12292. }
  12293. return node;
  12294. }
  12295. ts.getSourceFileOfNode = getSourceFileOfNode;
  12296. function isStatementWithLocals(node) {
  12297. switch (node.kind) {
  12298. case 223 /* Block */:
  12299. case 251 /* CaseBlock */:
  12300. case 230 /* ForStatement */:
  12301. case 231 /* ForInStatement */:
  12302. case 232 /* ForOfStatement */:
  12303. return true;
  12304. }
  12305. return false;
  12306. }
  12307. ts.isStatementWithLocals = isStatementWithLocals;
  12308. function getStartPositionOfLine(line, sourceFile) {
  12309. ts.Debug.assert(line >= 0);
  12310. return ts.getLineStarts(sourceFile)[line];
  12311. }
  12312. ts.getStartPositionOfLine = getStartPositionOfLine;
  12313. // This is a useful function for debugging purposes.
  12314. function nodePosToString(node) {
  12315. var file = getSourceFileOfNode(node);
  12316. var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
  12317. return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
  12318. }
  12319. ts.nodePosToString = nodePosToString;
  12320. function getEndLinePosition(line, sourceFile) {
  12321. ts.Debug.assert(line >= 0);
  12322. var lineStarts = ts.getLineStarts(sourceFile);
  12323. var lineIndex = line;
  12324. var sourceText = sourceFile.text;
  12325. if (lineIndex + 1 === lineStarts.length) {
  12326. // last line - return EOF
  12327. return sourceText.length - 1;
  12328. }
  12329. else {
  12330. // current line start
  12331. var start = lineStarts[lineIndex];
  12332. // take the start position of the next line - 1 = it should be some line break
  12333. var pos = lineStarts[lineIndex + 1] - 1;
  12334. ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
  12335. // walk backwards skipping line breaks, stop the the beginning of current line.
  12336. // i.e:
  12337. // <some text>
  12338. // $ <- end of line for this position should match the start position
  12339. while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
  12340. pos--;
  12341. }
  12342. return pos;
  12343. }
  12344. }
  12345. ts.getEndLinePosition = getEndLinePosition;
  12346. /**
  12347. * Returns a value indicating whether a name is unique globally or within the current file.
  12348. * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`.
  12349. */
  12350. function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
  12351. return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
  12352. }
  12353. ts.isFileLevelUniqueName = isFileLevelUniqueName;
  12354. // Returns true if this node is missing from the actual source code. A 'missing' node is different
  12355. // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
  12356. // in the tree), it is definitely missing. However, a node may be defined, but still be
  12357. // missing. This happens whenever the parser knows it needs to parse something, but can't
  12358. // get anything in the source code that it expects at that location. For example:
  12359. //
  12360. // let a: ;
  12361. //
  12362. // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
  12363. // code). So the parser will attempt to parse out a type, and will create an actual node.
  12364. // However, this node will be 'missing' in the sense that no actual source-code/tokens are
  12365. // contained within it.
  12366. function nodeIsMissing(node) {
  12367. if (node === undefined) {
  12368. return true;
  12369. }
  12370. return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
  12371. }
  12372. ts.nodeIsMissing = nodeIsMissing;
  12373. function nodeIsPresent(node) {
  12374. return !nodeIsMissing(node);
  12375. }
  12376. ts.nodeIsPresent = nodeIsPresent;
  12377. function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
  12378. if (from === undefined || from.length === 0)
  12379. return to;
  12380. var statementIndex = 0;
  12381. // skip all prologue directives to insert at the correct position
  12382. for (; statementIndex < to.length; ++statementIndex) {
  12383. if (!isPrologueDirective(to[statementIndex])) {
  12384. break;
  12385. }
  12386. }
  12387. to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
  12388. return to;
  12389. }
  12390. function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
  12391. if (statement === undefined)
  12392. return to;
  12393. var statementIndex = 0;
  12394. // skip all prologue directives to insert at the correct position
  12395. for (; statementIndex < to.length; ++statementIndex) {
  12396. if (!isPrologueDirective(to[statementIndex])) {
  12397. break;
  12398. }
  12399. }
  12400. to.splice(statementIndex, 0, statement);
  12401. return to;
  12402. }
  12403. function isAnyPrologueDirective(node) {
  12404. return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
  12405. }
  12406. /**
  12407. * Prepends statements to an array while taking care of prologue directives.
  12408. */
  12409. function insertStatementsAfterStandardPrologue(to, from) {
  12410. return insertStatementsAfterPrologue(to, from, isPrologueDirective);
  12411. }
  12412. ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
  12413. function insertStatementsAfterCustomPrologue(to, from) {
  12414. return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
  12415. }
  12416. ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
  12417. /**
  12418. * Prepends statements to an array while taking care of prologue directives.
  12419. */
  12420. function insertStatementAfterStandardPrologue(to, statement) {
  12421. return insertStatementAfterPrologue(to, statement, isPrologueDirective);
  12422. }
  12423. ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
  12424. function insertStatementAfterCustomPrologue(to, statement) {
  12425. return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
  12426. }
  12427. ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
  12428. /**
  12429. * Determine if the given comment is a triple-slash
  12430. *
  12431. * @return true if the comment is a triple-slash comment else false
  12432. */
  12433. function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
  12434. // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
  12435. // so that we don't end up computing comment string and doing match for all // comments
  12436. if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
  12437. commentPos + 2 < commentEnd &&
  12438. text.charCodeAt(commentPos + 2) === 47 /* slash */) {
  12439. var textSubStr = text.substring(commentPos, commentEnd);
  12440. return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
  12441. textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
  12442. textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
  12443. textSubStr.match(defaultLibReferenceRegEx) ?
  12444. true : false;
  12445. }
  12446. return false;
  12447. }
  12448. ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
  12449. function isPinnedComment(text, start) {
  12450. return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
  12451. text.charCodeAt(start + 2) === 33 /* exclamation */;
  12452. }
  12453. ts.isPinnedComment = isPinnedComment;
  12454. function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
  12455. // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
  12456. // want to skip trivia because this will launch us forward to the next token.
  12457. if (nodeIsMissing(node)) {
  12458. return node.pos;
  12459. }
  12460. if (ts.isJSDocNode(node)) {
  12461. return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
  12462. }
  12463. if (includeJsDoc && ts.hasJSDocNodes(node)) {
  12464. return getTokenPosOfNode(node.jsDoc[0]);
  12465. }
  12466. // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
  12467. // the syntax list itself considers them as normal trivia. Therefore if we simply skip
  12468. // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
  12469. // first child to determine the actual position of its first token.
  12470. if (node.kind === 323 /* SyntaxList */ && node._children.length > 0) {
  12471. return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
  12472. }
  12473. return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
  12474. }
  12475. ts.getTokenPosOfNode = getTokenPosOfNode;
  12476. function getNonDecoratorTokenPosOfNode(node, sourceFile) {
  12477. if (nodeIsMissing(node) || !node.decorators) {
  12478. return getTokenPosOfNode(node, sourceFile);
  12479. }
  12480. return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
  12481. }
  12482. ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
  12483. function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
  12484. if (includeTrivia === void 0) { includeTrivia = false; }
  12485. return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
  12486. }
  12487. ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
  12488. function isJSDocTypeExpressionOrChild(node) {
  12489. return !!findAncestor(node, ts.isJSDocTypeExpression);
  12490. }
  12491. function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
  12492. if (includeTrivia === void 0) { includeTrivia = false; }
  12493. if (nodeIsMissing(node)) {
  12494. return "";
  12495. }
  12496. var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
  12497. if (isJSDocTypeExpressionOrChild(node)) {
  12498. // strip space + asterisk at line start
  12499. text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
  12500. }
  12501. return text;
  12502. }
  12503. ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
  12504. function getTextOfNode(node, includeTrivia) {
  12505. if (includeTrivia === void 0) { includeTrivia = false; }
  12506. return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
  12507. }
  12508. ts.getTextOfNode = getTextOfNode;
  12509. function getPos(range) {
  12510. return range.pos;
  12511. }
  12512. /**
  12513. * Note: it is expected that the `nodeArray` and the `node` are within the same file.
  12514. * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
  12515. */
  12516. function indexOfNode(nodeArray, node) {
  12517. return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
  12518. }
  12519. ts.indexOfNode = indexOfNode;
  12520. /**
  12521. * Gets flags that control emit behavior of a node.
  12522. */
  12523. function getEmitFlags(node) {
  12524. var emitNode = node.emitNode;
  12525. return emitNode && emitNode.flags || 0;
  12526. }
  12527. ts.getEmitFlags = getEmitFlags;
  12528. function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
  12529. // If we don't need to downlevel and we can reach the original source text using
  12530. // the node's parent reference, then simply get the text as it was originally written.
  12531. if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
  12532. ts.isBigIntLiteral(node))) {
  12533. return getSourceTextOfNodeFromSourceFile(sourceFile, node);
  12534. }
  12535. // If we can't reach the original source text, use the canonical form if it's a number,
  12536. // or a (possibly escaped) quoted form of the original text if it's string-like.
  12537. switch (node.kind) {
  12538. case 10 /* StringLiteral */: {
  12539. var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
  12540. neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
  12541. escapeNonAsciiString;
  12542. if (node.singleQuote) {
  12543. return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
  12544. }
  12545. else {
  12546. return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
  12547. }
  12548. }
  12549. case 14 /* NoSubstitutionTemplateLiteral */:
  12550. case 15 /* TemplateHead */:
  12551. case 16 /* TemplateMiddle */:
  12552. case 17 /* TemplateTail */: {
  12553. // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
  12554. // had to include a backslash: `not \${a} substitution`.
  12555. var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
  12556. escapeNonAsciiString;
  12557. var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
  12558. switch (node.kind) {
  12559. case 14 /* NoSubstitutionTemplateLiteral */:
  12560. return "`" + rawText + "`";
  12561. case 15 /* TemplateHead */:
  12562. return "`" + rawText + "${";
  12563. case 16 /* TemplateMiddle */:
  12564. return "}" + rawText + "${";
  12565. case 17 /* TemplateTail */:
  12566. return "}" + rawText + "`";
  12567. }
  12568. break;
  12569. }
  12570. case 8 /* NumericLiteral */:
  12571. case 9 /* BigIntLiteral */:
  12572. case 13 /* RegularExpressionLiteral */:
  12573. return node.text;
  12574. }
  12575. return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
  12576. }
  12577. ts.getLiteralText = getLiteralText;
  12578. function getTextOfConstantValue(value) {
  12579. return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
  12580. }
  12581. ts.getTextOfConstantValue = getTextOfConstantValue;
  12582. // Make an identifier from an external module name by extracting the string after the last "/" and replacing
  12583. // all non-alphanumeric characters with underscores
  12584. function makeIdentifierFromModuleName(moduleName) {
  12585. return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
  12586. }
  12587. ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
  12588. function isBlockOrCatchScoped(declaration) {
  12589. return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
  12590. isCatchClauseVariableDeclarationOrBindingElement(declaration);
  12591. }
  12592. ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
  12593. function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
  12594. var node = getRootDeclaration(declaration);
  12595. return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
  12596. }
  12597. ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
  12598. function isAmbientModule(node) {
  12599. return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
  12600. }
  12601. ts.isAmbientModule = isAmbientModule;
  12602. function isModuleWithStringLiteralName(node) {
  12603. return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
  12604. }
  12605. ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
  12606. function isNonGlobalAmbientModule(node) {
  12607. return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
  12608. }
  12609. ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
  12610. /**
  12611. * An effective module (namespace) declaration is either
  12612. * 1. An actual declaration: namespace X { ... }
  12613. * 2. A Javascript declaration, which is:
  12614. * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
  12615. */
  12616. function isEffectiveModuleDeclaration(node) {
  12617. return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
  12618. }
  12619. ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
  12620. /** Given a symbol for a module, checks that it is a shorthand ambient module. */
  12621. function isShorthandAmbientModuleSymbol(moduleSymbol) {
  12622. return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
  12623. }
  12624. ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
  12625. function isShorthandAmbientModule(node) {
  12626. // The only kind of module that can be missing a body is a shorthand ambient module.
  12627. return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
  12628. }
  12629. function isBlockScopedContainerTopLevel(node) {
  12630. return node.kind === 290 /* SourceFile */ ||
  12631. node.kind === 249 /* ModuleDeclaration */ ||
  12632. ts.isFunctionLike(node);
  12633. }
  12634. ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
  12635. function isGlobalScopeAugmentation(module) {
  12636. return !!(module.flags & 1024 /* GlobalAugmentation */);
  12637. }
  12638. ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
  12639. function isExternalModuleAugmentation(node) {
  12640. return isAmbientModule(node) && isModuleAugmentationExternal(node);
  12641. }
  12642. ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
  12643. function isModuleAugmentationExternal(node) {
  12644. // external module augmentation is a ambient module declaration that is either:
  12645. // - defined in the top level scope and source file is an external module
  12646. // - defined inside ambient module declaration located in the top level scope and source file not an external module
  12647. switch (node.parent.kind) {
  12648. case 290 /* SourceFile */:
  12649. return ts.isExternalModule(node.parent);
  12650. case 250 /* ModuleBlock */:
  12651. return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
  12652. }
  12653. return false;
  12654. }
  12655. ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
  12656. function getNonAugmentationDeclaration(symbol) {
  12657. return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
  12658. }
  12659. ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
  12660. function isEffectiveExternalModule(node, compilerOptions) {
  12661. return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
  12662. }
  12663. ts.isEffectiveExternalModule = isEffectiveExternalModule;
  12664. /**
  12665. * Returns whether the source file will be treated as if it were in strict mode at runtime.
  12666. */
  12667. function isEffectiveStrictModeSourceFile(node, compilerOptions) {
  12668. // We can only verify strict mode for JS/TS files
  12669. switch (node.scriptKind) {
  12670. case 1 /* JS */:
  12671. case 3 /* TS */:
  12672. case 2 /* JSX */:
  12673. case 4 /* TSX */:
  12674. break;
  12675. default:
  12676. return false;
  12677. }
  12678. // Strict mode does not matter for declaration files.
  12679. if (node.isDeclarationFile) {
  12680. return false;
  12681. }
  12682. // If `alwaysStrict` is set, then treat the file as strict.
  12683. if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
  12684. return true;
  12685. }
  12686. // Starting with a "use strict" directive indicates the file is strict.
  12687. if (ts.startsWithUseStrict(node.statements)) {
  12688. return true;
  12689. }
  12690. if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
  12691. // ECMAScript Modules are always strict.
  12692. if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
  12693. return true;
  12694. }
  12695. // Other modules are strict unless otherwise specified.
  12696. return !compilerOptions.noImplicitUseStrict;
  12697. }
  12698. return false;
  12699. }
  12700. ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
  12701. function isBlockScope(node, parentNode) {
  12702. switch (node.kind) {
  12703. case 290 /* SourceFile */:
  12704. case 251 /* CaseBlock */:
  12705. case 280 /* CatchClause */:
  12706. case 249 /* ModuleDeclaration */:
  12707. case 230 /* ForStatement */:
  12708. case 231 /* ForInStatement */:
  12709. case 232 /* ForOfStatement */:
  12710. case 162 /* Constructor */:
  12711. case 161 /* MethodDeclaration */:
  12712. case 163 /* GetAccessor */:
  12713. case 164 /* SetAccessor */:
  12714. case 244 /* FunctionDeclaration */:
  12715. case 201 /* FunctionExpression */:
  12716. case 202 /* ArrowFunction */:
  12717. return true;
  12718. case 223 /* Block */:
  12719. // function block is not considered block-scope container
  12720. // see comment in binder.ts: bind(...), case for SyntaxKind.Block
  12721. return !ts.isFunctionLike(parentNode);
  12722. }
  12723. return false;
  12724. }
  12725. ts.isBlockScope = isBlockScope;
  12726. function isDeclarationWithTypeParameters(node) {
  12727. switch (node.kind) {
  12728. case 314 /* JSDocCallbackTag */:
  12729. case 321 /* JSDocTypedefTag */:
  12730. case 305 /* JSDocSignature */:
  12731. return true;
  12732. default:
  12733. ts.assertType(node);
  12734. return isDeclarationWithTypeParameterChildren(node);
  12735. }
  12736. }
  12737. ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
  12738. function isDeclarationWithTypeParameterChildren(node) {
  12739. switch (node.kind) {
  12740. case 165 /* CallSignature */:
  12741. case 166 /* ConstructSignature */:
  12742. case 160 /* MethodSignature */:
  12743. case 167 /* IndexSignature */:
  12744. case 170 /* FunctionType */:
  12745. case 171 /* ConstructorType */:
  12746. case 300 /* JSDocFunctionType */:
  12747. case 245 /* ClassDeclaration */:
  12748. case 214 /* ClassExpression */:
  12749. case 246 /* InterfaceDeclaration */:
  12750. case 247 /* TypeAliasDeclaration */:
  12751. case 320 /* JSDocTemplateTag */:
  12752. case 244 /* FunctionDeclaration */:
  12753. case 161 /* MethodDeclaration */:
  12754. case 162 /* Constructor */:
  12755. case 163 /* GetAccessor */:
  12756. case 164 /* SetAccessor */:
  12757. case 201 /* FunctionExpression */:
  12758. case 202 /* ArrowFunction */:
  12759. return true;
  12760. default:
  12761. ts.assertType(node);
  12762. return false;
  12763. }
  12764. }
  12765. ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
  12766. function isAnyImportSyntax(node) {
  12767. switch (node.kind) {
  12768. case 254 /* ImportDeclaration */:
  12769. case 253 /* ImportEqualsDeclaration */:
  12770. return true;
  12771. default:
  12772. return false;
  12773. }
  12774. }
  12775. ts.isAnyImportSyntax = isAnyImportSyntax;
  12776. function isLateVisibilityPaintedStatement(node) {
  12777. switch (node.kind) {
  12778. case 254 /* ImportDeclaration */:
  12779. case 253 /* ImportEqualsDeclaration */:
  12780. case 225 /* VariableStatement */:
  12781. case 245 /* ClassDeclaration */:
  12782. case 244 /* FunctionDeclaration */:
  12783. case 249 /* ModuleDeclaration */:
  12784. case 247 /* TypeAliasDeclaration */:
  12785. case 246 /* InterfaceDeclaration */:
  12786. case 248 /* EnumDeclaration */:
  12787. return true;
  12788. default:
  12789. return false;
  12790. }
  12791. }
  12792. ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
  12793. function isAnyImportOrReExport(node) {
  12794. return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
  12795. }
  12796. ts.isAnyImportOrReExport = isAnyImportOrReExport;
  12797. // Gets the nearest enclosing block scope container that has the provided node
  12798. // as a descendant, that is not the provided node.
  12799. function getEnclosingBlockScopeContainer(node) {
  12800. return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
  12801. }
  12802. ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
  12803. // Return display name of an identifier
  12804. // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
  12805. // text of the expression in the computed property.
  12806. function declarationNameToString(name) {
  12807. return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
  12808. }
  12809. ts.declarationNameToString = declarationNameToString;
  12810. function getNameFromIndexInfo(info) {
  12811. return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
  12812. }
  12813. ts.getNameFromIndexInfo = getNameFromIndexInfo;
  12814. function getTextOfPropertyName(name) {
  12815. switch (name.kind) {
  12816. case 75 /* Identifier */:
  12817. case 76 /* PrivateIdentifier */:
  12818. return name.escapedText;
  12819. case 10 /* StringLiteral */:
  12820. case 8 /* NumericLiteral */:
  12821. case 14 /* NoSubstitutionTemplateLiteral */:
  12822. return ts.escapeLeadingUnderscores(name.text);
  12823. case 154 /* ComputedPropertyName */:
  12824. if (isStringOrNumericLiteralLike(name.expression))
  12825. return ts.escapeLeadingUnderscores(name.expression.text);
  12826. return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
  12827. default:
  12828. return ts.Debug.assertNever(name);
  12829. }
  12830. }
  12831. ts.getTextOfPropertyName = getTextOfPropertyName;
  12832. function entityNameToString(name) {
  12833. switch (name.kind) {
  12834. case 75 /* Identifier */:
  12835. return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
  12836. case 153 /* QualifiedName */:
  12837. return entityNameToString(name.left) + "." + entityNameToString(name.right);
  12838. case 194 /* PropertyAccessExpression */:
  12839. if (ts.isIdentifier(name.name)) {
  12840. return entityNameToString(name.expression) + "." + entityNameToString(name.name);
  12841. }
  12842. else {
  12843. return ts.Debug.assertNever(name.name);
  12844. }
  12845. default:
  12846. return ts.Debug.assertNever(name);
  12847. }
  12848. }
  12849. ts.entityNameToString = entityNameToString;
  12850. function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
  12851. var sourceFile = getSourceFileOfNode(node);
  12852. return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
  12853. }
  12854. ts.createDiagnosticForNode = createDiagnosticForNode;
  12855. function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
  12856. var start = ts.skipTrivia(sourceFile.text, nodes.pos);
  12857. return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
  12858. }
  12859. ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
  12860. function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
  12861. var span = getErrorSpanForNode(sourceFile, node);
  12862. return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
  12863. }
  12864. ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
  12865. function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
  12866. var sourceFile = getSourceFileOfNode(node);
  12867. var span = getErrorSpanForNode(sourceFile, node);
  12868. return {
  12869. file: sourceFile,
  12870. start: span.start,
  12871. length: span.length,
  12872. code: messageChain.code,
  12873. category: messageChain.category,
  12874. messageText: messageChain.next ? messageChain : messageChain.messageText,
  12875. relatedInformation: relatedInformation
  12876. };
  12877. }
  12878. ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
  12879. function getSpanOfTokenAtPosition(sourceFile, pos) {
  12880. var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
  12881. scanner.scan();
  12882. var start = scanner.getTokenPos();
  12883. return ts.createTextSpanFromBounds(start, scanner.getTextPos());
  12884. }
  12885. ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
  12886. function getErrorSpanForArrowFunction(sourceFile, node) {
  12887. var pos = ts.skipTrivia(sourceFile.text, node.pos);
  12888. if (node.body && node.body.kind === 223 /* Block */) {
  12889. var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
  12890. var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
  12891. if (startLine < endLine) {
  12892. // The arrow function spans multiple lines,
  12893. // make the error span be the first line, inclusive.
  12894. return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
  12895. }
  12896. }
  12897. return ts.createTextSpanFromBounds(pos, node.end);
  12898. }
  12899. function getErrorSpanForNode(sourceFile, node) {
  12900. var errorNode = node;
  12901. switch (node.kind) {
  12902. case 290 /* SourceFile */:
  12903. var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
  12904. if (pos_1 === sourceFile.text.length) {
  12905. // file is empty - return span for the beginning of the file
  12906. return ts.createTextSpan(0, 0);
  12907. }
  12908. return getSpanOfTokenAtPosition(sourceFile, pos_1);
  12909. // This list is a work in progress. Add missing node kinds to improve their error
  12910. // spans.
  12911. case 242 /* VariableDeclaration */:
  12912. case 191 /* BindingElement */:
  12913. case 245 /* ClassDeclaration */:
  12914. case 214 /* ClassExpression */:
  12915. case 246 /* InterfaceDeclaration */:
  12916. case 249 /* ModuleDeclaration */:
  12917. case 248 /* EnumDeclaration */:
  12918. case 284 /* EnumMember */:
  12919. case 244 /* FunctionDeclaration */:
  12920. case 201 /* FunctionExpression */:
  12921. case 161 /* MethodDeclaration */:
  12922. case 163 /* GetAccessor */:
  12923. case 164 /* SetAccessor */:
  12924. case 247 /* TypeAliasDeclaration */:
  12925. case 159 /* PropertyDeclaration */:
  12926. case 158 /* PropertySignature */:
  12927. errorNode = node.name;
  12928. break;
  12929. case 202 /* ArrowFunction */:
  12930. return getErrorSpanForArrowFunction(sourceFile, node);
  12931. case 277 /* CaseClause */:
  12932. case 278 /* DefaultClause */:
  12933. var start = ts.skipTrivia(sourceFile.text, node.pos);
  12934. var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
  12935. return ts.createTextSpanFromBounds(start, end);
  12936. }
  12937. if (errorNode === undefined) {
  12938. // If we don't have a better node, then just set the error on the first token of
  12939. // construct.
  12940. return getSpanOfTokenAtPosition(sourceFile, node.pos);
  12941. }
  12942. ts.Debug.assert(!ts.isJSDoc(errorNode));
  12943. var isMissing = nodeIsMissing(errorNode);
  12944. var pos = isMissing || ts.isJsxText(node)
  12945. ? errorNode.pos
  12946. : ts.skipTrivia(sourceFile.text, errorNode.pos);
  12947. // These asserts should all be satisfied for a properly constructed `errorNode`.
  12948. if (isMissing) {
  12949. ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
  12950. ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
  12951. }
  12952. else {
  12953. ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
  12954. ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
  12955. }
  12956. return ts.createTextSpanFromBounds(pos, errorNode.end);
  12957. }
  12958. ts.getErrorSpanForNode = getErrorSpanForNode;
  12959. function isExternalOrCommonJsModule(file) {
  12960. return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
  12961. }
  12962. ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
  12963. function isJsonSourceFile(file) {
  12964. return file.scriptKind === 6 /* JSON */;
  12965. }
  12966. ts.isJsonSourceFile = isJsonSourceFile;
  12967. function isEnumConst(node) {
  12968. return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
  12969. }
  12970. ts.isEnumConst = isEnumConst;
  12971. function isDeclarationReadonly(declaration) {
  12972. return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
  12973. }
  12974. ts.isDeclarationReadonly = isDeclarationReadonly;
  12975. function isVarConst(node) {
  12976. return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
  12977. }
  12978. ts.isVarConst = isVarConst;
  12979. function isLet(node) {
  12980. return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
  12981. }
  12982. ts.isLet = isLet;
  12983. function isSuperCall(n) {
  12984. return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
  12985. }
  12986. ts.isSuperCall = isSuperCall;
  12987. function isImportCall(n) {
  12988. return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
  12989. }
  12990. ts.isImportCall = isImportCall;
  12991. function isImportMeta(n) {
  12992. return ts.isMetaProperty(n)
  12993. && n.keywordToken === 96 /* ImportKeyword */
  12994. && n.name.escapedText === "meta";
  12995. }
  12996. ts.isImportMeta = isImportMeta;
  12997. function isLiteralImportTypeNode(n) {
  12998. return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
  12999. }
  13000. ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
  13001. function isPrologueDirective(node) {
  13002. return node.kind === 226 /* ExpressionStatement */
  13003. && node.expression.kind === 10 /* StringLiteral */;
  13004. }
  13005. ts.isPrologueDirective = isPrologueDirective;
  13006. function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
  13007. return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
  13008. }
  13009. ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
  13010. function getJSDocCommentRanges(node, text) {
  13011. var commentRanges = (node.kind === 156 /* Parameter */ ||
  13012. node.kind === 155 /* TypeParameter */ ||
  13013. node.kind === 201 /* FunctionExpression */ ||
  13014. node.kind === 202 /* ArrowFunction */ ||
  13015. node.kind === 200 /* ParenthesizedExpression */) ?
  13016. ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
  13017. ts.getLeadingCommentRanges(text, node.pos);
  13018. // True if the comment starts with '/**' but not if it is '/**/'
  13019. return ts.filter(commentRanges, function (comment) {
  13020. return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
  13021. text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
  13022. text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
  13023. });
  13024. }
  13025. ts.getJSDocCommentRanges = getJSDocCommentRanges;
  13026. ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
  13027. var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
  13028. ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
  13029. var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
  13030. function isPartOfTypeNode(node) {
  13031. if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
  13032. return true;
  13033. }
  13034. switch (node.kind) {
  13035. case 125 /* AnyKeyword */:
  13036. case 148 /* UnknownKeyword */:
  13037. case 140 /* NumberKeyword */:
  13038. case 151 /* BigIntKeyword */:
  13039. case 143 /* StringKeyword */:
  13040. case 128 /* BooleanKeyword */:
  13041. case 144 /* SymbolKeyword */:
  13042. case 141 /* ObjectKeyword */:
  13043. case 146 /* UndefinedKeyword */:
  13044. case 137 /* NeverKeyword */:
  13045. return true;
  13046. case 110 /* VoidKeyword */:
  13047. return node.parent.kind !== 205 /* VoidExpression */;
  13048. case 216 /* ExpressionWithTypeArguments */:
  13049. return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
  13050. case 155 /* TypeParameter */:
  13051. return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
  13052. // Identifiers and qualified names may be type nodes, depending on their context. Climb
  13053. // above them to find the lowest container
  13054. case 75 /* Identifier */:
  13055. // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
  13056. if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
  13057. node = node.parent;
  13058. }
  13059. else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
  13060. node = node.parent;
  13061. }
  13062. // At this point, node is either a qualified name or an identifier
  13063. ts.Debug.assert(node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */ || node.kind === 194 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
  13064. // falls through
  13065. case 153 /* QualifiedName */:
  13066. case 194 /* PropertyAccessExpression */:
  13067. case 104 /* ThisKeyword */: {
  13068. var parent = node.parent;
  13069. if (parent.kind === 172 /* TypeQuery */) {
  13070. return false;
  13071. }
  13072. if (parent.kind === 188 /* ImportType */) {
  13073. return !parent.isTypeOf;
  13074. }
  13075. // Do not recursively call isPartOfTypeNode on the parent. In the example:
  13076. //
  13077. // let a: A.B.C;
  13078. //
  13079. // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
  13080. // Only C and A.B.C are type nodes.
  13081. if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
  13082. return true;
  13083. }
  13084. switch (parent.kind) {
  13085. case 216 /* ExpressionWithTypeArguments */:
  13086. return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
  13087. case 155 /* TypeParameter */:
  13088. return node === parent.constraint;
  13089. case 320 /* JSDocTemplateTag */:
  13090. return node === parent.constraint;
  13091. case 159 /* PropertyDeclaration */:
  13092. case 158 /* PropertySignature */:
  13093. case 156 /* Parameter */:
  13094. case 242 /* VariableDeclaration */:
  13095. return node === parent.type;
  13096. case 244 /* FunctionDeclaration */:
  13097. case 201 /* FunctionExpression */:
  13098. case 202 /* ArrowFunction */:
  13099. case 162 /* Constructor */:
  13100. case 161 /* MethodDeclaration */:
  13101. case 160 /* MethodSignature */:
  13102. case 163 /* GetAccessor */:
  13103. case 164 /* SetAccessor */:
  13104. return node === parent.type;
  13105. case 165 /* CallSignature */:
  13106. case 166 /* ConstructSignature */:
  13107. case 167 /* IndexSignature */:
  13108. return node === parent.type;
  13109. case 199 /* TypeAssertionExpression */:
  13110. return node === parent.type;
  13111. case 196 /* CallExpression */:
  13112. case 197 /* NewExpression */:
  13113. return ts.contains(parent.typeArguments, node);
  13114. case 198 /* TaggedTemplateExpression */:
  13115. // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
  13116. return false;
  13117. }
  13118. }
  13119. }
  13120. return false;
  13121. }
  13122. ts.isPartOfTypeNode = isPartOfTypeNode;
  13123. function isChildOfNodeWithKind(node, kind) {
  13124. while (node) {
  13125. if (node.kind === kind) {
  13126. return true;
  13127. }
  13128. node = node.parent;
  13129. }
  13130. return false;
  13131. }
  13132. ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
  13133. // Warning: This has the same semantics as the forEach family of functions,
  13134. // in that traversal terminates in the event that 'visitor' supplies a truthy value.
  13135. function forEachReturnStatement(body, visitor) {
  13136. return traverse(body);
  13137. function traverse(node) {
  13138. switch (node.kind) {
  13139. case 235 /* ReturnStatement */:
  13140. return visitor(node);
  13141. case 251 /* CaseBlock */:
  13142. case 223 /* Block */:
  13143. case 227 /* IfStatement */:
  13144. case 228 /* DoStatement */:
  13145. case 229 /* WhileStatement */:
  13146. case 230 /* ForStatement */:
  13147. case 231 /* ForInStatement */:
  13148. case 232 /* ForOfStatement */:
  13149. case 236 /* WithStatement */:
  13150. case 237 /* SwitchStatement */:
  13151. case 277 /* CaseClause */:
  13152. case 278 /* DefaultClause */:
  13153. case 238 /* LabeledStatement */:
  13154. case 240 /* TryStatement */:
  13155. case 280 /* CatchClause */:
  13156. return ts.forEachChild(node, traverse);
  13157. }
  13158. }
  13159. }
  13160. ts.forEachReturnStatement = forEachReturnStatement;
  13161. function forEachYieldExpression(body, visitor) {
  13162. return traverse(body);
  13163. function traverse(node) {
  13164. switch (node.kind) {
  13165. case 212 /* YieldExpression */:
  13166. visitor(node);
  13167. var operand = node.expression;
  13168. if (operand) {
  13169. traverse(operand);
  13170. }
  13171. return;
  13172. case 248 /* EnumDeclaration */:
  13173. case 246 /* InterfaceDeclaration */:
  13174. case 249 /* ModuleDeclaration */:
  13175. case 247 /* TypeAliasDeclaration */:
  13176. // These are not allowed inside a generator now, but eventually they may be allowed
  13177. // as local types. Regardless, skip them to avoid the work.
  13178. return;
  13179. default:
  13180. if (ts.isFunctionLike(node)) {
  13181. if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
  13182. // Note that we will not include methods/accessors of a class because they would require
  13183. // first descending into the class. This is by design.
  13184. traverse(node.name.expression);
  13185. return;
  13186. }
  13187. }
  13188. else if (!isPartOfTypeNode(node)) {
  13189. // This is the general case, which should include mostly expressions and statements.
  13190. // Also includes NodeArrays.
  13191. ts.forEachChild(node, traverse);
  13192. }
  13193. }
  13194. }
  13195. }
  13196. ts.forEachYieldExpression = forEachYieldExpression;
  13197. /**
  13198. * Gets the most likely element type for a TypeNode. This is not an exhaustive test
  13199. * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
  13200. *
  13201. * @param node The type node.
  13202. */
  13203. function getRestParameterElementType(node) {
  13204. if (node && node.kind === 174 /* ArrayType */) {
  13205. return node.elementType;
  13206. }
  13207. else if (node && node.kind === 169 /* TypeReference */) {
  13208. return ts.singleOrUndefined(node.typeArguments);
  13209. }
  13210. else {
  13211. return undefined;
  13212. }
  13213. }
  13214. ts.getRestParameterElementType = getRestParameterElementType;
  13215. function getMembersOfDeclaration(node) {
  13216. switch (node.kind) {
  13217. case 246 /* InterfaceDeclaration */:
  13218. case 245 /* ClassDeclaration */:
  13219. case 214 /* ClassExpression */:
  13220. case 173 /* TypeLiteral */:
  13221. return node.members;
  13222. case 193 /* ObjectLiteralExpression */:
  13223. return node.properties;
  13224. }
  13225. }
  13226. ts.getMembersOfDeclaration = getMembersOfDeclaration;
  13227. function isVariableLike(node) {
  13228. if (node) {
  13229. switch (node.kind) {
  13230. case 191 /* BindingElement */:
  13231. case 284 /* EnumMember */:
  13232. case 156 /* Parameter */:
  13233. case 281 /* PropertyAssignment */:
  13234. case 159 /* PropertyDeclaration */:
  13235. case 158 /* PropertySignature */:
  13236. case 282 /* ShorthandPropertyAssignment */:
  13237. case 242 /* VariableDeclaration */:
  13238. return true;
  13239. }
  13240. }
  13241. return false;
  13242. }
  13243. ts.isVariableLike = isVariableLike;
  13244. function isVariableLikeOrAccessor(node) {
  13245. return isVariableLike(node) || ts.isAccessor(node);
  13246. }
  13247. ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
  13248. function isVariableDeclarationInVariableStatement(node) {
  13249. return node.parent.kind === 243 /* VariableDeclarationList */
  13250. && node.parent.parent.kind === 225 /* VariableStatement */;
  13251. }
  13252. ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
  13253. function isValidESSymbolDeclaration(node) {
  13254. return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
  13255. ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
  13256. ts.isPropertySignature(node) && hasReadonlyModifier(node);
  13257. }
  13258. ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
  13259. function introducesArgumentsExoticObject(node) {
  13260. switch (node.kind) {
  13261. case 161 /* MethodDeclaration */:
  13262. case 160 /* MethodSignature */:
  13263. case 162 /* Constructor */:
  13264. case 163 /* GetAccessor */:
  13265. case 164 /* SetAccessor */:
  13266. case 244 /* FunctionDeclaration */:
  13267. case 201 /* FunctionExpression */:
  13268. return true;
  13269. }
  13270. return false;
  13271. }
  13272. ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
  13273. function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
  13274. while (true) {
  13275. if (beforeUnwrapLabelCallback) {
  13276. beforeUnwrapLabelCallback(node);
  13277. }
  13278. if (node.statement.kind !== 238 /* LabeledStatement */) {
  13279. return node.statement;
  13280. }
  13281. node = node.statement;
  13282. }
  13283. }
  13284. ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
  13285. function isFunctionBlock(node) {
  13286. return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
  13287. }
  13288. ts.isFunctionBlock = isFunctionBlock;
  13289. function isObjectLiteralMethod(node) {
  13290. return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
  13291. }
  13292. ts.isObjectLiteralMethod = isObjectLiteralMethod;
  13293. function isObjectLiteralOrClassExpressionMethod(node) {
  13294. return node.kind === 161 /* MethodDeclaration */ &&
  13295. (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
  13296. node.parent.kind === 214 /* ClassExpression */);
  13297. }
  13298. ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
  13299. function isIdentifierTypePredicate(predicate) {
  13300. return predicate && predicate.kind === 1 /* Identifier */;
  13301. }
  13302. ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
  13303. function isThisTypePredicate(predicate) {
  13304. return predicate && predicate.kind === 0 /* This */;
  13305. }
  13306. ts.isThisTypePredicate = isThisTypePredicate;
  13307. function getPropertyAssignment(objectLiteral, key, key2) {
  13308. return objectLiteral.properties.filter(function (property) {
  13309. if (property.kind === 281 /* PropertyAssignment */) {
  13310. var propName = getTextOfPropertyName(property.name);
  13311. return key === propName || (!!key2 && key2 === propName);
  13312. }
  13313. return false;
  13314. });
  13315. }
  13316. ts.getPropertyAssignment = getPropertyAssignment;
  13317. function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
  13318. if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
  13319. var expression = tsConfigSourceFile.statements[0].expression;
  13320. return ts.tryCast(expression, ts.isObjectLiteralExpression);
  13321. }
  13322. }
  13323. ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
  13324. function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
  13325. return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
  13326. return ts.isArrayLiteralExpression(property.initializer) ?
  13327. ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
  13328. undefined;
  13329. });
  13330. }
  13331. ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
  13332. function getTsConfigPropArray(tsConfigSourceFile, propKey) {
  13333. var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
  13334. return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
  13335. }
  13336. ts.getTsConfigPropArray = getTsConfigPropArray;
  13337. function getContainingFunction(node) {
  13338. return findAncestor(node.parent, ts.isFunctionLike);
  13339. }
  13340. ts.getContainingFunction = getContainingFunction;
  13341. function getContainingFunctionDeclaration(node) {
  13342. return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
  13343. }
  13344. ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
  13345. function getContainingClass(node) {
  13346. return findAncestor(node.parent, ts.isClassLike);
  13347. }
  13348. ts.getContainingClass = getContainingClass;
  13349. function getThisContainer(node, includeArrowFunctions) {
  13350. ts.Debug.assert(node.kind !== 290 /* SourceFile */);
  13351. while (true) {
  13352. node = node.parent;
  13353. if (!node) {
  13354. return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
  13355. }
  13356. switch (node.kind) {
  13357. case 154 /* ComputedPropertyName */:
  13358. // If the grandparent node is an object literal (as opposed to a class),
  13359. // then the computed property is not a 'this' container.
  13360. // A computed property name in a class needs to be a this container
  13361. // so that we can error on it.
  13362. if (ts.isClassLike(node.parent.parent)) {
  13363. return node;
  13364. }
  13365. // If this is a computed property, then the parent should not
  13366. // make it a this container. The parent might be a property
  13367. // in an object literal, like a method or accessor. But in order for
  13368. // such a parent to be a this container, the reference must be in
  13369. // the *body* of the container.
  13370. node = node.parent;
  13371. break;
  13372. case 157 /* Decorator */:
  13373. // Decorators are always applied outside of the body of a class or method.
  13374. if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
  13375. // If the decorator's parent is a Parameter, we resolve the this container from
  13376. // the grandparent class declaration.
  13377. node = node.parent.parent;
  13378. }
  13379. else if (ts.isClassElement(node.parent)) {
  13380. // If the decorator's parent is a class element, we resolve the 'this' container
  13381. // from the parent class declaration.
  13382. node = node.parent;
  13383. }
  13384. break;
  13385. case 202 /* ArrowFunction */:
  13386. if (!includeArrowFunctions) {
  13387. continue;
  13388. }
  13389. // falls through
  13390. case 244 /* FunctionDeclaration */:
  13391. case 201 /* FunctionExpression */:
  13392. case 249 /* ModuleDeclaration */:
  13393. case 159 /* PropertyDeclaration */:
  13394. case 158 /* PropertySignature */:
  13395. case 161 /* MethodDeclaration */:
  13396. case 160 /* MethodSignature */:
  13397. case 162 /* Constructor */:
  13398. case 163 /* GetAccessor */:
  13399. case 164 /* SetAccessor */:
  13400. case 165 /* CallSignature */:
  13401. case 166 /* ConstructSignature */:
  13402. case 167 /* IndexSignature */:
  13403. case 248 /* EnumDeclaration */:
  13404. case 290 /* SourceFile */:
  13405. return node;
  13406. }
  13407. }
  13408. }
  13409. ts.getThisContainer = getThisContainer;
  13410. function getNewTargetContainer(node) {
  13411. var container = getThisContainer(node, /*includeArrowFunctions*/ false);
  13412. if (container) {
  13413. switch (container.kind) {
  13414. case 162 /* Constructor */:
  13415. case 244 /* FunctionDeclaration */:
  13416. case 201 /* FunctionExpression */:
  13417. return container;
  13418. }
  13419. }
  13420. return undefined;
  13421. }
  13422. ts.getNewTargetContainer = getNewTargetContainer;
  13423. /**
  13424. * Given an super call/property node, returns the closest node where
  13425. * - a super call/property access is legal in the node and not legal in the parent node the node.
  13426. * i.e. super call is legal in constructor but not legal in the class body.
  13427. * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
  13428. * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
  13429. * i.e. super property access is illegal in function declaration but can be legal in the statement list
  13430. */
  13431. function getSuperContainer(node, stopOnFunctions) {
  13432. while (true) {
  13433. node = node.parent;
  13434. if (!node) {
  13435. return node;
  13436. }
  13437. switch (node.kind) {
  13438. case 154 /* ComputedPropertyName */:
  13439. node = node.parent;
  13440. break;
  13441. case 244 /* FunctionDeclaration */:
  13442. case 201 /* FunctionExpression */:
  13443. case 202 /* ArrowFunction */:
  13444. if (!stopOnFunctions) {
  13445. continue;
  13446. }
  13447. // falls through
  13448. case 159 /* PropertyDeclaration */:
  13449. case 158 /* PropertySignature */:
  13450. case 161 /* MethodDeclaration */:
  13451. case 160 /* MethodSignature */:
  13452. case 162 /* Constructor */:
  13453. case 163 /* GetAccessor */:
  13454. case 164 /* SetAccessor */:
  13455. return node;
  13456. case 157 /* Decorator */:
  13457. // Decorators are always applied outside of the body of a class or method.
  13458. if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
  13459. // If the decorator's parent is a Parameter, we resolve the this container from
  13460. // the grandparent class declaration.
  13461. node = node.parent.parent;
  13462. }
  13463. else if (ts.isClassElement(node.parent)) {
  13464. // If the decorator's parent is a class element, we resolve the 'this' container
  13465. // from the parent class declaration.
  13466. node = node.parent;
  13467. }
  13468. break;
  13469. }
  13470. }
  13471. }
  13472. ts.getSuperContainer = getSuperContainer;
  13473. function getImmediatelyInvokedFunctionExpression(func) {
  13474. if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
  13475. var prev = func;
  13476. var parent = func.parent;
  13477. while (parent.kind === 200 /* ParenthesizedExpression */) {
  13478. prev = parent;
  13479. parent = parent.parent;
  13480. }
  13481. if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
  13482. return parent;
  13483. }
  13484. }
  13485. }
  13486. ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
  13487. function isSuperOrSuperProperty(node) {
  13488. return node.kind === 102 /* SuperKeyword */
  13489. || isSuperProperty(node);
  13490. }
  13491. ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
  13492. /**
  13493. * Determines whether a node is a property or element access expression for `super`.
  13494. */
  13495. function isSuperProperty(node) {
  13496. var kind = node.kind;
  13497. return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
  13498. && node.expression.kind === 102 /* SuperKeyword */;
  13499. }
  13500. ts.isSuperProperty = isSuperProperty;
  13501. /**
  13502. * Determines whether a node is a property or element access expression for `this`.
  13503. */
  13504. function isThisProperty(node) {
  13505. var kind = node.kind;
  13506. return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
  13507. && node.expression.kind === 104 /* ThisKeyword */;
  13508. }
  13509. ts.isThisProperty = isThisProperty;
  13510. function getEntityNameFromTypeNode(node) {
  13511. switch (node.kind) {
  13512. case 169 /* TypeReference */:
  13513. return node.typeName;
  13514. case 216 /* ExpressionWithTypeArguments */:
  13515. return isEntityNameExpression(node.expression)
  13516. ? node.expression
  13517. : undefined;
  13518. case 75 /* Identifier */:
  13519. case 153 /* QualifiedName */:
  13520. return node;
  13521. }
  13522. return undefined;
  13523. }
  13524. ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
  13525. function getInvokedExpression(node) {
  13526. switch (node.kind) {
  13527. case 198 /* TaggedTemplateExpression */:
  13528. return node.tag;
  13529. case 268 /* JsxOpeningElement */:
  13530. case 267 /* JsxSelfClosingElement */:
  13531. return node.tagName;
  13532. default:
  13533. return node.expression;
  13534. }
  13535. }
  13536. ts.getInvokedExpression = getInvokedExpression;
  13537. function nodeCanBeDecorated(node, parent, grandparent) {
  13538. // private names cannot be used with decorators yet
  13539. if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
  13540. return false;
  13541. }
  13542. switch (node.kind) {
  13543. case 245 /* ClassDeclaration */:
  13544. // classes are valid targets
  13545. return true;
  13546. case 159 /* PropertyDeclaration */:
  13547. // property declarations are valid if their parent is a class declaration.
  13548. return parent.kind === 245 /* ClassDeclaration */;
  13549. case 163 /* GetAccessor */:
  13550. case 164 /* SetAccessor */:
  13551. case 161 /* MethodDeclaration */:
  13552. // if this method has a body and its parent is a class declaration, this is a valid target.
  13553. return node.body !== undefined
  13554. && parent.kind === 245 /* ClassDeclaration */;
  13555. case 156 /* Parameter */:
  13556. // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
  13557. return parent.body !== undefined
  13558. && (parent.kind === 162 /* Constructor */
  13559. || parent.kind === 161 /* MethodDeclaration */
  13560. || parent.kind === 164 /* SetAccessor */)
  13561. && grandparent.kind === 245 /* ClassDeclaration */;
  13562. }
  13563. return false;
  13564. }
  13565. ts.nodeCanBeDecorated = nodeCanBeDecorated;
  13566. function nodeIsDecorated(node, parent, grandparent) {
  13567. return node.decorators !== undefined
  13568. && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
  13569. }
  13570. ts.nodeIsDecorated = nodeIsDecorated;
  13571. function nodeOrChildIsDecorated(node, parent, grandparent) {
  13572. return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
  13573. }
  13574. ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
  13575. function childIsDecorated(node, parent) {
  13576. switch (node.kind) {
  13577. case 245 /* ClassDeclaration */:
  13578. return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
  13579. case 161 /* MethodDeclaration */:
  13580. case 164 /* SetAccessor */:
  13581. return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
  13582. default:
  13583. return false;
  13584. }
  13585. }
  13586. ts.childIsDecorated = childIsDecorated;
  13587. function isJSXTagName(node) {
  13588. var parent = node.parent;
  13589. if (parent.kind === 268 /* JsxOpeningElement */ ||
  13590. parent.kind === 267 /* JsxSelfClosingElement */ ||
  13591. parent.kind === 269 /* JsxClosingElement */) {
  13592. return parent.tagName === node;
  13593. }
  13594. return false;
  13595. }
  13596. ts.isJSXTagName = isJSXTagName;
  13597. function isExpressionNode(node) {
  13598. switch (node.kind) {
  13599. case 102 /* SuperKeyword */:
  13600. case 100 /* NullKeyword */:
  13601. case 106 /* TrueKeyword */:
  13602. case 91 /* FalseKeyword */:
  13603. case 13 /* RegularExpressionLiteral */:
  13604. case 192 /* ArrayLiteralExpression */:
  13605. case 193 /* ObjectLiteralExpression */:
  13606. case 194 /* PropertyAccessExpression */:
  13607. case 195 /* ElementAccessExpression */:
  13608. case 196 /* CallExpression */:
  13609. case 197 /* NewExpression */:
  13610. case 198 /* TaggedTemplateExpression */:
  13611. case 217 /* AsExpression */:
  13612. case 199 /* TypeAssertionExpression */:
  13613. case 218 /* NonNullExpression */:
  13614. case 200 /* ParenthesizedExpression */:
  13615. case 201 /* FunctionExpression */:
  13616. case 214 /* ClassExpression */:
  13617. case 202 /* ArrowFunction */:
  13618. case 205 /* VoidExpression */:
  13619. case 203 /* DeleteExpression */:
  13620. case 204 /* TypeOfExpression */:
  13621. case 207 /* PrefixUnaryExpression */:
  13622. case 208 /* PostfixUnaryExpression */:
  13623. case 209 /* BinaryExpression */:
  13624. case 210 /* ConditionalExpression */:
  13625. case 213 /* SpreadElement */:
  13626. case 211 /* TemplateExpression */:
  13627. case 215 /* OmittedExpression */:
  13628. case 266 /* JsxElement */:
  13629. case 267 /* JsxSelfClosingElement */:
  13630. case 270 /* JsxFragment */:
  13631. case 212 /* YieldExpression */:
  13632. case 206 /* AwaitExpression */:
  13633. case 219 /* MetaProperty */:
  13634. return true;
  13635. case 153 /* QualifiedName */:
  13636. while (node.parent.kind === 153 /* QualifiedName */) {
  13637. node = node.parent;
  13638. }
  13639. return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
  13640. case 75 /* Identifier */:
  13641. if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
  13642. return true;
  13643. }
  13644. // falls through
  13645. case 8 /* NumericLiteral */:
  13646. case 9 /* BigIntLiteral */:
  13647. case 10 /* StringLiteral */:
  13648. case 14 /* NoSubstitutionTemplateLiteral */:
  13649. case 104 /* ThisKeyword */:
  13650. return isInExpressionContext(node);
  13651. default:
  13652. return false;
  13653. }
  13654. }
  13655. ts.isExpressionNode = isExpressionNode;
  13656. function isInExpressionContext(node) {
  13657. var parent = node.parent;
  13658. switch (parent.kind) {
  13659. case 242 /* VariableDeclaration */:
  13660. case 156 /* Parameter */:
  13661. case 159 /* PropertyDeclaration */:
  13662. case 158 /* PropertySignature */:
  13663. case 284 /* EnumMember */:
  13664. case 281 /* PropertyAssignment */:
  13665. case 191 /* BindingElement */:
  13666. return parent.initializer === node;
  13667. case 226 /* ExpressionStatement */:
  13668. case 227 /* IfStatement */:
  13669. case 228 /* DoStatement */:
  13670. case 229 /* WhileStatement */:
  13671. case 235 /* ReturnStatement */:
  13672. case 236 /* WithStatement */:
  13673. case 237 /* SwitchStatement */:
  13674. case 277 /* CaseClause */:
  13675. case 239 /* ThrowStatement */:
  13676. return parent.expression === node;
  13677. case 230 /* ForStatement */:
  13678. var forStatement = parent;
  13679. return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
  13680. forStatement.condition === node ||
  13681. forStatement.incrementor === node;
  13682. case 231 /* ForInStatement */:
  13683. case 232 /* ForOfStatement */:
  13684. var forInStatement = parent;
  13685. return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
  13686. forInStatement.expression === node;
  13687. case 199 /* TypeAssertionExpression */:
  13688. case 217 /* AsExpression */:
  13689. return node === parent.expression;
  13690. case 221 /* TemplateSpan */:
  13691. return node === parent.expression;
  13692. case 154 /* ComputedPropertyName */:
  13693. return node === parent.expression;
  13694. case 157 /* Decorator */:
  13695. case 276 /* JsxExpression */:
  13696. case 275 /* JsxSpreadAttribute */:
  13697. case 283 /* SpreadAssignment */:
  13698. return true;
  13699. case 216 /* ExpressionWithTypeArguments */:
  13700. return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
  13701. case 282 /* ShorthandPropertyAssignment */:
  13702. return parent.objectAssignmentInitializer === node;
  13703. default:
  13704. return isExpressionNode(parent);
  13705. }
  13706. }
  13707. ts.isInExpressionContext = isInExpressionContext;
  13708. function isPartOfTypeQuery(node) {
  13709. while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
  13710. node = node.parent;
  13711. }
  13712. return node.kind === 172 /* TypeQuery */;
  13713. }
  13714. ts.isPartOfTypeQuery = isPartOfTypeQuery;
  13715. function isExternalModuleImportEqualsDeclaration(node) {
  13716. return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
  13717. }
  13718. ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
  13719. function getExternalModuleImportEqualsDeclarationExpression(node) {
  13720. ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
  13721. return node.moduleReference.expression;
  13722. }
  13723. ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
  13724. function isInternalModuleImportEqualsDeclaration(node) {
  13725. return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
  13726. }
  13727. ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
  13728. function isSourceFileJS(file) {
  13729. return isInJSFile(file);
  13730. }
  13731. ts.isSourceFileJS = isSourceFileJS;
  13732. function isSourceFileNotJS(file) {
  13733. return !isInJSFile(file);
  13734. }
  13735. ts.isSourceFileNotJS = isSourceFileNotJS;
  13736. function isInJSFile(node) {
  13737. return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
  13738. }
  13739. ts.isInJSFile = isInJSFile;
  13740. function isInJsonFile(node) {
  13741. return !!node && !!(node.flags & 33554432 /* JsonFile */);
  13742. }
  13743. ts.isInJsonFile = isInJsonFile;
  13744. function isSourceFileNotJson(file) {
  13745. return !isJsonSourceFile(file);
  13746. }
  13747. ts.isSourceFileNotJson = isSourceFileNotJson;
  13748. function isInJSDoc(node) {
  13749. return !!node && !!(node.flags & 4194304 /* JSDoc */);
  13750. }
  13751. ts.isInJSDoc = isInJSDoc;
  13752. function isJSDocIndexSignature(node) {
  13753. return ts.isTypeReferenceNode(node) &&
  13754. ts.isIdentifier(node.typeName) &&
  13755. node.typeName.escapedText === "Object" &&
  13756. node.typeArguments && node.typeArguments.length === 2 &&
  13757. (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
  13758. }
  13759. ts.isJSDocIndexSignature = isJSDocIndexSignature;
  13760. function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
  13761. if (callExpression.kind !== 196 /* CallExpression */) {
  13762. return false;
  13763. }
  13764. var _a = callExpression, expression = _a.expression, args = _a.arguments;
  13765. if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
  13766. return false;
  13767. }
  13768. if (args.length !== 1) {
  13769. return false;
  13770. }
  13771. var arg = args[0];
  13772. return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
  13773. }
  13774. ts.isRequireCall = isRequireCall;
  13775. function isSingleOrDoubleQuote(charCode) {
  13776. return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
  13777. }
  13778. ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
  13779. function isStringDoubleQuoted(str, sourceFile) {
  13780. return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
  13781. }
  13782. ts.isStringDoubleQuoted = isStringDoubleQuoted;
  13783. function getDeclarationOfExpando(node) {
  13784. if (!node.parent) {
  13785. return undefined;
  13786. }
  13787. var name;
  13788. var decl;
  13789. if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
  13790. if (!isInJSFile(node) && !isVarConst(node.parent)) {
  13791. return undefined;
  13792. }
  13793. name = node.parent.name;
  13794. decl = node.parent;
  13795. }
  13796. else if (ts.isBinaryExpression(node.parent)) {
  13797. var parentNode = node.parent;
  13798. var parentNodeOperator = node.parent.operatorToken.kind;
  13799. if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
  13800. name = parentNode.left;
  13801. decl = name;
  13802. }
  13803. else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
  13804. if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
  13805. name = parentNode.parent.name;
  13806. decl = parentNode.parent;
  13807. }
  13808. else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
  13809. name = parentNode.parent.left;
  13810. decl = name;
  13811. }
  13812. if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
  13813. return undefined;
  13814. }
  13815. }
  13816. }
  13817. if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
  13818. return undefined;
  13819. }
  13820. return decl;
  13821. }
  13822. ts.getDeclarationOfExpando = getDeclarationOfExpando;
  13823. function isAssignmentDeclaration(decl) {
  13824. return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
  13825. }
  13826. ts.isAssignmentDeclaration = isAssignmentDeclaration;
  13827. /** Get the initializer, taking into account defaulted Javascript initializers */
  13828. function getEffectiveInitializer(node) {
  13829. if (isInJSFile(node) && node.initializer &&
  13830. ts.isBinaryExpression(node.initializer) &&
  13831. (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
  13832. node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
  13833. return node.initializer.right;
  13834. }
  13835. return node.initializer;
  13836. }
  13837. ts.getEffectiveInitializer = getEffectiveInitializer;
  13838. /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
  13839. function getDeclaredExpandoInitializer(node) {
  13840. var init = getEffectiveInitializer(node);
  13841. return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
  13842. }
  13843. ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
  13844. function hasExpandoValueProperty(node, isPrototypeAssignment) {
  13845. return ts.forEach(node.properties, function (p) {
  13846. return ts.isPropertyAssignment(p) &&
  13847. ts.isIdentifier(p.name) &&
  13848. p.name.escapedText === "value" &&
  13849. p.initializer &&
  13850. getExpandoInitializer(p.initializer, isPrototypeAssignment);
  13851. });
  13852. }
  13853. /**
  13854. * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
  13855. * We treat the right hand side of assignments with container-like initalizers as declarations.
  13856. */
  13857. function getAssignedExpandoInitializer(node) {
  13858. if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
  13859. var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
  13860. return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
  13861. getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
  13862. }
  13863. if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
  13864. var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
  13865. if (result) {
  13866. return result;
  13867. }
  13868. }
  13869. }
  13870. ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
  13871. /**
  13872. * Recognized expando initializers are:
  13873. * 1. (function() {})() -- IIFEs
  13874. * 2. function() { } -- Function expressions
  13875. * 3. class { } -- Class expressions
  13876. * 4. {} -- Empty object literals
  13877. * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
  13878. *
  13879. * This function returns the provided initializer, or undefined if it is not valid.
  13880. */
  13881. function getExpandoInitializer(initializer, isPrototypeAssignment) {
  13882. if (ts.isCallExpression(initializer)) {
  13883. var e = skipParentheses(initializer.expression);
  13884. return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
  13885. }
  13886. if (initializer.kind === 201 /* FunctionExpression */ ||
  13887. initializer.kind === 214 /* ClassExpression */ ||
  13888. initializer.kind === 202 /* ArrowFunction */) {
  13889. return initializer;
  13890. }
  13891. if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
  13892. return initializer;
  13893. }
  13894. }
  13895. ts.getExpandoInitializer = getExpandoInitializer;
  13896. /**
  13897. * A defaulted expando initializer matches the pattern
  13898. * `Lhs = Lhs || ExpandoInitializer`
  13899. * or `var Lhs = Lhs || ExpandoInitializer`
  13900. *
  13901. * The second Lhs is required to be the same as the first except that it may be prefixed with
  13902. * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
  13903. */
  13904. function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
  13905. var e = ts.isBinaryExpression(initializer)
  13906. && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
  13907. && getExpandoInitializer(initializer.right, isPrototypeAssignment);
  13908. if (e && isSameEntityName(name, initializer.left)) {
  13909. return e;
  13910. }
  13911. }
  13912. function isDefaultedExpandoInitializer(node) {
  13913. var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
  13914. ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
  13915. undefined;
  13916. return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
  13917. }
  13918. ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
  13919. /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
  13920. function getNameOfExpando(node) {
  13921. if (ts.isBinaryExpression(node.parent)) {
  13922. var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
  13923. if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
  13924. return parent.left;
  13925. }
  13926. }
  13927. else if (ts.isVariableDeclaration(node.parent)) {
  13928. return node.parent.name;
  13929. }
  13930. }
  13931. ts.getNameOfExpando = getNameOfExpando;
  13932. /**
  13933. * Is the 'declared' name the same as the one in the initializer?
  13934. * @return true for identical entity names, as well as ones where the initializer is prefixed with
  13935. * 'window', 'self' or 'global'. For example:
  13936. *
  13937. * var my = my || {}
  13938. * var min = window.min || {}
  13939. * my.app = self.my.app || class { }
  13940. */
  13941. function isSameEntityName(name, initializer) {
  13942. if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
  13943. return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
  13944. }
  13945. if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
  13946. (initializer.expression.kind === 104 /* ThisKeyword */ ||
  13947. ts.isIdentifier(initializer.expression) &&
  13948. (initializer.expression.escapedText === "window" ||
  13949. initializer.expression.escapedText === "self" ||
  13950. initializer.expression.escapedText === "global"))) {
  13951. var nameOrArgument = getNameOrArgument(initializer);
  13952. if (ts.isPrivateIdentifier(nameOrArgument)) {
  13953. ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
  13954. }
  13955. return isSameEntityName(name, nameOrArgument);
  13956. }
  13957. if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
  13958. return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
  13959. && isSameEntityName(name.expression, initializer.expression);
  13960. }
  13961. return false;
  13962. }
  13963. function getRightMostAssignedExpression(node) {
  13964. while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
  13965. node = node.right;
  13966. }
  13967. return node;
  13968. }
  13969. ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
  13970. function isExportsIdentifier(node) {
  13971. return ts.isIdentifier(node) && node.escapedText === "exports";
  13972. }
  13973. ts.isExportsIdentifier = isExportsIdentifier;
  13974. function isModuleExportsAccessExpression(node) {
  13975. return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
  13976. && ts.isIdentifier(node.expression)
  13977. && node.expression.escapedText === "module"
  13978. && getElementOrPropertyAccessName(node) === "exports";
  13979. }
  13980. ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
  13981. /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
  13982. /// assignments we treat as special in the binder
  13983. function getAssignmentDeclarationKind(expr) {
  13984. var special = getAssignmentDeclarationKindWorker(expr);
  13985. return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
  13986. }
  13987. ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
  13988. function isBindableObjectDefinePropertyCall(expr) {
  13989. return ts.length(expr.arguments) === 3 &&
  13990. ts.isPropertyAccessExpression(expr.expression) &&
  13991. ts.isIdentifier(expr.expression.expression) &&
  13992. ts.idText(expr.expression.expression) === "Object" &&
  13993. ts.idText(expr.expression.name) === "defineProperty" &&
  13994. isStringOrNumericLiteralLike(expr.arguments[1]) &&
  13995. isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
  13996. }
  13997. ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
  13998. /** x.y OR x[0] */
  13999. function isLiteralLikeAccess(node) {
  14000. return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
  14001. }
  14002. ts.isLiteralLikeAccess = isLiteralLikeAccess;
  14003. /** x[0] OR x['a'] OR x[Symbol.y] */
  14004. function isLiteralLikeElementAccess(node) {
  14005. return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
  14006. isWellKnownSymbolSyntactically(node.argumentExpression));
  14007. }
  14008. ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
  14009. /** Any series of property and element accesses. */
  14010. function isBindableStaticAccessExpression(node, excludeThisKeyword) {
  14011. return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
  14012. || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
  14013. }
  14014. ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
  14015. /** Any series of property and element accesses, ending in a literal element access */
  14016. function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
  14017. return isLiteralLikeElementAccess(node)
  14018. && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
  14019. isEntityNameExpression(node.expression) ||
  14020. isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
  14021. }
  14022. ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
  14023. function isBindableStaticNameExpression(node, excludeThisKeyword) {
  14024. return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
  14025. }
  14026. ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
  14027. function getNameOrArgument(expr) {
  14028. if (ts.isPropertyAccessExpression(expr)) {
  14029. return expr.name;
  14030. }
  14031. return expr.argumentExpression;
  14032. }
  14033. ts.getNameOrArgument = getNameOrArgument;
  14034. function getAssignmentDeclarationKindWorker(expr) {
  14035. if (ts.isCallExpression(expr)) {
  14036. if (!isBindableObjectDefinePropertyCall(expr)) {
  14037. return 0 /* None */;
  14038. }
  14039. var entityName = expr.arguments[0];
  14040. if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
  14041. return 8 /* ObjectDefinePropertyExports */;
  14042. }
  14043. if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
  14044. return 9 /* ObjectDefinePrototypeProperty */;
  14045. }
  14046. return 7 /* ObjectDefinePropertyValue */;
  14047. }
  14048. if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
  14049. return 0 /* None */;
  14050. }
  14051. if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
  14052. // F.prototype = { ... }
  14053. return 6 /* Prototype */;
  14054. }
  14055. return getAssignmentDeclarationPropertyAccessKind(expr.left);
  14056. }
  14057. /**
  14058. * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
  14059. * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
  14060. */
  14061. /* @internal */
  14062. function getElementOrPropertyAccessArgumentExpressionOrName(node) {
  14063. if (ts.isPropertyAccessExpression(node)) {
  14064. return node.name;
  14065. }
  14066. var arg = skipParentheses(node.argumentExpression);
  14067. if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
  14068. return arg;
  14069. }
  14070. return node;
  14071. }
  14072. ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
  14073. function getElementOrPropertyAccessName(node) {
  14074. var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
  14075. if (name) {
  14076. if (ts.isIdentifier(name)) {
  14077. return name.escapedText;
  14078. }
  14079. if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
  14080. return ts.escapeLeadingUnderscores(name.text);
  14081. }
  14082. }
  14083. if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
  14084. return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
  14085. }
  14086. return undefined;
  14087. }
  14088. ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
  14089. function getAssignmentDeclarationPropertyAccessKind(lhs) {
  14090. if (lhs.expression.kind === 104 /* ThisKeyword */) {
  14091. return 4 /* ThisProperty */;
  14092. }
  14093. else if (isModuleExportsAccessExpression(lhs)) {
  14094. // module.exports = expr
  14095. return 2 /* ModuleExports */;
  14096. }
  14097. else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
  14098. if (isPrototypeAccess(lhs.expression)) {
  14099. // F.G....prototype.x = expr
  14100. return 3 /* PrototypeProperty */;
  14101. }
  14102. var nextToLast = lhs;
  14103. while (!ts.isIdentifier(nextToLast.expression)) {
  14104. nextToLast = nextToLast.expression;
  14105. }
  14106. var id = nextToLast.expression;
  14107. if ((id.escapedText === "exports" ||
  14108. id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
  14109. // ExportsProperty does not support binding with computed names
  14110. isBindableStaticAccessExpression(lhs)) {
  14111. // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
  14112. return 1 /* ExportsProperty */;
  14113. }
  14114. if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 104 /* ThisKeyword */)) {
  14115. // F.G...x = expr
  14116. return 5 /* Property */;
  14117. }
  14118. }
  14119. return 0 /* None */;
  14120. }
  14121. ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
  14122. function getInitializerOfBinaryExpression(expr) {
  14123. while (ts.isBinaryExpression(expr.right)) {
  14124. expr = expr.right;
  14125. }
  14126. return expr.right;
  14127. }
  14128. ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
  14129. function isPrototypePropertyAssignment(node) {
  14130. return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
  14131. }
  14132. ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
  14133. function isSpecialPropertyDeclaration(expr) {
  14134. return isInJSFile(expr) &&
  14135. expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
  14136. (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
  14137. !!ts.getJSDocTypeTag(expr.parent);
  14138. }
  14139. ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
  14140. function isFunctionSymbol(symbol) {
  14141. if (!symbol || !symbol.valueDeclaration) {
  14142. return false;
  14143. }
  14144. var decl = symbol.valueDeclaration;
  14145. return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
  14146. }
  14147. ts.isFunctionSymbol = isFunctionSymbol;
  14148. function importFromModuleSpecifier(node) {
  14149. return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
  14150. }
  14151. ts.importFromModuleSpecifier = importFromModuleSpecifier;
  14152. function tryGetImportFromModuleSpecifier(node) {
  14153. switch (node.parent.kind) {
  14154. case 254 /* ImportDeclaration */:
  14155. case 260 /* ExportDeclaration */:
  14156. return node.parent;
  14157. case 265 /* ExternalModuleReference */:
  14158. return node.parent.parent;
  14159. case 196 /* CallExpression */:
  14160. return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
  14161. case 187 /* LiteralType */:
  14162. ts.Debug.assert(ts.isStringLiteral(node));
  14163. return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
  14164. default:
  14165. return undefined;
  14166. }
  14167. }
  14168. ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
  14169. function getExternalModuleName(node) {
  14170. switch (node.kind) {
  14171. case 254 /* ImportDeclaration */:
  14172. case 260 /* ExportDeclaration */:
  14173. return node.moduleSpecifier;
  14174. case 253 /* ImportEqualsDeclaration */:
  14175. return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
  14176. case 188 /* ImportType */:
  14177. return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
  14178. default:
  14179. return ts.Debug.assertNever(node);
  14180. }
  14181. }
  14182. ts.getExternalModuleName = getExternalModuleName;
  14183. function getNamespaceDeclarationNode(node) {
  14184. switch (node.kind) {
  14185. case 254 /* ImportDeclaration */:
  14186. return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
  14187. case 253 /* ImportEqualsDeclaration */:
  14188. return node;
  14189. case 260 /* ExportDeclaration */:
  14190. return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
  14191. default:
  14192. return ts.Debug.assertNever(node);
  14193. }
  14194. }
  14195. ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
  14196. function isDefaultImport(node) {
  14197. return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
  14198. }
  14199. ts.isDefaultImport = isDefaultImport;
  14200. function forEachImportClauseDeclaration(node, action) {
  14201. if (node.name) {
  14202. var result = action(node);
  14203. if (result)
  14204. return result;
  14205. }
  14206. if (node.namedBindings) {
  14207. var result = ts.isNamespaceImport(node.namedBindings)
  14208. ? action(node.namedBindings)
  14209. : ts.forEach(node.namedBindings.elements, action);
  14210. if (result)
  14211. return result;
  14212. }
  14213. }
  14214. ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
  14215. function hasQuestionToken(node) {
  14216. if (node) {
  14217. switch (node.kind) {
  14218. case 156 /* Parameter */:
  14219. case 161 /* MethodDeclaration */:
  14220. case 160 /* MethodSignature */:
  14221. case 282 /* ShorthandPropertyAssignment */:
  14222. case 281 /* PropertyAssignment */:
  14223. case 159 /* PropertyDeclaration */:
  14224. case 158 /* PropertySignature */:
  14225. return node.questionToken !== undefined;
  14226. }
  14227. }
  14228. return false;
  14229. }
  14230. ts.hasQuestionToken = hasQuestionToken;
  14231. function isJSDocConstructSignature(node) {
  14232. var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
  14233. var name = ts.tryCast(param && param.name, ts.isIdentifier);
  14234. return !!name && name.escapedText === "new";
  14235. }
  14236. ts.isJSDocConstructSignature = isJSDocConstructSignature;
  14237. function isJSDocTypeAlias(node) {
  14238. return node.kind === 321 /* JSDocTypedefTag */ || node.kind === 314 /* JSDocCallbackTag */ || node.kind === 315 /* JSDocEnumTag */;
  14239. }
  14240. ts.isJSDocTypeAlias = isJSDocTypeAlias;
  14241. function isTypeAlias(node) {
  14242. return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
  14243. }
  14244. ts.isTypeAlias = isTypeAlias;
  14245. function getSourceOfAssignment(node) {
  14246. return ts.isExpressionStatement(node) &&
  14247. ts.isBinaryExpression(node.expression) &&
  14248. node.expression.operatorToken.kind === 62 /* EqualsToken */
  14249. ? getRightMostAssignedExpression(node.expression)
  14250. : undefined;
  14251. }
  14252. function getSourceOfDefaultedAssignment(node) {
  14253. return ts.isExpressionStatement(node) &&
  14254. ts.isBinaryExpression(node.expression) &&
  14255. getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
  14256. ts.isBinaryExpression(node.expression.right) &&
  14257. (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
  14258. ? node.expression.right.right
  14259. : undefined;
  14260. }
  14261. function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
  14262. switch (node.kind) {
  14263. case 225 /* VariableStatement */:
  14264. var v = getSingleVariableOfVariableStatement(node);
  14265. return v && v.initializer;
  14266. case 159 /* PropertyDeclaration */:
  14267. return node.initializer;
  14268. case 281 /* PropertyAssignment */:
  14269. return node.initializer;
  14270. }
  14271. }
  14272. ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
  14273. function getSingleVariableOfVariableStatement(node) {
  14274. return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
  14275. }
  14276. function getNestedModuleDeclaration(node) {
  14277. return ts.isModuleDeclaration(node) &&
  14278. node.body &&
  14279. node.body.kind === 249 /* ModuleDeclaration */
  14280. ? node.body
  14281. : undefined;
  14282. }
  14283. function getJSDocCommentsAndTags(hostNode) {
  14284. var result;
  14285. // Pull parameter comments from declaring function as well
  14286. if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
  14287. result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
  14288. }
  14289. var node = hostNode;
  14290. while (node && node.parent) {
  14291. if (ts.hasJSDocNodes(node)) {
  14292. result = ts.append(result, ts.last(node.jsDoc));
  14293. }
  14294. if (node.kind === 156 /* Parameter */) {
  14295. result = ts.addRange(result, ts.getJSDocParameterTags(node));
  14296. break;
  14297. }
  14298. if (node.kind === 155 /* TypeParameter */) {
  14299. result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
  14300. break;
  14301. }
  14302. node = getNextJSDocCommentLocation(node);
  14303. }
  14304. return result || ts.emptyArray;
  14305. }
  14306. ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
  14307. function getNextJSDocCommentLocation(node) {
  14308. var parent = node.parent;
  14309. if (parent.kind === 281 /* PropertyAssignment */ ||
  14310. parent.kind === 259 /* ExportAssignment */ ||
  14311. parent.kind === 159 /* PropertyDeclaration */ ||
  14312. parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
  14313. getNestedModuleDeclaration(parent) ||
  14314. ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
  14315. return parent;
  14316. }
  14317. // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
  14318. // /**
  14319. // * @param {number} name
  14320. // * @returns {number}
  14321. // */
  14322. // var x = function(name) { return name.length; }
  14323. else if (parent.parent &&
  14324. (getSingleVariableOfVariableStatement(parent.parent) === node ||
  14325. ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
  14326. return parent.parent;
  14327. }
  14328. else if (parent.parent && parent.parent.parent &&
  14329. (getSingleVariableOfVariableStatement(parent.parent.parent) ||
  14330. getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
  14331. getSourceOfDefaultedAssignment(parent.parent.parent))) {
  14332. return parent.parent.parent;
  14333. }
  14334. }
  14335. /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
  14336. function getParameterSymbolFromJSDoc(node) {
  14337. if (node.symbol) {
  14338. return node.symbol;
  14339. }
  14340. if (!ts.isIdentifier(node.name)) {
  14341. return undefined;
  14342. }
  14343. var name = node.name.escapedText;
  14344. var decl = getHostSignatureFromJSDoc(node);
  14345. if (!decl) {
  14346. return undefined;
  14347. }
  14348. var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
  14349. return parameter && parameter.symbol;
  14350. }
  14351. ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
  14352. function getHostSignatureFromJSDoc(node) {
  14353. return getHostSignatureFromJSDocHost(getJSDocHost(node));
  14354. }
  14355. ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
  14356. function getHostSignatureFromJSDocHost(host) {
  14357. var decl = getSourceOfDefaultedAssignment(host) ||
  14358. getSourceOfAssignment(host) ||
  14359. getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
  14360. getSingleVariableOfVariableStatement(host) ||
  14361. getNestedModuleDeclaration(host) ||
  14362. host;
  14363. return decl && ts.isFunctionLike(decl) ? decl : undefined;
  14364. }
  14365. ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
  14366. function getJSDocHost(node) {
  14367. return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
  14368. }
  14369. ts.getJSDocHost = getJSDocHost;
  14370. function getTypeParameterFromJsDoc(node) {
  14371. var name = node.name.escapedText;
  14372. var typeParameters = node.parent.parent.parent.typeParameters;
  14373. return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
  14374. }
  14375. ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
  14376. function hasRestParameter(s) {
  14377. var last = ts.lastOrUndefined(s.parameters);
  14378. return !!last && isRestParameter(last);
  14379. }
  14380. ts.hasRestParameter = hasRestParameter;
  14381. function isRestParameter(node) {
  14382. var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
  14383. return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
  14384. }
  14385. ts.isRestParameter = isRestParameter;
  14386. function hasTypeArguments(node) {
  14387. return !!node.typeArguments;
  14388. }
  14389. ts.hasTypeArguments = hasTypeArguments;
  14390. var AssignmentKind;
  14391. (function (AssignmentKind) {
  14392. AssignmentKind[AssignmentKind["None"] = 0] = "None";
  14393. AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
  14394. AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
  14395. })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
  14396. function getAssignmentTargetKind(node) {
  14397. var parent = node.parent;
  14398. while (true) {
  14399. switch (parent.kind) {
  14400. case 209 /* BinaryExpression */:
  14401. var binaryOperator = parent.operatorToken.kind;
  14402. return isAssignmentOperator(binaryOperator) && parent.left === node ?
  14403. binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
  14404. 0 /* None */;
  14405. case 207 /* PrefixUnaryExpression */:
  14406. case 208 /* PostfixUnaryExpression */:
  14407. var unaryOperator = parent.operator;
  14408. return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
  14409. case 231 /* ForInStatement */:
  14410. case 232 /* ForOfStatement */:
  14411. return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
  14412. case 200 /* ParenthesizedExpression */:
  14413. case 192 /* ArrayLiteralExpression */:
  14414. case 213 /* SpreadElement */:
  14415. case 218 /* NonNullExpression */:
  14416. node = parent;
  14417. break;
  14418. case 282 /* ShorthandPropertyAssignment */:
  14419. if (parent.name !== node) {
  14420. return 0 /* None */;
  14421. }
  14422. node = parent.parent;
  14423. break;
  14424. case 281 /* PropertyAssignment */:
  14425. if (parent.name === node) {
  14426. return 0 /* None */;
  14427. }
  14428. node = parent.parent;
  14429. break;
  14430. default:
  14431. return 0 /* None */;
  14432. }
  14433. parent = node.parent;
  14434. }
  14435. }
  14436. ts.getAssignmentTargetKind = getAssignmentTargetKind;
  14437. // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
  14438. // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
  14439. // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
  14440. // (Note that `p` is not a target in the above examples, only `a`.)
  14441. function isAssignmentTarget(node) {
  14442. return getAssignmentTargetKind(node) !== 0 /* None */;
  14443. }
  14444. ts.isAssignmentTarget = isAssignmentTarget;
  14445. /**
  14446. * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
  14447. * the same `var` declaration scope as the node's parent.
  14448. */
  14449. function isNodeWithPossibleHoistedDeclaration(node) {
  14450. switch (node.kind) {
  14451. case 223 /* Block */:
  14452. case 225 /* VariableStatement */:
  14453. case 236 /* WithStatement */:
  14454. case 227 /* IfStatement */:
  14455. case 237 /* SwitchStatement */:
  14456. case 251 /* CaseBlock */:
  14457. case 277 /* CaseClause */:
  14458. case 278 /* DefaultClause */:
  14459. case 238 /* LabeledStatement */:
  14460. case 230 /* ForStatement */:
  14461. case 231 /* ForInStatement */:
  14462. case 232 /* ForOfStatement */:
  14463. case 228 /* DoStatement */:
  14464. case 229 /* WhileStatement */:
  14465. case 240 /* TryStatement */:
  14466. case 280 /* CatchClause */:
  14467. return true;
  14468. }
  14469. return false;
  14470. }
  14471. ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
  14472. function isValueSignatureDeclaration(node) {
  14473. return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
  14474. }
  14475. ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
  14476. function walkUp(node, kind) {
  14477. while (node && node.kind === kind) {
  14478. node = node.parent;
  14479. }
  14480. return node;
  14481. }
  14482. function walkUpParenthesizedTypes(node) {
  14483. return walkUp(node, 182 /* ParenthesizedType */);
  14484. }
  14485. ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
  14486. function walkUpParenthesizedExpressions(node) {
  14487. return walkUp(node, 200 /* ParenthesizedExpression */);
  14488. }
  14489. ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
  14490. function skipParentheses(node) {
  14491. while (node.kind === 200 /* ParenthesizedExpression */) {
  14492. node = node.expression;
  14493. }
  14494. return node;
  14495. }
  14496. ts.skipParentheses = skipParentheses;
  14497. function skipParenthesesUp(node) {
  14498. while (node.kind === 200 /* ParenthesizedExpression */) {
  14499. node = node.parent;
  14500. }
  14501. return node;
  14502. }
  14503. // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
  14504. function isDeleteTarget(node) {
  14505. if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
  14506. return false;
  14507. }
  14508. node = walkUpParenthesizedExpressions(node.parent);
  14509. return node && node.kind === 203 /* DeleteExpression */;
  14510. }
  14511. ts.isDeleteTarget = isDeleteTarget;
  14512. function isNodeDescendantOf(node, ancestor) {
  14513. while (node) {
  14514. if (node === ancestor)
  14515. return true;
  14516. node = node.parent;
  14517. }
  14518. return false;
  14519. }
  14520. ts.isNodeDescendantOf = isNodeDescendantOf;
  14521. // True if `name` is the name of a declaration node
  14522. function isDeclarationName(name) {
  14523. return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
  14524. }
  14525. ts.isDeclarationName = isDeclarationName;
  14526. // See GH#16030
  14527. function getDeclarationFromName(name) {
  14528. var parent = name.parent;
  14529. switch (name.kind) {
  14530. case 10 /* StringLiteral */:
  14531. case 14 /* NoSubstitutionTemplateLiteral */:
  14532. case 8 /* NumericLiteral */:
  14533. if (ts.isComputedPropertyName(parent))
  14534. return parent.parent;
  14535. // falls through
  14536. case 75 /* Identifier */:
  14537. if (ts.isDeclaration(parent)) {
  14538. return parent.name === name ? parent : undefined;
  14539. }
  14540. else if (ts.isQualifiedName(parent)) {
  14541. var tag = parent.parent;
  14542. return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
  14543. }
  14544. else {
  14545. var binExp = parent.parent;
  14546. return ts.isBinaryExpression(binExp) &&
  14547. getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
  14548. (binExp.left.symbol || binExp.symbol) &&
  14549. ts.getNameOfDeclaration(binExp) === name
  14550. ? binExp
  14551. : undefined;
  14552. }
  14553. case 76 /* PrivateIdentifier */:
  14554. return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
  14555. default:
  14556. return undefined;
  14557. }
  14558. }
  14559. ts.getDeclarationFromName = getDeclarationFromName;
  14560. function isLiteralComputedPropertyDeclarationName(node) {
  14561. return isStringOrNumericLiteralLike(node) &&
  14562. node.parent.kind === 154 /* ComputedPropertyName */ &&
  14563. ts.isDeclaration(node.parent.parent);
  14564. }
  14565. ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
  14566. // Return true if the given identifier is classified as an IdentifierName
  14567. function isIdentifierName(node) {
  14568. var parent = node.parent;
  14569. switch (parent.kind) {
  14570. case 159 /* PropertyDeclaration */:
  14571. case 158 /* PropertySignature */:
  14572. case 161 /* MethodDeclaration */:
  14573. case 160 /* MethodSignature */:
  14574. case 163 /* GetAccessor */:
  14575. case 164 /* SetAccessor */:
  14576. case 284 /* EnumMember */:
  14577. case 281 /* PropertyAssignment */:
  14578. case 194 /* PropertyAccessExpression */:
  14579. // Name in member declaration or property name in property access
  14580. return parent.name === node;
  14581. case 153 /* QualifiedName */:
  14582. // Name on right hand side of dot in a type query or type reference
  14583. if (parent.right === node) {
  14584. while (parent.kind === 153 /* QualifiedName */) {
  14585. parent = parent.parent;
  14586. }
  14587. return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
  14588. }
  14589. return false;
  14590. case 191 /* BindingElement */:
  14591. case 258 /* ImportSpecifier */:
  14592. // Property name in binding element or import specifier
  14593. return parent.propertyName === node;
  14594. case 263 /* ExportSpecifier */:
  14595. case 273 /* JsxAttribute */:
  14596. // Any name in an export specifier or JSX Attribute
  14597. return true;
  14598. }
  14599. return false;
  14600. }
  14601. ts.isIdentifierName = isIdentifierName;
  14602. // An alias symbol is created by one of the following declarations:
  14603. // import <symbol> = ...
  14604. // import <symbol> from ...
  14605. // import * as <symbol> from ...
  14606. // import { x as <symbol> } from ...
  14607. // export { x as <symbol> } from ...
  14608. // export * as ns <symbol> from ...
  14609. // export = <EntityNameExpression>
  14610. // export default <EntityNameExpression>
  14611. // module.exports = <EntityNameExpression>
  14612. // {<Identifier>}
  14613. // {name: <EntityNameExpression>}
  14614. function isAliasSymbolDeclaration(node) {
  14615. return node.kind === 253 /* ImportEqualsDeclaration */ ||
  14616. node.kind === 252 /* NamespaceExportDeclaration */ ||
  14617. node.kind === 255 /* ImportClause */ && !!node.name ||
  14618. node.kind === 256 /* NamespaceImport */ ||
  14619. node.kind === 262 /* NamespaceExport */ ||
  14620. node.kind === 258 /* ImportSpecifier */ ||
  14621. node.kind === 263 /* ExportSpecifier */ ||
  14622. node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
  14623. ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
  14624. ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
  14625. node.kind === 282 /* ShorthandPropertyAssignment */ ||
  14626. node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
  14627. }
  14628. ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
  14629. function getAliasDeclarationFromName(node) {
  14630. switch (node.parent.kind) {
  14631. case 255 /* ImportClause */:
  14632. case 258 /* ImportSpecifier */:
  14633. case 256 /* NamespaceImport */:
  14634. case 263 /* ExportSpecifier */:
  14635. case 259 /* ExportAssignment */:
  14636. case 253 /* ImportEqualsDeclaration */:
  14637. return node.parent;
  14638. case 153 /* QualifiedName */:
  14639. do {
  14640. node = node.parent;
  14641. } while (node.parent.kind === 153 /* QualifiedName */);
  14642. return getAliasDeclarationFromName(node);
  14643. }
  14644. }
  14645. ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
  14646. function isAliasableExpression(e) {
  14647. return isEntityNameExpression(e) || ts.isClassExpression(e);
  14648. }
  14649. ts.isAliasableExpression = isAliasableExpression;
  14650. function exportAssignmentIsAlias(node) {
  14651. var e = getExportAssignmentExpression(node);
  14652. return isAliasableExpression(e);
  14653. }
  14654. ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
  14655. function getExportAssignmentExpression(node) {
  14656. return ts.isExportAssignment(node) ? node.expression : node.right;
  14657. }
  14658. ts.getExportAssignmentExpression = getExportAssignmentExpression;
  14659. function getPropertyAssignmentAliasLikeExpression(node) {
  14660. return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
  14661. node.parent.right;
  14662. }
  14663. ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
  14664. function getEffectiveBaseTypeNode(node) {
  14665. var baseType = getClassExtendsHeritageElement(node);
  14666. if (baseType && isInJSFile(node)) {
  14667. // Prefer an @augments tag because it may have type parameters.
  14668. var tag = ts.getJSDocAugmentsTag(node);
  14669. if (tag) {
  14670. return tag.class;
  14671. }
  14672. }
  14673. return baseType;
  14674. }
  14675. ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
  14676. function getClassExtendsHeritageElement(node) {
  14677. var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
  14678. return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
  14679. }
  14680. ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
  14681. function getClassImplementsHeritageClauseElements(node) {
  14682. var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
  14683. return heritageClause ? heritageClause.types : undefined;
  14684. }
  14685. ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements;
  14686. /** Returns the node in an `extends` or `implements` clause of a class or interface. */
  14687. function getAllSuperTypeNodes(node) {
  14688. return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
  14689. ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray :
  14690. ts.emptyArray;
  14691. }
  14692. ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
  14693. function getInterfaceBaseTypeNodes(node) {
  14694. var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
  14695. return heritageClause ? heritageClause.types : undefined;
  14696. }
  14697. ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
  14698. function getHeritageClause(clauses, kind) {
  14699. if (clauses) {
  14700. for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
  14701. var clause = clauses_1[_i];
  14702. if (clause.token === kind) {
  14703. return clause;
  14704. }
  14705. }
  14706. }
  14707. return undefined;
  14708. }
  14709. ts.getHeritageClause = getHeritageClause;
  14710. function getAncestor(node, kind) {
  14711. while (node) {
  14712. if (node.kind === kind) {
  14713. return node;
  14714. }
  14715. node = node.parent;
  14716. }
  14717. return undefined;
  14718. }
  14719. ts.getAncestor = getAncestor;
  14720. function isKeyword(token) {
  14721. return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
  14722. }
  14723. ts.isKeyword = isKeyword;
  14724. function isContextualKeyword(token) {
  14725. return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
  14726. }
  14727. ts.isContextualKeyword = isContextualKeyword;
  14728. function isNonContextualKeyword(token) {
  14729. return isKeyword(token) && !isContextualKeyword(token);
  14730. }
  14731. ts.isNonContextualKeyword = isNonContextualKeyword;
  14732. function isFutureReservedKeyword(token) {
  14733. return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
  14734. }
  14735. ts.isFutureReservedKeyword = isFutureReservedKeyword;
  14736. function isStringANonContextualKeyword(name) {
  14737. var token = ts.stringToToken(name);
  14738. return token !== undefined && isNonContextualKeyword(token);
  14739. }
  14740. ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
  14741. function isStringAKeyword(name) {
  14742. var token = ts.stringToToken(name);
  14743. return token !== undefined && isKeyword(token);
  14744. }
  14745. ts.isStringAKeyword = isStringAKeyword;
  14746. function isIdentifierANonContextualKeyword(_a) {
  14747. var originalKeywordKind = _a.originalKeywordKind;
  14748. return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
  14749. }
  14750. ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
  14751. function isTrivia(token) {
  14752. return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
  14753. }
  14754. ts.isTrivia = isTrivia;
  14755. var FunctionFlags;
  14756. (function (FunctionFlags) {
  14757. FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
  14758. FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
  14759. FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
  14760. FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
  14761. FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
  14762. })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
  14763. function getFunctionFlags(node) {
  14764. if (!node) {
  14765. return 4 /* Invalid */;
  14766. }
  14767. var flags = 0 /* Normal */;
  14768. switch (node.kind) {
  14769. case 244 /* FunctionDeclaration */:
  14770. case 201 /* FunctionExpression */:
  14771. case 161 /* MethodDeclaration */:
  14772. if (node.asteriskToken) {
  14773. flags |= 1 /* Generator */;
  14774. }
  14775. // falls through
  14776. case 202 /* ArrowFunction */:
  14777. if (hasModifier(node, 256 /* Async */)) {
  14778. flags |= 2 /* Async */;
  14779. }
  14780. break;
  14781. }
  14782. if (!node.body) {
  14783. flags |= 4 /* Invalid */;
  14784. }
  14785. return flags;
  14786. }
  14787. ts.getFunctionFlags = getFunctionFlags;
  14788. function isAsyncFunction(node) {
  14789. switch (node.kind) {
  14790. case 244 /* FunctionDeclaration */:
  14791. case 201 /* FunctionExpression */:
  14792. case 202 /* ArrowFunction */:
  14793. case 161 /* MethodDeclaration */:
  14794. return node.body !== undefined
  14795. && node.asteriskToken === undefined
  14796. && hasModifier(node, 256 /* Async */);
  14797. }
  14798. return false;
  14799. }
  14800. ts.isAsyncFunction = isAsyncFunction;
  14801. function isStringOrNumericLiteralLike(node) {
  14802. return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
  14803. }
  14804. ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
  14805. function isSignedNumericLiteral(node) {
  14806. return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
  14807. }
  14808. ts.isSignedNumericLiteral = isSignedNumericLiteral;
  14809. /**
  14810. * A declaration has a dynamic name if all of the following are true:
  14811. * 1. The declaration has a computed property name.
  14812. * 2. The computed name is *not* expressed as a StringLiteral.
  14813. * 3. The computed name is *not* expressed as a NumericLiteral.
  14814. * 4. The computed name is *not* expressed as a PlusToken or MinusToken
  14815. * immediately followed by a NumericLiteral.
  14816. * 5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
  14817. * is a property of the Symbol constructor that denotes a built-in
  14818. * Symbol.
  14819. */
  14820. function hasDynamicName(declaration) {
  14821. var name = ts.getNameOfDeclaration(declaration);
  14822. return !!name && isDynamicName(name);
  14823. }
  14824. ts.hasDynamicName = hasDynamicName;
  14825. function isDynamicName(name) {
  14826. if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
  14827. return false;
  14828. }
  14829. var expr = ts.isElementAccessExpression(name) ? name.argumentExpression : name.expression;
  14830. return !isStringOrNumericLiteralLike(expr) &&
  14831. !isSignedNumericLiteral(expr) &&
  14832. !isWellKnownSymbolSyntactically(expr);
  14833. }
  14834. ts.isDynamicName = isDynamicName;
  14835. /**
  14836. * Checks if the expression is of the form:
  14837. * Symbol.name
  14838. * where Symbol is literally the word "Symbol", and name is any identifierName
  14839. */
  14840. function isWellKnownSymbolSyntactically(node) {
  14841. return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
  14842. }
  14843. ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
  14844. function getPropertyNameForPropertyNameNode(name) {
  14845. switch (name.kind) {
  14846. case 75 /* Identifier */:
  14847. case 76 /* PrivateIdentifier */:
  14848. return name.escapedText;
  14849. case 10 /* StringLiteral */:
  14850. case 8 /* NumericLiteral */:
  14851. return ts.escapeLeadingUnderscores(name.text);
  14852. case 154 /* ComputedPropertyName */:
  14853. var nameExpression = name.expression;
  14854. if (isWellKnownSymbolSyntactically(nameExpression)) {
  14855. return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
  14856. }
  14857. else if (isStringOrNumericLiteralLike(nameExpression)) {
  14858. return ts.escapeLeadingUnderscores(nameExpression.text);
  14859. }
  14860. return undefined;
  14861. default:
  14862. return ts.Debug.assertNever(name);
  14863. }
  14864. }
  14865. ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
  14866. function isPropertyNameLiteral(node) {
  14867. switch (node.kind) {
  14868. case 75 /* Identifier */:
  14869. case 10 /* StringLiteral */:
  14870. case 14 /* NoSubstitutionTemplateLiteral */:
  14871. case 8 /* NumericLiteral */:
  14872. return true;
  14873. default:
  14874. return false;
  14875. }
  14876. }
  14877. ts.isPropertyNameLiteral = isPropertyNameLiteral;
  14878. function getTextOfIdentifierOrLiteral(node) {
  14879. return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
  14880. }
  14881. ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
  14882. function getEscapedTextOfIdentifierOrLiteral(node) {
  14883. return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
  14884. }
  14885. ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
  14886. function getPropertyNameForUniqueESSymbol(symbol) {
  14887. return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
  14888. }
  14889. ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
  14890. function getPropertyNameForKnownSymbolName(symbolName) {
  14891. return "__@" + symbolName;
  14892. }
  14893. ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
  14894. function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
  14895. return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
  14896. }
  14897. ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
  14898. function isKnownSymbol(symbol) {
  14899. return ts.startsWith(symbol.escapedName, "__@");
  14900. }
  14901. ts.isKnownSymbol = isKnownSymbol;
  14902. /**
  14903. * Includes the word "Symbol" with unicode escapes
  14904. */
  14905. function isESSymbolIdentifier(node) {
  14906. return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
  14907. }
  14908. ts.isESSymbolIdentifier = isESSymbolIdentifier;
  14909. function isPushOrUnshiftIdentifier(node) {
  14910. return node.escapedText === "push" || node.escapedText === "unshift";
  14911. }
  14912. ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
  14913. function isParameterDeclaration(node) {
  14914. var root = getRootDeclaration(node);
  14915. return root.kind === 156 /* Parameter */;
  14916. }
  14917. ts.isParameterDeclaration = isParameterDeclaration;
  14918. function getRootDeclaration(node) {
  14919. while (node.kind === 191 /* BindingElement */) {
  14920. node = node.parent.parent;
  14921. }
  14922. return node;
  14923. }
  14924. ts.getRootDeclaration = getRootDeclaration;
  14925. function nodeStartsNewLexicalEnvironment(node) {
  14926. var kind = node.kind;
  14927. return kind === 162 /* Constructor */
  14928. || kind === 201 /* FunctionExpression */
  14929. || kind === 244 /* FunctionDeclaration */
  14930. || kind === 202 /* ArrowFunction */
  14931. || kind === 161 /* MethodDeclaration */
  14932. || kind === 163 /* GetAccessor */
  14933. || kind === 164 /* SetAccessor */
  14934. || kind === 249 /* ModuleDeclaration */
  14935. || kind === 290 /* SourceFile */;
  14936. }
  14937. ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
  14938. function nodeIsSynthesized(range) {
  14939. return positionIsSynthesized(range.pos)
  14940. || positionIsSynthesized(range.end);
  14941. }
  14942. ts.nodeIsSynthesized = nodeIsSynthesized;
  14943. function getOriginalSourceFile(sourceFile) {
  14944. return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
  14945. }
  14946. ts.getOriginalSourceFile = getOriginalSourceFile;
  14947. var Associativity;
  14948. (function (Associativity) {
  14949. Associativity[Associativity["Left"] = 0] = "Left";
  14950. Associativity[Associativity["Right"] = 1] = "Right";
  14951. })(Associativity = ts.Associativity || (ts.Associativity = {}));
  14952. function getExpressionAssociativity(expression) {
  14953. var operator = getOperator(expression);
  14954. var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
  14955. return getOperatorAssociativity(expression.kind, operator, hasArguments);
  14956. }
  14957. ts.getExpressionAssociativity = getExpressionAssociativity;
  14958. function getOperatorAssociativity(kind, operator, hasArguments) {
  14959. switch (kind) {
  14960. case 197 /* NewExpression */:
  14961. return hasArguments ? 0 /* Left */ : 1 /* Right */;
  14962. case 207 /* PrefixUnaryExpression */:
  14963. case 204 /* TypeOfExpression */:
  14964. case 205 /* VoidExpression */:
  14965. case 203 /* DeleteExpression */:
  14966. case 206 /* AwaitExpression */:
  14967. case 210 /* ConditionalExpression */:
  14968. case 212 /* YieldExpression */:
  14969. return 1 /* Right */;
  14970. case 209 /* BinaryExpression */:
  14971. switch (operator) {
  14972. case 42 /* AsteriskAsteriskToken */:
  14973. case 62 /* EqualsToken */:
  14974. case 63 /* PlusEqualsToken */:
  14975. case 64 /* MinusEqualsToken */:
  14976. case 66 /* AsteriskAsteriskEqualsToken */:
  14977. case 65 /* AsteriskEqualsToken */:
  14978. case 67 /* SlashEqualsToken */:
  14979. case 68 /* PercentEqualsToken */:
  14980. case 69 /* LessThanLessThanEqualsToken */:
  14981. case 70 /* GreaterThanGreaterThanEqualsToken */:
  14982. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  14983. case 72 /* AmpersandEqualsToken */:
  14984. case 74 /* CaretEqualsToken */:
  14985. case 73 /* BarEqualsToken */:
  14986. return 1 /* Right */;
  14987. }
  14988. }
  14989. return 0 /* Left */;
  14990. }
  14991. ts.getOperatorAssociativity = getOperatorAssociativity;
  14992. function getExpressionPrecedence(expression) {
  14993. var operator = getOperator(expression);
  14994. var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
  14995. return getOperatorPrecedence(expression.kind, operator, hasArguments);
  14996. }
  14997. ts.getExpressionPrecedence = getExpressionPrecedence;
  14998. function getOperator(expression) {
  14999. if (expression.kind === 209 /* BinaryExpression */) {
  15000. return expression.operatorToken.kind;
  15001. }
  15002. else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
  15003. return expression.operator;
  15004. }
  15005. else {
  15006. return expression.kind;
  15007. }
  15008. }
  15009. ts.getOperator = getOperator;
  15010. function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
  15011. switch (nodeKind) {
  15012. case 326 /* CommaListExpression */:
  15013. return 0;
  15014. case 213 /* SpreadElement */:
  15015. return 1;
  15016. case 212 /* YieldExpression */:
  15017. return 2;
  15018. case 210 /* ConditionalExpression */:
  15019. return 4;
  15020. case 209 /* BinaryExpression */:
  15021. switch (operatorKind) {
  15022. case 27 /* CommaToken */:
  15023. return 0;
  15024. case 62 /* EqualsToken */:
  15025. case 63 /* PlusEqualsToken */:
  15026. case 64 /* MinusEqualsToken */:
  15027. case 66 /* AsteriskAsteriskEqualsToken */:
  15028. case 65 /* AsteriskEqualsToken */:
  15029. case 67 /* SlashEqualsToken */:
  15030. case 68 /* PercentEqualsToken */:
  15031. case 69 /* LessThanLessThanEqualsToken */:
  15032. case 70 /* GreaterThanGreaterThanEqualsToken */:
  15033. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  15034. case 72 /* AmpersandEqualsToken */:
  15035. case 74 /* CaretEqualsToken */:
  15036. case 73 /* BarEqualsToken */:
  15037. return 3;
  15038. default:
  15039. return getBinaryOperatorPrecedence(operatorKind);
  15040. }
  15041. case 207 /* PrefixUnaryExpression */:
  15042. case 204 /* TypeOfExpression */:
  15043. case 205 /* VoidExpression */:
  15044. case 203 /* DeleteExpression */:
  15045. case 206 /* AwaitExpression */:
  15046. return 16;
  15047. case 208 /* PostfixUnaryExpression */:
  15048. return 17;
  15049. case 196 /* CallExpression */:
  15050. return 18;
  15051. case 197 /* NewExpression */:
  15052. return hasArguments ? 19 : 18;
  15053. case 198 /* TaggedTemplateExpression */:
  15054. case 194 /* PropertyAccessExpression */:
  15055. case 195 /* ElementAccessExpression */:
  15056. return 19;
  15057. case 104 /* ThisKeyword */:
  15058. case 102 /* SuperKeyword */:
  15059. case 75 /* Identifier */:
  15060. case 100 /* NullKeyword */:
  15061. case 106 /* TrueKeyword */:
  15062. case 91 /* FalseKeyword */:
  15063. case 8 /* NumericLiteral */:
  15064. case 9 /* BigIntLiteral */:
  15065. case 10 /* StringLiteral */:
  15066. case 192 /* ArrayLiteralExpression */:
  15067. case 193 /* ObjectLiteralExpression */:
  15068. case 201 /* FunctionExpression */:
  15069. case 202 /* ArrowFunction */:
  15070. case 214 /* ClassExpression */:
  15071. case 266 /* JsxElement */:
  15072. case 267 /* JsxSelfClosingElement */:
  15073. case 270 /* JsxFragment */:
  15074. case 13 /* RegularExpressionLiteral */:
  15075. case 14 /* NoSubstitutionTemplateLiteral */:
  15076. case 211 /* TemplateExpression */:
  15077. case 200 /* ParenthesizedExpression */:
  15078. case 215 /* OmittedExpression */:
  15079. return 20;
  15080. default:
  15081. return -1;
  15082. }
  15083. }
  15084. ts.getOperatorPrecedence = getOperatorPrecedence;
  15085. function getBinaryOperatorPrecedence(kind) {
  15086. switch (kind) {
  15087. case 60 /* QuestionQuestionToken */:
  15088. return 4;
  15089. case 56 /* BarBarToken */:
  15090. return 5;
  15091. case 55 /* AmpersandAmpersandToken */:
  15092. return 6;
  15093. case 51 /* BarToken */:
  15094. return 7;
  15095. case 52 /* CaretToken */:
  15096. return 8;
  15097. case 50 /* AmpersandToken */:
  15098. return 9;
  15099. case 34 /* EqualsEqualsToken */:
  15100. case 35 /* ExclamationEqualsToken */:
  15101. case 36 /* EqualsEqualsEqualsToken */:
  15102. case 37 /* ExclamationEqualsEqualsToken */:
  15103. return 10;
  15104. case 29 /* LessThanToken */:
  15105. case 31 /* GreaterThanToken */:
  15106. case 32 /* LessThanEqualsToken */:
  15107. case 33 /* GreaterThanEqualsToken */:
  15108. case 98 /* InstanceOfKeyword */:
  15109. case 97 /* InKeyword */:
  15110. case 123 /* AsKeyword */:
  15111. return 11;
  15112. case 47 /* LessThanLessThanToken */:
  15113. case 48 /* GreaterThanGreaterThanToken */:
  15114. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  15115. return 12;
  15116. case 39 /* PlusToken */:
  15117. case 40 /* MinusToken */:
  15118. return 13;
  15119. case 41 /* AsteriskToken */:
  15120. case 43 /* SlashToken */:
  15121. case 44 /* PercentToken */:
  15122. return 14;
  15123. case 42 /* AsteriskAsteriskToken */:
  15124. return 15;
  15125. }
  15126. // -1 is lower than all other precedences. Returning it will cause binary expression
  15127. // parsing to stop.
  15128. return -1;
  15129. }
  15130. ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
  15131. function createDiagnosticCollection() {
  15132. var nonFileDiagnostics = []; // See GH#19873
  15133. var filesWithDiagnostics = [];
  15134. var fileDiagnostics = ts.createMap();
  15135. var hasReadNonFileDiagnostics = false;
  15136. return {
  15137. add: add,
  15138. lookup: lookup,
  15139. getGlobalDiagnostics: getGlobalDiagnostics,
  15140. getDiagnostics: getDiagnostics,
  15141. reattachFileDiagnostics: reattachFileDiagnostics
  15142. };
  15143. function reattachFileDiagnostics(newFile) {
  15144. ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
  15145. }
  15146. function lookup(diagnostic) {
  15147. var diagnostics;
  15148. if (diagnostic.file) {
  15149. diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
  15150. }
  15151. else {
  15152. diagnostics = nonFileDiagnostics;
  15153. }
  15154. if (!diagnostics) {
  15155. return undefined;
  15156. }
  15157. var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
  15158. if (result >= 0) {
  15159. return diagnostics[result];
  15160. }
  15161. return undefined;
  15162. }
  15163. function add(diagnostic) {
  15164. var diagnostics;
  15165. if (diagnostic.file) {
  15166. diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
  15167. if (!diagnostics) {
  15168. diagnostics = []; // See GH#19873
  15169. fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
  15170. ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
  15171. }
  15172. }
  15173. else {
  15174. // If we've already read the non-file diagnostics, do not modify the existing array.
  15175. if (hasReadNonFileDiagnostics) {
  15176. hasReadNonFileDiagnostics = false;
  15177. nonFileDiagnostics = nonFileDiagnostics.slice();
  15178. }
  15179. diagnostics = nonFileDiagnostics;
  15180. }
  15181. ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
  15182. }
  15183. function getGlobalDiagnostics() {
  15184. hasReadNonFileDiagnostics = true;
  15185. return nonFileDiagnostics;
  15186. }
  15187. function getDiagnostics(fileName) {
  15188. if (fileName) {
  15189. return fileDiagnostics.get(fileName) || [];
  15190. }
  15191. var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
  15192. if (!nonFileDiagnostics.length) {
  15193. return fileDiags;
  15194. }
  15195. fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
  15196. return fileDiags;
  15197. }
  15198. }
  15199. ts.createDiagnosticCollection = createDiagnosticCollection;
  15200. var templateSubstitutionRegExp = /\$\{/g;
  15201. function escapeTemplateSubstitution(str) {
  15202. return str.replace(templateSubstitutionRegExp, "\\${");
  15203. }
  15204. // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
  15205. // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
  15206. // the language service. These characters should be escaped when printing, and if any characters are added,
  15207. // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
  15208. // There is no reason for this other than that JSON.stringify does not handle it either.
  15209. var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
  15210. var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
  15211. // Template strings should be preserved as much as possible
  15212. var backtickQuoteEscapedCharsRegExp = /[\\\`]/g;
  15213. var escapedCharsMap = ts.createMapFromTemplate({
  15214. "\t": "\\t",
  15215. "\v": "\\v",
  15216. "\f": "\\f",
  15217. "\b": "\\b",
  15218. "\r": "\\r",
  15219. "\n": "\\n",
  15220. "\\": "\\\\",
  15221. "\"": "\\\"",
  15222. "\'": "\\\'",
  15223. "\`": "\\\`",
  15224. "\u2028": "\\u2028",
  15225. "\u2029": "\\u2029",
  15226. "\u0085": "\\u0085" // nextLine
  15227. });
  15228. function encodeUtf16EscapeSequence(charCode) {
  15229. var hexCharCode = charCode.toString(16).toUpperCase();
  15230. var paddedHexCode = ("0000" + hexCharCode).slice(-4);
  15231. return "\\u" + paddedHexCode;
  15232. }
  15233. function getReplacement(c, offset, input) {
  15234. if (c.charCodeAt(0) === 0 /* nullCharacter */) {
  15235. var lookAhead = input.charCodeAt(offset + c.length);
  15236. if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
  15237. // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode)
  15238. return "\\x00";
  15239. }
  15240. // Otherwise, keep printing a literal \0 for the null character
  15241. return "\\0";
  15242. }
  15243. return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
  15244. }
  15245. /**
  15246. * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
  15247. * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
  15248. * Note that this doesn't actually wrap the input in double quotes.
  15249. */
  15250. function escapeString(s, quoteChar) {
  15251. var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
  15252. quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
  15253. doubleQuoteEscapedCharsRegExp;
  15254. return s.replace(escapedCharsRegExp, getReplacement);
  15255. }
  15256. ts.escapeString = escapeString;
  15257. var nonAsciiCharacters = /[^\u0000-\u007F]/g;
  15258. function escapeNonAsciiString(s, quoteChar) {
  15259. s = escapeString(s, quoteChar);
  15260. // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
  15261. // Otherwise just return the original string.
  15262. return nonAsciiCharacters.test(s) ?
  15263. s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
  15264. s;
  15265. }
  15266. ts.escapeNonAsciiString = escapeNonAsciiString;
  15267. // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
  15268. // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
  15269. // the language service. These characters should be escaped when printing, and if any characters are added,
  15270. // the map below must be updated.
  15271. var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
  15272. var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
  15273. var jsxEscapedCharsMap = ts.createMapFromTemplate({
  15274. "\"": "&quot;",
  15275. "\'": "&apos;"
  15276. });
  15277. function encodeJsxCharacterEntity(charCode) {
  15278. var hexCharCode = charCode.toString(16).toUpperCase();
  15279. return "&#x" + hexCharCode + ";";
  15280. }
  15281. function getJsxAttributeStringReplacement(c) {
  15282. if (c.charCodeAt(0) === 0 /* nullCharacter */) {
  15283. return "&#0;";
  15284. }
  15285. return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
  15286. }
  15287. function escapeJsxAttributeString(s, quoteChar) {
  15288. var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
  15289. jsxDoubleQuoteEscapedCharsRegExp;
  15290. return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
  15291. }
  15292. ts.escapeJsxAttributeString = escapeJsxAttributeString;
  15293. /**
  15294. * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
  15295. *
  15296. * @return non-quoted string
  15297. */
  15298. function stripQuotes(name) {
  15299. var length = name.length;
  15300. if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
  15301. return name.substring(1, length - 1);
  15302. }
  15303. return name;
  15304. }
  15305. ts.stripQuotes = stripQuotes;
  15306. function isQuoteOrBacktick(charCode) {
  15307. return charCode === 39 /* singleQuote */ ||
  15308. charCode === 34 /* doubleQuote */ ||
  15309. charCode === 96 /* backtick */;
  15310. }
  15311. function isIntrinsicJsxName(name) {
  15312. var ch = name.charCodeAt(0);
  15313. return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
  15314. }
  15315. ts.isIntrinsicJsxName = isIntrinsicJsxName;
  15316. var indentStrings = ["", " "];
  15317. function getIndentString(level) {
  15318. if (indentStrings[level] === undefined) {
  15319. indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
  15320. }
  15321. return indentStrings[level];
  15322. }
  15323. ts.getIndentString = getIndentString;
  15324. function getIndentSize() {
  15325. return indentStrings[1].length;
  15326. }
  15327. ts.getIndentSize = getIndentSize;
  15328. function createTextWriter(newLine) {
  15329. var output;
  15330. var indent;
  15331. var lineStart;
  15332. var lineCount;
  15333. var linePos;
  15334. var hasTrailingComment = false;
  15335. function updateLineCountAndPosFor(s) {
  15336. var lineStartsOfS = ts.computeLineStarts(s);
  15337. if (lineStartsOfS.length > 1) {
  15338. lineCount = lineCount + lineStartsOfS.length - 1;
  15339. linePos = output.length - s.length + ts.last(lineStartsOfS);
  15340. lineStart = (linePos - output.length) === 0;
  15341. }
  15342. else {
  15343. lineStart = false;
  15344. }
  15345. }
  15346. function writeText(s) {
  15347. if (s && s.length) {
  15348. if (lineStart) {
  15349. s = getIndentString(indent) + s;
  15350. lineStart = false;
  15351. }
  15352. output += s;
  15353. updateLineCountAndPosFor(s);
  15354. }
  15355. }
  15356. function write(s) {
  15357. if (s)
  15358. hasTrailingComment = false;
  15359. writeText(s);
  15360. }
  15361. function writeComment(s) {
  15362. if (s)
  15363. hasTrailingComment = true;
  15364. writeText(s);
  15365. }
  15366. function reset() {
  15367. output = "";
  15368. indent = 0;
  15369. lineStart = true;
  15370. lineCount = 0;
  15371. linePos = 0;
  15372. hasTrailingComment = false;
  15373. }
  15374. function rawWrite(s) {
  15375. if (s !== undefined) {
  15376. output += s;
  15377. updateLineCountAndPosFor(s);
  15378. hasTrailingComment = false;
  15379. }
  15380. }
  15381. function writeLiteral(s) {
  15382. if (s && s.length) {
  15383. write(s);
  15384. }
  15385. }
  15386. function writeLine() {
  15387. if (!lineStart) {
  15388. output += newLine;
  15389. lineCount++;
  15390. linePos = output.length;
  15391. lineStart = true;
  15392. hasTrailingComment = false;
  15393. }
  15394. }
  15395. function getTextPosWithWriteLine() {
  15396. return lineStart ? output.length : (output.length + newLine.length);
  15397. }
  15398. reset();
  15399. return {
  15400. write: write,
  15401. rawWrite: rawWrite,
  15402. writeLiteral: writeLiteral,
  15403. writeLine: writeLine,
  15404. increaseIndent: function () { indent++; },
  15405. decreaseIndent: function () { indent--; },
  15406. getIndent: function () { return indent; },
  15407. getTextPos: function () { return output.length; },
  15408. getLine: function () { return lineCount; },
  15409. getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
  15410. getText: function () { return output; },
  15411. isAtStartOfLine: function () { return lineStart; },
  15412. hasTrailingComment: function () { return hasTrailingComment; },
  15413. hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
  15414. clear: reset,
  15415. reportInaccessibleThisError: ts.noop,
  15416. reportPrivateInBaseOfClassExpression: ts.noop,
  15417. reportInaccessibleUniqueSymbolError: ts.noop,
  15418. trackSymbol: ts.noop,
  15419. writeKeyword: write,
  15420. writeOperator: write,
  15421. writeParameter: write,
  15422. writeProperty: write,
  15423. writePunctuation: write,
  15424. writeSpace: write,
  15425. writeStringLiteral: write,
  15426. writeSymbol: function (s, _) { return write(s); },
  15427. writeTrailingSemicolon: write,
  15428. writeComment: writeComment,
  15429. getTextPosWithWriteLine: getTextPosWithWriteLine
  15430. };
  15431. }
  15432. ts.createTextWriter = createTextWriter;
  15433. function getTrailingSemicolonDeferringWriter(writer) {
  15434. var pendingTrailingSemicolon = false;
  15435. function commitPendingTrailingSemicolon() {
  15436. if (pendingTrailingSemicolon) {
  15437. writer.writeTrailingSemicolon(";");
  15438. pendingTrailingSemicolon = false;
  15439. }
  15440. }
  15441. return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
  15442. pendingTrailingSemicolon = true;
  15443. },
  15444. writeLiteral: function (s) {
  15445. commitPendingTrailingSemicolon();
  15446. writer.writeLiteral(s);
  15447. },
  15448. writeStringLiteral: function (s) {
  15449. commitPendingTrailingSemicolon();
  15450. writer.writeStringLiteral(s);
  15451. },
  15452. writeSymbol: function (s, sym) {
  15453. commitPendingTrailingSemicolon();
  15454. writer.writeSymbol(s, sym);
  15455. },
  15456. writePunctuation: function (s) {
  15457. commitPendingTrailingSemicolon();
  15458. writer.writePunctuation(s);
  15459. },
  15460. writeKeyword: function (s) {
  15461. commitPendingTrailingSemicolon();
  15462. writer.writeKeyword(s);
  15463. },
  15464. writeOperator: function (s) {
  15465. commitPendingTrailingSemicolon();
  15466. writer.writeOperator(s);
  15467. },
  15468. writeParameter: function (s) {
  15469. commitPendingTrailingSemicolon();
  15470. writer.writeParameter(s);
  15471. },
  15472. writeSpace: function (s) {
  15473. commitPendingTrailingSemicolon();
  15474. writer.writeSpace(s);
  15475. },
  15476. writeProperty: function (s) {
  15477. commitPendingTrailingSemicolon();
  15478. writer.writeProperty(s);
  15479. },
  15480. writeComment: function (s) {
  15481. commitPendingTrailingSemicolon();
  15482. writer.writeComment(s);
  15483. },
  15484. writeLine: function () {
  15485. commitPendingTrailingSemicolon();
  15486. writer.writeLine();
  15487. },
  15488. increaseIndent: function () {
  15489. commitPendingTrailingSemicolon();
  15490. writer.increaseIndent();
  15491. },
  15492. decreaseIndent: function () {
  15493. commitPendingTrailingSemicolon();
  15494. writer.decreaseIndent();
  15495. } });
  15496. }
  15497. ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
  15498. function getResolvedExternalModuleName(host, file, referenceFile) {
  15499. return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
  15500. }
  15501. ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
  15502. function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
  15503. var file = resolver.getExternalModuleFileFromDeclaration(declaration);
  15504. if (!file || file.isDeclarationFile) {
  15505. return undefined;
  15506. }
  15507. return getResolvedExternalModuleName(host, file);
  15508. }
  15509. ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
  15510. /**
  15511. * Resolves a local path to a path which is absolute to the base of the emit
  15512. */
  15513. function getExternalModuleNameFromPath(host, fileName, referencePath) {
  15514. var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
  15515. var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
  15516. var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
  15517. var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
  15518. var extensionless = removeFileExtension(relativePath);
  15519. return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
  15520. }
  15521. ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
  15522. function getOwnEmitOutputFilePath(fileName, host, extension) {
  15523. var compilerOptions = host.getCompilerOptions();
  15524. var emitOutputFilePathWithoutExtension;
  15525. if (compilerOptions.outDir) {
  15526. emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
  15527. }
  15528. else {
  15529. emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
  15530. }
  15531. return emitOutputFilePathWithoutExtension + extension;
  15532. }
  15533. ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
  15534. function getDeclarationEmitOutputFilePath(fileName, host) {
  15535. return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
  15536. }
  15537. ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
  15538. function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
  15539. var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
  15540. var path = outputDir
  15541. ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
  15542. : fileName;
  15543. return removeFileExtension(path) + ".d.ts" /* Dts */;
  15544. }
  15545. ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
  15546. /**
  15547. * Gets the source files that are expected to have an emit output.
  15548. *
  15549. * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
  15550. * transformations.
  15551. *
  15552. * @param host An EmitHost.
  15553. * @param targetSourceFile An optional target source file to emit.
  15554. */
  15555. function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
  15556. var options = host.getCompilerOptions();
  15557. if (options.outFile || options.out) {
  15558. var moduleKind = getEmitModuleKind(options);
  15559. var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
  15560. // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
  15561. return ts.filter(host.getSourceFiles(), function (sourceFile) {
  15562. return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
  15563. sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
  15564. });
  15565. }
  15566. else {
  15567. var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
  15568. return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
  15569. }
  15570. }
  15571. ts.getSourceFilesToEmit = getSourceFilesToEmit;
  15572. /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
  15573. function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
  15574. var options = host.getCompilerOptions();
  15575. return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
  15576. !sourceFile.isDeclarationFile &&
  15577. !host.isSourceFileFromExternalLibrary(sourceFile) &&
  15578. !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
  15579. (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
  15580. }
  15581. ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
  15582. function getSourceFilePathInNewDir(fileName, host, newDirPath) {
  15583. return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
  15584. }
  15585. ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
  15586. function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
  15587. var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
  15588. var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
  15589. sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
  15590. return ts.combinePaths(newDirPath, sourceFilePath);
  15591. }
  15592. ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
  15593. function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
  15594. host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
  15595. diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
  15596. }, sourceFiles);
  15597. }
  15598. ts.writeFile = writeFile;
  15599. function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
  15600. if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
  15601. var parentDirectory = ts.getDirectoryPath(directoryPath);
  15602. ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
  15603. createDirectory(directoryPath);
  15604. }
  15605. }
  15606. function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
  15607. // PERF: Checking for directory existence is expensive. Instead, assume the directory exists
  15608. // and fall back to creating it if the file write fails.
  15609. try {
  15610. writeFile(path, data, writeByteOrderMark);
  15611. }
  15612. catch (_a) {
  15613. ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
  15614. writeFile(path, data, writeByteOrderMark);
  15615. }
  15616. }
  15617. ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
  15618. function getLineOfLocalPosition(currentSourceFile, pos) {
  15619. return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
  15620. }
  15621. ts.getLineOfLocalPosition = getLineOfLocalPosition;
  15622. function getLineOfLocalPositionFromLineMap(lineMap, pos) {
  15623. return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
  15624. }
  15625. ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
  15626. function getFirstConstructorWithBody(node) {
  15627. return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
  15628. }
  15629. ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
  15630. function getSetAccessorValueParameter(accessor) {
  15631. if (accessor && accessor.parameters.length > 0) {
  15632. var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
  15633. return accessor.parameters[hasThis ? 1 : 0];
  15634. }
  15635. }
  15636. ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
  15637. /** Get the type annotation for the value parameter. */
  15638. function getSetAccessorTypeAnnotationNode(accessor) {
  15639. var parameter = getSetAccessorValueParameter(accessor);
  15640. return parameter && parameter.type;
  15641. }
  15642. ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
  15643. function getThisParameter(signature) {
  15644. // callback tags do not currently support this parameters
  15645. if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
  15646. var thisParameter = signature.parameters[0];
  15647. if (parameterIsThisKeyword(thisParameter)) {
  15648. return thisParameter;
  15649. }
  15650. }
  15651. }
  15652. ts.getThisParameter = getThisParameter;
  15653. function parameterIsThisKeyword(parameter) {
  15654. return isThisIdentifier(parameter.name);
  15655. }
  15656. ts.parameterIsThisKeyword = parameterIsThisKeyword;
  15657. function isThisIdentifier(node) {
  15658. return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
  15659. }
  15660. ts.isThisIdentifier = isThisIdentifier;
  15661. function identifierIsThisKeyword(id) {
  15662. return id.originalKeywordKind === 104 /* ThisKeyword */;
  15663. }
  15664. ts.identifierIsThisKeyword = identifierIsThisKeyword;
  15665. function getAllAccessorDeclarations(declarations, accessor) {
  15666. // TODO: GH#18217
  15667. var firstAccessor;
  15668. var secondAccessor;
  15669. var getAccessor;
  15670. var setAccessor;
  15671. if (hasDynamicName(accessor)) {
  15672. firstAccessor = accessor;
  15673. if (accessor.kind === 163 /* GetAccessor */) {
  15674. getAccessor = accessor;
  15675. }
  15676. else if (accessor.kind === 164 /* SetAccessor */) {
  15677. setAccessor = accessor;
  15678. }
  15679. else {
  15680. ts.Debug.fail("Accessor has wrong kind");
  15681. }
  15682. }
  15683. else {
  15684. ts.forEach(declarations, function (member) {
  15685. if (ts.isAccessor(member)
  15686. && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
  15687. var memberName = getPropertyNameForPropertyNameNode(member.name);
  15688. var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
  15689. if (memberName === accessorName) {
  15690. if (!firstAccessor) {
  15691. firstAccessor = member;
  15692. }
  15693. else if (!secondAccessor) {
  15694. secondAccessor = member;
  15695. }
  15696. if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
  15697. getAccessor = member;
  15698. }
  15699. if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
  15700. setAccessor = member;
  15701. }
  15702. }
  15703. }
  15704. });
  15705. }
  15706. return {
  15707. firstAccessor: firstAccessor,
  15708. secondAccessor: secondAccessor,
  15709. getAccessor: getAccessor,
  15710. setAccessor: setAccessor
  15711. };
  15712. }
  15713. ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
  15714. /**
  15715. * Gets the effective type annotation of a variable, parameter, or property. If the node was
  15716. * parsed in a JavaScript file, gets the type annotation from JSDoc. Also gets the type of
  15717. * functions only the JSDoc case.
  15718. */
  15719. function getEffectiveTypeAnnotationNode(node) {
  15720. if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
  15721. return undefined;
  15722. var type = node.type;
  15723. if (type || !isInJSFile(node))
  15724. return type;
  15725. return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
  15726. }
  15727. ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
  15728. function getTypeAnnotationNode(node) {
  15729. return node.type;
  15730. }
  15731. ts.getTypeAnnotationNode = getTypeAnnotationNode;
  15732. /**
  15733. * Gets the effective return type annotation of a signature. If the node was parsed in a
  15734. * JavaScript file, gets the return type annotation from JSDoc.
  15735. */
  15736. function getEffectiveReturnTypeNode(node) {
  15737. return ts.isJSDocSignature(node) ?
  15738. node.type && node.type.typeExpression && node.type.typeExpression.type :
  15739. node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
  15740. }
  15741. ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
  15742. function getJSDocTypeParameterDeclarations(node) {
  15743. return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
  15744. }
  15745. ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
  15746. /** template tags are only available when a typedef isn't already using them */
  15747. function isNonTypeAliasTemplate(tag) {
  15748. return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
  15749. }
  15750. /**
  15751. * Gets the effective type annotation of the value parameter of a set accessor. If the node
  15752. * was parsed in a JavaScript file, gets the type annotation from JSDoc.
  15753. */
  15754. function getEffectiveSetAccessorTypeAnnotationNode(node) {
  15755. var parameter = getSetAccessorValueParameter(node);
  15756. return parameter && getEffectiveTypeAnnotationNode(parameter);
  15757. }
  15758. ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
  15759. function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
  15760. emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
  15761. }
  15762. ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
  15763. function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
  15764. // If the leading comments start on different line than the start of node, write new line
  15765. if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
  15766. getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
  15767. writer.writeLine();
  15768. }
  15769. }
  15770. ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
  15771. function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
  15772. // If the leading comments start on different line than the start of node, write new line
  15773. if (pos !== commentPos &&
  15774. getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
  15775. writer.writeLine();
  15776. }
  15777. }
  15778. ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
  15779. function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
  15780. if (comments && comments.length > 0) {
  15781. if (leadingSeparator) {
  15782. writer.writeSpace(" ");
  15783. }
  15784. var emitInterveningSeparator = false;
  15785. for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
  15786. var comment = comments_1[_i];
  15787. if (emitInterveningSeparator) {
  15788. writer.writeSpace(" ");
  15789. emitInterveningSeparator = false;
  15790. }
  15791. writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
  15792. if (comment.hasTrailingNewLine) {
  15793. writer.writeLine();
  15794. }
  15795. else {
  15796. emitInterveningSeparator = true;
  15797. }
  15798. }
  15799. if (emitInterveningSeparator && trailingSeparator) {
  15800. writer.writeSpace(" ");
  15801. }
  15802. }
  15803. }
  15804. ts.emitComments = emitComments;
  15805. /**
  15806. * Detached comment is a comment at the top of file or function body that is separated from
  15807. * the next statement by space.
  15808. */
  15809. function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
  15810. var leadingComments;
  15811. var currentDetachedCommentInfo;
  15812. if (removeComments) {
  15813. // removeComments is true, only reserve pinned comment at the top of file
  15814. // For example:
  15815. // /*! Pinned Comment */
  15816. //
  15817. // var x = 10;
  15818. if (node.pos === 0) {
  15819. leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
  15820. }
  15821. }
  15822. else {
  15823. // removeComments is false, just get detached as normal and bypass the process to filter comment
  15824. leadingComments = ts.getLeadingCommentRanges(text, node.pos);
  15825. }
  15826. if (leadingComments) {
  15827. var detachedComments = [];
  15828. var lastComment = void 0;
  15829. for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
  15830. var comment = leadingComments_1[_i];
  15831. if (lastComment) {
  15832. var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
  15833. var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
  15834. if (commentLine >= lastCommentLine + 2) {
  15835. // There was a blank line between the last comment and this comment. This
  15836. // comment is not part of the copyright comments. Return what we have so
  15837. // far.
  15838. break;
  15839. }
  15840. }
  15841. detachedComments.push(comment);
  15842. lastComment = comment;
  15843. }
  15844. if (detachedComments.length) {
  15845. // All comments look like they could have been part of the copyright header. Make
  15846. // sure there is at least one blank line between it and the node. If not, it's not
  15847. // a copyright header.
  15848. var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
  15849. var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
  15850. if (nodeLine >= lastCommentLine + 2) {
  15851. // Valid detachedComments
  15852. emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
  15853. emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
  15854. currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
  15855. }
  15856. }
  15857. }
  15858. return currentDetachedCommentInfo;
  15859. function isPinnedCommentLocal(comment) {
  15860. return isPinnedComment(text, comment.pos);
  15861. }
  15862. }
  15863. ts.emitDetachedComments = emitDetachedComments;
  15864. function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
  15865. if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
  15866. var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
  15867. var lineCount = lineMap.length;
  15868. var firstCommentLineIndent = void 0;
  15869. for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
  15870. var nextLineStart = (currentLine + 1) === lineCount
  15871. ? text.length + 1
  15872. : lineMap[currentLine + 1];
  15873. if (pos !== commentPos) {
  15874. // If we are not emitting first line, we need to write the spaces to adjust the alignment
  15875. if (firstCommentLineIndent === undefined) {
  15876. firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
  15877. }
  15878. // These are number of spaces writer is going to write at current indent
  15879. var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
  15880. // Number of spaces we want to be writing
  15881. // eg: Assume writer indent
  15882. // module m {
  15883. // /* starts at character 9 this is line 1
  15884. // * starts at character pos 4 line --1 = 8 - 8 + 3
  15885. // More left indented comment */ --2 = 8 - 8 + 2
  15886. // class c { }
  15887. // }
  15888. // module m {
  15889. // /* this is line 1 -- Assume current writer indent 8
  15890. // * line --3 = 8 - 4 + 5
  15891. // More right indented comment */ --4 = 8 - 4 + 11
  15892. // class c { }
  15893. // }
  15894. var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
  15895. if (spacesToEmit > 0) {
  15896. var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
  15897. var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
  15898. // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
  15899. writer.rawWrite(indentSizeSpaceString);
  15900. // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
  15901. while (numberOfSingleSpacesToEmit) {
  15902. writer.rawWrite(" ");
  15903. numberOfSingleSpacesToEmit--;
  15904. }
  15905. }
  15906. else {
  15907. // No spaces to emit write empty string
  15908. writer.rawWrite("");
  15909. }
  15910. }
  15911. // Write the comment line text
  15912. writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
  15913. pos = nextLineStart;
  15914. }
  15915. }
  15916. else {
  15917. // Single line comment of style //....
  15918. writer.writeComment(text.substring(commentPos, commentEnd));
  15919. }
  15920. }
  15921. ts.writeCommentRange = writeCommentRange;
  15922. function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
  15923. var end = Math.min(commentEnd, nextLineStart - 1);
  15924. var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
  15925. if (currentLineText) {
  15926. // trimmed forward and ending spaces text
  15927. writer.writeComment(currentLineText);
  15928. if (end !== commentEnd) {
  15929. writer.writeLine();
  15930. }
  15931. }
  15932. else {
  15933. // Empty string - make sure we write empty line
  15934. writer.rawWrite(newLine);
  15935. }
  15936. }
  15937. function calculateIndent(text, pos, end) {
  15938. var currentLineIndent = 0;
  15939. for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
  15940. if (text.charCodeAt(pos) === 9 /* tab */) {
  15941. // Tabs = TabSize = indent size and go to next tabStop
  15942. currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
  15943. }
  15944. else {
  15945. // Single space
  15946. currentLineIndent++;
  15947. }
  15948. }
  15949. return currentLineIndent;
  15950. }
  15951. function hasModifiers(node) {
  15952. return getModifierFlags(node) !== 0 /* None */;
  15953. }
  15954. ts.hasModifiers = hasModifiers;
  15955. function hasModifier(node, flags) {
  15956. return !!getSelectedModifierFlags(node, flags);
  15957. }
  15958. ts.hasModifier = hasModifier;
  15959. function hasStaticModifier(node) {
  15960. return hasModifier(node, 32 /* Static */);
  15961. }
  15962. ts.hasStaticModifier = hasStaticModifier;
  15963. function hasReadonlyModifier(node) {
  15964. return hasModifier(node, 64 /* Readonly */);
  15965. }
  15966. ts.hasReadonlyModifier = hasReadonlyModifier;
  15967. function getSelectedModifierFlags(node, flags) {
  15968. return getModifierFlags(node) & flags;
  15969. }
  15970. ts.getSelectedModifierFlags = getSelectedModifierFlags;
  15971. function getModifierFlags(node) {
  15972. if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
  15973. return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
  15974. }
  15975. var flags = getModifierFlagsNoCache(node);
  15976. node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
  15977. return flags;
  15978. }
  15979. ts.getModifierFlags = getModifierFlags;
  15980. function getModifierFlagsNoCache(node) {
  15981. var flags = 0 /* None */;
  15982. if (node.modifiers) {
  15983. for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
  15984. var modifier = _a[_i];
  15985. flags |= modifierToFlag(modifier.kind);
  15986. }
  15987. }
  15988. if (isInJSFile(node) && !!node.parent) {
  15989. // getModifierFlagsNoCache should only be called when parent pointers are set,
  15990. // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
  15991. var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
  15992. | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
  15993. | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
  15994. | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
  15995. flags |= tags;
  15996. }
  15997. if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
  15998. flags |= 1 /* Export */;
  15999. }
  16000. return flags;
  16001. }
  16002. ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
  16003. function modifierToFlag(token) {
  16004. switch (token) {
  16005. case 120 /* StaticKeyword */: return 32 /* Static */;
  16006. case 119 /* PublicKeyword */: return 4 /* Public */;
  16007. case 118 /* ProtectedKeyword */: return 16 /* Protected */;
  16008. case 117 /* PrivateKeyword */: return 8 /* Private */;
  16009. case 122 /* AbstractKeyword */: return 128 /* Abstract */;
  16010. case 89 /* ExportKeyword */: return 1 /* Export */;
  16011. case 130 /* DeclareKeyword */: return 2 /* Ambient */;
  16012. case 81 /* ConstKeyword */: return 2048 /* Const */;
  16013. case 84 /* DefaultKeyword */: return 512 /* Default */;
  16014. case 126 /* AsyncKeyword */: return 256 /* Async */;
  16015. case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
  16016. }
  16017. return 0 /* None */;
  16018. }
  16019. ts.modifierToFlag = modifierToFlag;
  16020. function isLogicalOperator(token) {
  16021. return token === 56 /* BarBarToken */
  16022. || token === 55 /* AmpersandAmpersandToken */
  16023. || token === 53 /* ExclamationToken */;
  16024. }
  16025. ts.isLogicalOperator = isLogicalOperator;
  16026. function isAssignmentOperator(token) {
  16027. return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
  16028. }
  16029. ts.isAssignmentOperator = isAssignmentOperator;
  16030. /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
  16031. function tryGetClassExtendingExpressionWithTypeArguments(node) {
  16032. var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
  16033. return cls && !cls.isImplements ? cls.class : undefined;
  16034. }
  16035. ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
  16036. function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
  16037. return ts.isExpressionWithTypeArguments(node)
  16038. && ts.isHeritageClause(node.parent)
  16039. && ts.isClassLike(node.parent.parent)
  16040. ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
  16041. : undefined;
  16042. }
  16043. ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
  16044. function isAssignmentExpression(node, excludeCompoundAssignment) {
  16045. return ts.isBinaryExpression(node)
  16046. && (excludeCompoundAssignment
  16047. ? node.operatorToken.kind === 62 /* EqualsToken */
  16048. : isAssignmentOperator(node.operatorToken.kind))
  16049. && ts.isLeftHandSideExpression(node.left);
  16050. }
  16051. ts.isAssignmentExpression = isAssignmentExpression;
  16052. function isDestructuringAssignment(node) {
  16053. if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
  16054. var kind = node.left.kind;
  16055. return kind === 193 /* ObjectLiteralExpression */
  16056. || kind === 192 /* ArrayLiteralExpression */;
  16057. }
  16058. return false;
  16059. }
  16060. ts.isDestructuringAssignment = isDestructuringAssignment;
  16061. function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
  16062. return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
  16063. }
  16064. ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
  16065. function isEntityNameExpression(node) {
  16066. return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
  16067. }
  16068. ts.isEntityNameExpression = isEntityNameExpression;
  16069. function getFirstIdentifier(node) {
  16070. switch (node.kind) {
  16071. case 75 /* Identifier */:
  16072. return node;
  16073. case 153 /* QualifiedName */:
  16074. do {
  16075. node = node.left;
  16076. } while (node.kind !== 75 /* Identifier */);
  16077. return node;
  16078. case 194 /* PropertyAccessExpression */:
  16079. do {
  16080. node = node.expression;
  16081. } while (node.kind !== 75 /* Identifier */);
  16082. return node;
  16083. }
  16084. }
  16085. ts.getFirstIdentifier = getFirstIdentifier;
  16086. function isDottedName(node) {
  16087. return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
  16088. node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
  16089. node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
  16090. }
  16091. ts.isDottedName = isDottedName;
  16092. function isPropertyAccessEntityNameExpression(node) {
  16093. return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression);
  16094. }
  16095. ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
  16096. function tryGetPropertyAccessOrIdentifierToString(expr) {
  16097. if (ts.isPropertyAccessExpression(expr)) {
  16098. var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
  16099. if (baseStr !== undefined) {
  16100. return baseStr + "." + expr.name;
  16101. }
  16102. }
  16103. else if (ts.isIdentifier(expr)) {
  16104. return ts.unescapeLeadingUnderscores(expr.escapedText);
  16105. }
  16106. return undefined;
  16107. }
  16108. ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
  16109. function isPrototypeAccess(node) {
  16110. return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
  16111. }
  16112. ts.isPrototypeAccess = isPrototypeAccess;
  16113. function isRightSideOfQualifiedNameOrPropertyAccess(node) {
  16114. return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
  16115. (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
  16116. }
  16117. ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
  16118. function isEmptyObjectLiteral(expression) {
  16119. return expression.kind === 193 /* ObjectLiteralExpression */ &&
  16120. expression.properties.length === 0;
  16121. }
  16122. ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
  16123. function isEmptyArrayLiteral(expression) {
  16124. return expression.kind === 192 /* ArrayLiteralExpression */ &&
  16125. expression.elements.length === 0;
  16126. }
  16127. ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
  16128. function getLocalSymbolForExportDefault(symbol) {
  16129. return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
  16130. }
  16131. ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
  16132. function isExportDefaultSymbol(symbol) {
  16133. return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
  16134. }
  16135. /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
  16136. function tryExtractTSExtension(fileName) {
  16137. return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
  16138. }
  16139. ts.tryExtractTSExtension = tryExtractTSExtension;
  16140. /**
  16141. * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
  16142. * representing the UTF-8 encoding of the character, and return the expanded char code list.
  16143. */
  16144. function getExpandedCharCodes(input) {
  16145. var output = [];
  16146. var length = input.length;
  16147. for (var i = 0; i < length; i++) {
  16148. var charCode = input.charCodeAt(i);
  16149. // handle utf8
  16150. if (charCode < 0x80) {
  16151. output.push(charCode);
  16152. }
  16153. else if (charCode < 0x800) {
  16154. output.push((charCode >> 6) | 192);
  16155. output.push((charCode & 63) | 128);
  16156. }
  16157. else if (charCode < 0x10000) {
  16158. output.push((charCode >> 12) | 224);
  16159. output.push(((charCode >> 6) & 63) | 128);
  16160. output.push((charCode & 63) | 128);
  16161. }
  16162. else if (charCode < 0x20000) {
  16163. output.push((charCode >> 18) | 240);
  16164. output.push(((charCode >> 12) & 63) | 128);
  16165. output.push(((charCode >> 6) & 63) | 128);
  16166. output.push((charCode & 63) | 128);
  16167. }
  16168. else {
  16169. ts.Debug.assert(false, "Unexpected code point");
  16170. }
  16171. }
  16172. return output;
  16173. }
  16174. var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  16175. /**
  16176. * Converts a string to a base-64 encoded ASCII string.
  16177. */
  16178. function convertToBase64(input) {
  16179. var result = "";
  16180. var charCodes = getExpandedCharCodes(input);
  16181. var i = 0;
  16182. var length = charCodes.length;
  16183. var byte1, byte2, byte3, byte4;
  16184. while (i < length) {
  16185. // Convert every 6-bits in the input 3 character points
  16186. // into a base64 digit
  16187. byte1 = charCodes[i] >> 2;
  16188. byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
  16189. byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
  16190. byte4 = charCodes[i + 2] & 63;
  16191. // We are out of characters in the input, set the extra
  16192. // digits to 64 (padding character).
  16193. if (i + 1 >= length) {
  16194. byte3 = byte4 = 64;
  16195. }
  16196. else if (i + 2 >= length) {
  16197. byte4 = 64;
  16198. }
  16199. // Write to the output
  16200. result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
  16201. i += 3;
  16202. }
  16203. return result;
  16204. }
  16205. ts.convertToBase64 = convertToBase64;
  16206. function getStringFromExpandedCharCodes(codes) {
  16207. var output = "";
  16208. var i = 0;
  16209. var length = codes.length;
  16210. while (i < length) {
  16211. var charCode = codes[i];
  16212. if (charCode < 0x80) {
  16213. output += String.fromCharCode(charCode);
  16214. i++;
  16215. }
  16216. else if ((charCode & 192) === 192) {
  16217. var value = charCode & 63;
  16218. i++;
  16219. var nextCode = codes[i];
  16220. while ((nextCode & 192) === 128) {
  16221. value = (value << 6) | (nextCode & 63);
  16222. i++;
  16223. nextCode = codes[i];
  16224. }
  16225. // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
  16226. output += String.fromCharCode(value);
  16227. }
  16228. else {
  16229. // We don't want to kill the process when decoding fails (due to a following char byte not
  16230. // following a leading char), so we just print the (bad) value
  16231. output += String.fromCharCode(charCode);
  16232. i++;
  16233. }
  16234. }
  16235. return output;
  16236. }
  16237. function base64encode(host, input) {
  16238. if (host && host.base64encode) {
  16239. return host.base64encode(input);
  16240. }
  16241. return convertToBase64(input);
  16242. }
  16243. ts.base64encode = base64encode;
  16244. function base64decode(host, input) {
  16245. if (host && host.base64decode) {
  16246. return host.base64decode(input);
  16247. }
  16248. var length = input.length;
  16249. var expandedCharCodes = [];
  16250. var i = 0;
  16251. while (i < length) {
  16252. // Stop decoding once padding characters are present
  16253. if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
  16254. break;
  16255. }
  16256. // convert 4 input digits into three characters, ignoring padding characters at the end
  16257. var ch1 = base64Digits.indexOf(input[i]);
  16258. var ch2 = base64Digits.indexOf(input[i + 1]);
  16259. var ch3 = base64Digits.indexOf(input[i + 2]);
  16260. var ch4 = base64Digits.indexOf(input[i + 3]);
  16261. var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
  16262. var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
  16263. var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
  16264. if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
  16265. expandedCharCodes.push(code1);
  16266. }
  16267. else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
  16268. expandedCharCodes.push(code1, code2);
  16269. }
  16270. else {
  16271. expandedCharCodes.push(code1, code2, code3);
  16272. }
  16273. i += 4;
  16274. }
  16275. return getStringFromExpandedCharCodes(expandedCharCodes);
  16276. }
  16277. ts.base64decode = base64decode;
  16278. function readJson(path, host) {
  16279. try {
  16280. var jsonText = host.readFile(path);
  16281. if (!jsonText)
  16282. return {};
  16283. var result = ts.parseConfigFileTextToJson(path, jsonText);
  16284. if (result.error) {
  16285. return {};
  16286. }
  16287. return result.config;
  16288. }
  16289. catch (e) {
  16290. // gracefully handle if readFile fails or returns not JSON
  16291. return {};
  16292. }
  16293. }
  16294. ts.readJson = readJson;
  16295. function directoryProbablyExists(directoryName, host) {
  16296. // if host does not support 'directoryExists' assume that directory will exist
  16297. return !host.directoryExists || host.directoryExists(directoryName);
  16298. }
  16299. ts.directoryProbablyExists = directoryProbablyExists;
  16300. var carriageReturnLineFeed = "\r\n";
  16301. var lineFeed = "\n";
  16302. function getNewLineCharacter(options, getNewLine) {
  16303. switch (options.newLine) {
  16304. case 0 /* CarriageReturnLineFeed */:
  16305. return carriageReturnLineFeed;
  16306. case 1 /* LineFeed */:
  16307. return lineFeed;
  16308. }
  16309. return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
  16310. }
  16311. ts.getNewLineCharacter = getNewLineCharacter;
  16312. /**
  16313. * Creates a new TextRange from the provided pos and end.
  16314. *
  16315. * @param pos The start position.
  16316. * @param end The end position.
  16317. */
  16318. function createRange(pos, end) {
  16319. if (end === void 0) { end = pos; }
  16320. ts.Debug.assert(end >= pos || end === -1);
  16321. return { pos: pos, end: end };
  16322. }
  16323. ts.createRange = createRange;
  16324. /**
  16325. * Creates a new TextRange from a provided range with a new end position.
  16326. *
  16327. * @param range A TextRange.
  16328. * @param end The new end position.
  16329. */
  16330. function moveRangeEnd(range, end) {
  16331. return createRange(range.pos, end);
  16332. }
  16333. ts.moveRangeEnd = moveRangeEnd;
  16334. /**
  16335. * Creates a new TextRange from a provided range with a new start position.
  16336. *
  16337. * @param range A TextRange.
  16338. * @param pos The new Start position.
  16339. */
  16340. function moveRangePos(range, pos) {
  16341. return createRange(pos, range.end);
  16342. }
  16343. ts.moveRangePos = moveRangePos;
  16344. /**
  16345. * Moves the start position of a range past any decorators.
  16346. */
  16347. function moveRangePastDecorators(node) {
  16348. return node.decorators && node.decorators.length > 0
  16349. ? moveRangePos(node, node.decorators.end)
  16350. : node;
  16351. }
  16352. ts.moveRangePastDecorators = moveRangePastDecorators;
  16353. /**
  16354. * Moves the start position of a range past any decorators or modifiers.
  16355. */
  16356. function moveRangePastModifiers(node) {
  16357. return node.modifiers && node.modifiers.length > 0
  16358. ? moveRangePos(node, node.modifiers.end)
  16359. : moveRangePastDecorators(node);
  16360. }
  16361. ts.moveRangePastModifiers = moveRangePastModifiers;
  16362. /**
  16363. * Determines whether a TextRange has the same start and end positions.
  16364. *
  16365. * @param range A TextRange.
  16366. */
  16367. function isCollapsedRange(range) {
  16368. return range.pos === range.end;
  16369. }
  16370. ts.isCollapsedRange = isCollapsedRange;
  16371. /**
  16372. * Creates a new TextRange for a token at the provides start position.
  16373. *
  16374. * @param pos The start position.
  16375. * @param token The token.
  16376. */
  16377. function createTokenRange(pos, token) {
  16378. return createRange(pos, pos + ts.tokenToString(token).length);
  16379. }
  16380. ts.createTokenRange = createTokenRange;
  16381. function rangeIsOnSingleLine(range, sourceFile) {
  16382. return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
  16383. }
  16384. ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
  16385. function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
  16386. return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile);
  16387. }
  16388. ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
  16389. function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
  16390. return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
  16391. }
  16392. ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
  16393. function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
  16394. return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile);
  16395. }
  16396. ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
  16397. function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
  16398. return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile);
  16399. }
  16400. ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
  16401. function isNodeArrayMultiLine(list, sourceFile) {
  16402. return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
  16403. }
  16404. ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
  16405. function positionsAreOnSameLine(pos1, pos2, sourceFile) {
  16406. return pos1 === pos2 ||
  16407. getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2);
  16408. }
  16409. ts.positionsAreOnSameLine = positionsAreOnSameLine;
  16410. function getStartPositionOfRange(range, sourceFile) {
  16411. return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
  16412. }
  16413. ts.getStartPositionOfRange = getStartPositionOfRange;
  16414. /**
  16415. * Determines whether a name was originally the declaration name of an enum or namespace
  16416. * declaration.
  16417. */
  16418. function isDeclarationNameOfEnumOrNamespace(node) {
  16419. var parseNode = ts.getParseTreeNode(node);
  16420. if (parseNode) {
  16421. switch (parseNode.parent.kind) {
  16422. case 248 /* EnumDeclaration */:
  16423. case 249 /* ModuleDeclaration */:
  16424. return parseNode === parseNode.parent.name;
  16425. }
  16426. }
  16427. return false;
  16428. }
  16429. ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
  16430. function getInitializedVariables(node) {
  16431. return ts.filter(node.declarations, isInitializedVariable);
  16432. }
  16433. ts.getInitializedVariables = getInitializedVariables;
  16434. function isInitializedVariable(node) {
  16435. return node.initializer !== undefined;
  16436. }
  16437. function isWatchSet(options) {
  16438. // Firefox has Object.prototype.watch
  16439. return options.watch && options.hasOwnProperty("watch");
  16440. }
  16441. ts.isWatchSet = isWatchSet;
  16442. function closeFileWatcher(watcher) {
  16443. watcher.close();
  16444. }
  16445. ts.closeFileWatcher = closeFileWatcher;
  16446. function getCheckFlags(symbol) {
  16447. return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
  16448. }
  16449. ts.getCheckFlags = getCheckFlags;
  16450. function getDeclarationModifierFlagsFromSymbol(s) {
  16451. if (s.valueDeclaration) {
  16452. var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
  16453. return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
  16454. }
  16455. if (getCheckFlags(s) & 6 /* Synthetic */) {
  16456. var checkFlags = s.checkFlags;
  16457. var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
  16458. checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
  16459. 16 /* Protected */;
  16460. var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
  16461. return accessModifier | staticModifier;
  16462. }
  16463. if (s.flags & 4194304 /* Prototype */) {
  16464. return 4 /* Public */ | 32 /* Static */;
  16465. }
  16466. return 0;
  16467. }
  16468. ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
  16469. function skipAlias(symbol, checker) {
  16470. return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
  16471. }
  16472. ts.skipAlias = skipAlias;
  16473. /** See comment on `declareModuleMember` in `binder.ts`. */
  16474. function getCombinedLocalAndExportSymbolFlags(symbol) {
  16475. return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
  16476. }
  16477. ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
  16478. function isWriteOnlyAccess(node) {
  16479. return accessKind(node) === 1 /* Write */;
  16480. }
  16481. ts.isWriteOnlyAccess = isWriteOnlyAccess;
  16482. function isWriteAccess(node) {
  16483. return accessKind(node) !== 0 /* Read */;
  16484. }
  16485. ts.isWriteAccess = isWriteAccess;
  16486. var AccessKind;
  16487. (function (AccessKind) {
  16488. /** Only reads from a variable. */
  16489. AccessKind[AccessKind["Read"] = 0] = "Read";
  16490. /** Only writes to a variable without using the result. E.g.: `x++;`. */
  16491. AccessKind[AccessKind["Write"] = 1] = "Write";
  16492. /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
  16493. AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
  16494. })(AccessKind || (AccessKind = {}));
  16495. function accessKind(node) {
  16496. var parent = node.parent;
  16497. if (!parent)
  16498. return 0 /* Read */;
  16499. switch (parent.kind) {
  16500. case 200 /* ParenthesizedExpression */:
  16501. return accessKind(parent);
  16502. case 208 /* PostfixUnaryExpression */:
  16503. case 207 /* PrefixUnaryExpression */:
  16504. var operator = parent.operator;
  16505. return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
  16506. case 209 /* BinaryExpression */:
  16507. var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
  16508. return left === node && isAssignmentOperator(operatorToken.kind) ?
  16509. operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
  16510. : 0 /* Read */;
  16511. case 194 /* PropertyAccessExpression */:
  16512. return parent.name !== node ? 0 /* Read */ : accessKind(parent);
  16513. case 281 /* PropertyAssignment */: {
  16514. var parentAccess = accessKind(parent.parent);
  16515. // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
  16516. return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
  16517. }
  16518. case 282 /* ShorthandPropertyAssignment */:
  16519. // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
  16520. return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
  16521. case 192 /* ArrayLiteralExpression */:
  16522. return accessKind(parent);
  16523. default:
  16524. return 0 /* Read */;
  16525. }
  16526. function writeOrReadWrite() {
  16527. // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
  16528. return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
  16529. }
  16530. }
  16531. function reverseAccessKind(a) {
  16532. switch (a) {
  16533. case 0 /* Read */:
  16534. return 1 /* Write */;
  16535. case 1 /* Write */:
  16536. return 0 /* Read */;
  16537. case 2 /* ReadWrite */:
  16538. return 2 /* ReadWrite */;
  16539. default:
  16540. return ts.Debug.assertNever(a);
  16541. }
  16542. }
  16543. function compareDataObjects(dst, src) {
  16544. if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
  16545. return false;
  16546. }
  16547. for (var e in dst) {
  16548. if (typeof dst[e] === "object") {
  16549. if (!compareDataObjects(dst[e], src[e])) {
  16550. return false;
  16551. }
  16552. }
  16553. else if (typeof dst[e] !== "function") {
  16554. if (dst[e] !== src[e]) {
  16555. return false;
  16556. }
  16557. }
  16558. }
  16559. return true;
  16560. }
  16561. ts.compareDataObjects = compareDataObjects;
  16562. /**
  16563. * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
  16564. */
  16565. function clearMap(map, onDeleteValue) {
  16566. // Remove all
  16567. map.forEach(onDeleteValue);
  16568. map.clear();
  16569. }
  16570. ts.clearMap = clearMap;
  16571. /**
  16572. * Mutates the map with newMap such that keys in map will be same as newMap.
  16573. */
  16574. function mutateMapSkippingNewValues(map, newMap, options) {
  16575. var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
  16576. // Needs update
  16577. map.forEach(function (existingValue, key) {
  16578. var valueInNewMap = newMap.get(key);
  16579. // Not present any more in new map, remove it
  16580. if (valueInNewMap === undefined) {
  16581. map.delete(key);
  16582. onDeleteValue(existingValue, key);
  16583. }
  16584. // If present notify about existing values
  16585. else if (onExistingValue) {
  16586. onExistingValue(existingValue, valueInNewMap, key);
  16587. }
  16588. });
  16589. }
  16590. ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
  16591. /**
  16592. * Mutates the map with newMap such that keys in map will be same as newMap.
  16593. */
  16594. function mutateMap(map, newMap, options) {
  16595. // Needs update
  16596. mutateMapSkippingNewValues(map, newMap, options);
  16597. var createNewValue = options.createNewValue;
  16598. // Add new values that are not already present
  16599. newMap.forEach(function (valueInNewMap, key) {
  16600. if (!map.has(key)) {
  16601. // New values
  16602. map.set(key, createNewValue(key, valueInNewMap));
  16603. }
  16604. });
  16605. }
  16606. ts.mutateMap = mutateMap;
  16607. // Return true if the given type is the constructor type for an abstract class
  16608. function isAbstractConstructorType(type) {
  16609. return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
  16610. }
  16611. ts.isAbstractConstructorType = isAbstractConstructorType;
  16612. function isAbstractConstructorSymbol(symbol) {
  16613. if (symbol.flags & 32 /* Class */) {
  16614. var declaration = getClassLikeDeclarationOfSymbol(symbol);
  16615. return !!declaration && hasModifier(declaration, 128 /* Abstract */);
  16616. }
  16617. return false;
  16618. }
  16619. ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
  16620. function getClassLikeDeclarationOfSymbol(symbol) {
  16621. return ts.find(symbol.declarations, ts.isClassLike);
  16622. }
  16623. ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
  16624. function getObjectFlags(type) {
  16625. return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
  16626. }
  16627. ts.getObjectFlags = getObjectFlags;
  16628. function typeHasCallOrConstructSignatures(type, checker) {
  16629. return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
  16630. }
  16631. ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
  16632. function forSomeAncestorDirectory(directory, callback) {
  16633. return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
  16634. }
  16635. ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
  16636. function isUMDExportSymbol(symbol) {
  16637. return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
  16638. }
  16639. ts.isUMDExportSymbol = isUMDExportSymbol;
  16640. function showModuleSpecifier(_a) {
  16641. var moduleSpecifier = _a.moduleSpecifier;
  16642. return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
  16643. }
  16644. ts.showModuleSpecifier = showModuleSpecifier;
  16645. function getLastChild(node) {
  16646. var lastChild;
  16647. ts.forEachChild(node, function (child) {
  16648. if (nodeIsPresent(child))
  16649. lastChild = child;
  16650. }, function (children) {
  16651. // As an optimization, jump straight to the end of the list.
  16652. for (var i = children.length - 1; i >= 0; i--) {
  16653. if (nodeIsPresent(children[i])) {
  16654. lastChild = children[i];
  16655. break;
  16656. }
  16657. }
  16658. });
  16659. return lastChild;
  16660. }
  16661. ts.getLastChild = getLastChild;
  16662. function addToSeen(seen, key, value) {
  16663. if (value === void 0) { value = true; }
  16664. key = String(key);
  16665. if (seen.has(key)) {
  16666. return false;
  16667. }
  16668. seen.set(key, value);
  16669. return true;
  16670. }
  16671. ts.addToSeen = addToSeen;
  16672. function isObjectTypeDeclaration(node) {
  16673. return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
  16674. }
  16675. ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
  16676. function isTypeNodeKind(kind) {
  16677. return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
  16678. || kind === 125 /* AnyKeyword */
  16679. || kind === 148 /* UnknownKeyword */
  16680. || kind === 140 /* NumberKeyword */
  16681. || kind === 151 /* BigIntKeyword */
  16682. || kind === 141 /* ObjectKeyword */
  16683. || kind === 128 /* BooleanKeyword */
  16684. || kind === 143 /* StringKeyword */
  16685. || kind === 144 /* SymbolKeyword */
  16686. || kind === 104 /* ThisKeyword */
  16687. || kind === 110 /* VoidKeyword */
  16688. || kind === 146 /* UndefinedKeyword */
  16689. || kind === 100 /* NullKeyword */
  16690. || kind === 137 /* NeverKeyword */
  16691. || kind === 216 /* ExpressionWithTypeArguments */
  16692. || kind === 295 /* JSDocAllType */
  16693. || kind === 296 /* JSDocUnknownType */
  16694. || kind === 297 /* JSDocNullableType */
  16695. || kind === 298 /* JSDocNonNullableType */
  16696. || kind === 299 /* JSDocOptionalType */
  16697. || kind === 300 /* JSDocFunctionType */
  16698. || kind === 301 /* JSDocVariadicType */;
  16699. }
  16700. ts.isTypeNodeKind = isTypeNodeKind;
  16701. function isAccessExpression(node) {
  16702. return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
  16703. }
  16704. ts.isAccessExpression = isAccessExpression;
  16705. function isBundleFileTextLike(section) {
  16706. switch (section.kind) {
  16707. case "text" /* Text */:
  16708. case "internal" /* Internal */:
  16709. return true;
  16710. default:
  16711. return false;
  16712. }
  16713. }
  16714. ts.isBundleFileTextLike = isBundleFileTextLike;
  16715. function getDotOrQuestionDotToken(node) {
  16716. return node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
  16717. }
  16718. ts.getDotOrQuestionDotToken = getDotOrQuestionDotToken;
  16719. function isNamedImportsOrExports(node) {
  16720. return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
  16721. }
  16722. ts.isNamedImportsOrExports = isNamedImportsOrExports;
  16723. function Symbol(flags, name) {
  16724. this.flags = flags;
  16725. this.escapedName = name;
  16726. this.declarations = undefined;
  16727. this.valueDeclaration = undefined;
  16728. this.id = undefined;
  16729. this.mergeId = undefined;
  16730. this.parent = undefined;
  16731. }
  16732. function Type(checker, flags) {
  16733. this.flags = flags;
  16734. if (ts.Debug.isDebugging) {
  16735. this.checker = checker;
  16736. }
  16737. }
  16738. function Signature(checker, flags) {
  16739. this.flags = flags;
  16740. if (ts.Debug.isDebugging) {
  16741. this.checker = checker;
  16742. }
  16743. }
  16744. function Node(kind, pos, end) {
  16745. this.pos = pos;
  16746. this.end = end;
  16747. this.kind = kind;
  16748. this.id = 0;
  16749. this.flags = 0 /* None */;
  16750. this.modifierFlagsCache = 0 /* None */;
  16751. this.transformFlags = 0 /* None */;
  16752. this.parent = undefined;
  16753. this.original = undefined;
  16754. }
  16755. function SourceMapSource(fileName, text, skipTrivia) {
  16756. this.fileName = fileName;
  16757. this.text = text;
  16758. this.skipTrivia = skipTrivia || (function (pos) { return pos; });
  16759. }
  16760. // eslint-disable-next-line prefer-const
  16761. ts.objectAllocator = {
  16762. getNodeConstructor: function () { return Node; },
  16763. getTokenConstructor: function () { return Node; },
  16764. getIdentifierConstructor: function () { return Node; },
  16765. getPrivateIdentifierConstructor: function () { return Node; },
  16766. getSourceFileConstructor: function () { return Node; },
  16767. getSymbolConstructor: function () { return Symbol; },
  16768. getTypeConstructor: function () { return Type; },
  16769. getSignatureConstructor: function () { return Signature; },
  16770. getSourceMapSourceConstructor: function () { return SourceMapSource; },
  16771. };
  16772. function setObjectAllocator(alloc) {
  16773. ts.objectAllocator = alloc;
  16774. }
  16775. ts.setObjectAllocator = setObjectAllocator;
  16776. function formatStringFromArgs(text, args, baseIndex) {
  16777. if (baseIndex === void 0) { baseIndex = 0; }
  16778. return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); });
  16779. }
  16780. ts.formatStringFromArgs = formatStringFromArgs;
  16781. /* @internal */
  16782. function setLocalizedDiagnosticMessages(messages) {
  16783. ts.localizedDiagnosticMessages = messages;
  16784. }
  16785. ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
  16786. function getLocaleSpecificMessage(message) {
  16787. return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
  16788. }
  16789. ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
  16790. function createFileDiagnostic(file, start, length, message) {
  16791. ts.Debug.assertGreaterThanOrEqual(start, 0);
  16792. ts.Debug.assertGreaterThanOrEqual(length, 0);
  16793. if (file) {
  16794. ts.Debug.assertLessThanOrEqual(start, file.text.length);
  16795. ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
  16796. }
  16797. var text = getLocaleSpecificMessage(message);
  16798. if (arguments.length > 4) {
  16799. text = formatStringFromArgs(text, arguments, 4);
  16800. }
  16801. return {
  16802. file: file,
  16803. start: start,
  16804. length: length,
  16805. messageText: text,
  16806. category: message.category,
  16807. code: message.code,
  16808. reportsUnnecessary: message.reportsUnnecessary,
  16809. };
  16810. }
  16811. ts.createFileDiagnostic = createFileDiagnostic;
  16812. function formatMessage(_dummy, message) {
  16813. var text = getLocaleSpecificMessage(message);
  16814. if (arguments.length > 2) {
  16815. text = formatStringFromArgs(text, arguments, 2);
  16816. }
  16817. return text;
  16818. }
  16819. ts.formatMessage = formatMessage;
  16820. function createCompilerDiagnostic(message) {
  16821. var text = getLocaleSpecificMessage(message);
  16822. if (arguments.length > 1) {
  16823. text = formatStringFromArgs(text, arguments, 1);
  16824. }
  16825. return {
  16826. file: undefined,
  16827. start: undefined,
  16828. length: undefined,
  16829. messageText: text,
  16830. category: message.category,
  16831. code: message.code,
  16832. reportsUnnecessary: message.reportsUnnecessary,
  16833. };
  16834. }
  16835. ts.createCompilerDiagnostic = createCompilerDiagnostic;
  16836. function createCompilerDiagnosticFromMessageChain(chain) {
  16837. return {
  16838. file: undefined,
  16839. start: undefined,
  16840. length: undefined,
  16841. code: chain.code,
  16842. category: chain.category,
  16843. messageText: chain.next ? chain : chain.messageText,
  16844. };
  16845. }
  16846. ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
  16847. function chainDiagnosticMessages(details, message) {
  16848. var text = getLocaleSpecificMessage(message);
  16849. if (arguments.length > 2) {
  16850. text = formatStringFromArgs(text, arguments, 2);
  16851. }
  16852. return {
  16853. messageText: text,
  16854. category: message.category,
  16855. code: message.code,
  16856. next: details === undefined || Array.isArray(details) ? details : [details]
  16857. };
  16858. }
  16859. ts.chainDiagnosticMessages = chainDiagnosticMessages;
  16860. function concatenateDiagnosticMessageChains(headChain, tailChain) {
  16861. var lastChain = headChain;
  16862. while (lastChain.next) {
  16863. lastChain = lastChain.next[0];
  16864. }
  16865. lastChain.next = [tailChain];
  16866. }
  16867. ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
  16868. function getDiagnosticFilePath(diagnostic) {
  16869. return diagnostic.file ? diagnostic.file.path : undefined;
  16870. }
  16871. function compareDiagnostics(d1, d2) {
  16872. return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
  16873. compareRelatedInformation(d1, d2) ||
  16874. 0 /* EqualTo */;
  16875. }
  16876. ts.compareDiagnostics = compareDiagnostics;
  16877. function compareDiagnosticsSkipRelatedInformation(d1, d2) {
  16878. return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
  16879. ts.compareValues(d1.start, d2.start) ||
  16880. ts.compareValues(d1.length, d2.length) ||
  16881. ts.compareValues(d1.code, d2.code) ||
  16882. compareMessageText(d1.messageText, d2.messageText) ||
  16883. 0 /* EqualTo */;
  16884. }
  16885. ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
  16886. function compareRelatedInformation(d1, d2) {
  16887. if (!d1.relatedInformation && !d2.relatedInformation) {
  16888. return 0 /* EqualTo */;
  16889. }
  16890. if (d1.relatedInformation && d2.relatedInformation) {
  16891. return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
  16892. var d2i = d2.relatedInformation[index];
  16893. return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
  16894. }) || 0 /* EqualTo */;
  16895. }
  16896. return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
  16897. }
  16898. function compareMessageText(t1, t2) {
  16899. if (typeof t1 === "string" && typeof t2 === "string") {
  16900. return ts.compareStringsCaseSensitive(t1, t2);
  16901. }
  16902. else if (typeof t1 === "string") {
  16903. return -1 /* LessThan */;
  16904. }
  16905. else if (typeof t2 === "string") {
  16906. return 1 /* GreaterThan */;
  16907. }
  16908. var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
  16909. if (res) {
  16910. return res;
  16911. }
  16912. if (!t1.next && !t2.next) {
  16913. return 0 /* EqualTo */;
  16914. }
  16915. if (!t1.next) {
  16916. return -1 /* LessThan */;
  16917. }
  16918. if (!t2.next) {
  16919. return 1 /* GreaterThan */;
  16920. }
  16921. var len = Math.min(t1.next.length, t2.next.length);
  16922. for (var i = 0; i < len; i++) {
  16923. res = compareMessageText(t1.next[i], t2.next[i]);
  16924. if (res) {
  16925. return res;
  16926. }
  16927. }
  16928. if (t1.next.length < t2.next.length) {
  16929. return -1 /* LessThan */;
  16930. }
  16931. else if (t1.next.length > t2.next.length) {
  16932. return 1 /* GreaterThan */;
  16933. }
  16934. return 0 /* EqualTo */;
  16935. }
  16936. function getEmitScriptTarget(compilerOptions) {
  16937. return compilerOptions.target || 0 /* ES3 */;
  16938. }
  16939. ts.getEmitScriptTarget = getEmitScriptTarget;
  16940. function getEmitModuleKind(compilerOptions) {
  16941. return typeof compilerOptions.module === "number" ?
  16942. compilerOptions.module :
  16943. getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
  16944. }
  16945. ts.getEmitModuleKind = getEmitModuleKind;
  16946. function getEmitModuleResolutionKind(compilerOptions) {
  16947. var moduleResolution = compilerOptions.moduleResolution;
  16948. if (moduleResolution === undefined) {
  16949. moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
  16950. }
  16951. return moduleResolution;
  16952. }
  16953. ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
  16954. function hasJsonModuleEmitEnabled(options) {
  16955. switch (getEmitModuleKind(options)) {
  16956. case ts.ModuleKind.CommonJS:
  16957. case ts.ModuleKind.AMD:
  16958. case ts.ModuleKind.ES2015:
  16959. case ts.ModuleKind.ES2020:
  16960. case ts.ModuleKind.ESNext:
  16961. return true;
  16962. default:
  16963. return false;
  16964. }
  16965. }
  16966. ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
  16967. function unreachableCodeIsError(options) {
  16968. return options.allowUnreachableCode === false;
  16969. }
  16970. ts.unreachableCodeIsError = unreachableCodeIsError;
  16971. function unusedLabelIsError(options) {
  16972. return options.allowUnusedLabels === false;
  16973. }
  16974. ts.unusedLabelIsError = unusedLabelIsError;
  16975. function getAreDeclarationMapsEnabled(options) {
  16976. return !!(getEmitDeclarations(options) && options.declarationMap);
  16977. }
  16978. ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
  16979. function getAllowSyntheticDefaultImports(compilerOptions) {
  16980. var moduleKind = getEmitModuleKind(compilerOptions);
  16981. return compilerOptions.allowSyntheticDefaultImports !== undefined
  16982. ? compilerOptions.allowSyntheticDefaultImports
  16983. : compilerOptions.esModuleInterop ||
  16984. moduleKind === ts.ModuleKind.System;
  16985. }
  16986. ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
  16987. function getEmitDeclarations(compilerOptions) {
  16988. return !!(compilerOptions.declaration || compilerOptions.composite);
  16989. }
  16990. ts.getEmitDeclarations = getEmitDeclarations;
  16991. function isIncrementalCompilation(options) {
  16992. return !!(options.incremental || options.composite);
  16993. }
  16994. ts.isIncrementalCompilation = isIncrementalCompilation;
  16995. function getStrictOptionValue(compilerOptions, flag) {
  16996. return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
  16997. }
  16998. ts.getStrictOptionValue = getStrictOptionValue;
  16999. function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
  17000. return oldOptions !== newOptions &&
  17001. ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
  17002. }
  17003. ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
  17004. function compilerOptionsAffectEmit(newOptions, oldOptions) {
  17005. return oldOptions !== newOptions &&
  17006. ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
  17007. }
  17008. ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
  17009. function getCompilerOptionValue(options, option) {
  17010. return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
  17011. }
  17012. ts.getCompilerOptionValue = getCompilerOptionValue;
  17013. function hasZeroOrOneAsteriskCharacter(str) {
  17014. var seenAsterisk = false;
  17015. for (var i = 0; i < str.length; i++) {
  17016. if (str.charCodeAt(i) === 42 /* asterisk */) {
  17017. if (!seenAsterisk) {
  17018. seenAsterisk = true;
  17019. }
  17020. else {
  17021. // have already seen asterisk
  17022. return false;
  17023. }
  17024. }
  17025. }
  17026. return true;
  17027. }
  17028. ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
  17029. function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
  17030. var result = ts.createMap();
  17031. var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
  17032. return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
  17033. return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
  17034. })));
  17035. }));
  17036. for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
  17037. var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
  17038. var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
  17039. result.set(commonOriginal, commonResolved);
  17040. }
  17041. return result;
  17042. }
  17043. ts.discoverProbableSymlinks = discoverProbableSymlinks;
  17044. function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
  17045. var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
  17046. var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
  17047. while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
  17048. !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
  17049. getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
  17050. aParts.pop();
  17051. bParts.pop();
  17052. }
  17053. return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
  17054. }
  17055. // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
  17056. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
  17057. function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
  17058. return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
  17059. }
  17060. function stripLeadingDirectorySeparator(s) {
  17061. return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
  17062. }
  17063. function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
  17064. var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
  17065. return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
  17066. }
  17067. ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
  17068. // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
  17069. // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
  17070. // proof.
  17071. var reservedCharacterPattern = /[^\w\s\/]/g;
  17072. function regExpEscape(text) {
  17073. return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
  17074. }
  17075. ts.regExpEscape = regExpEscape;
  17076. function escapeRegExpCharacter(match) {
  17077. return "\\" + match;
  17078. }
  17079. var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
  17080. ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
  17081. var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
  17082. var filesMatcher = {
  17083. /**
  17084. * Matches any single directory segment unless it is the last segment and a .min.js file
  17085. * Breakdown:
  17086. * [^./] # matches everything up to the first . character (excluding directory separators)
  17087. * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
  17088. */
  17089. singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
  17090. /**
  17091. * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
  17092. * files or directories, does not match subdirectories that start with a . character
  17093. */
  17094. doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
  17095. replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
  17096. };
  17097. var directoriesMatcher = {
  17098. singleAsteriskRegexFragment: "[^/]*",
  17099. /**
  17100. * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
  17101. * files or directories, does not match subdirectories that start with a . character
  17102. */
  17103. doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
  17104. replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
  17105. };
  17106. var excludeMatcher = {
  17107. singleAsteriskRegexFragment: "[^/]*",
  17108. doubleAsteriskRegexFragment: "(/.+?)?",
  17109. replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
  17110. };
  17111. var wildcardMatchers = {
  17112. files: filesMatcher,
  17113. directories: directoriesMatcher,
  17114. exclude: excludeMatcher
  17115. };
  17116. function getRegularExpressionForWildcard(specs, basePath, usage) {
  17117. var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
  17118. if (!patterns || !patterns.length) {
  17119. return undefined;
  17120. }
  17121. var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
  17122. // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
  17123. var terminator = usage === "exclude" ? "($|/)" : "$";
  17124. return "^(" + pattern + ")" + terminator;
  17125. }
  17126. ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
  17127. function getRegularExpressionsForWildcards(specs, basePath, usage) {
  17128. if (specs === undefined || specs.length === 0) {
  17129. return undefined;
  17130. }
  17131. return ts.flatMap(specs, function (spec) {
  17132. return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
  17133. });
  17134. }
  17135. ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
  17136. /**
  17137. * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
  17138. * and does not contain any glob characters itself.
  17139. */
  17140. function isImplicitGlob(lastPathComponent) {
  17141. return !/[.*?]/.test(lastPathComponent);
  17142. }
  17143. ts.isImplicitGlob = isImplicitGlob;
  17144. function getSubPatternFromSpec(spec, basePath, usage, _a) {
  17145. var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
  17146. var subpattern = "";
  17147. var hasWrittenComponent = false;
  17148. var components = ts.getNormalizedPathComponents(spec, basePath);
  17149. var lastComponent = ts.last(components);
  17150. if (usage !== "exclude" && lastComponent === "**") {
  17151. return undefined;
  17152. }
  17153. // getNormalizedPathComponents includes the separator for the root component.
  17154. // We need to remove to create our regex correctly.
  17155. components[0] = ts.removeTrailingDirectorySeparator(components[0]);
  17156. if (isImplicitGlob(lastComponent)) {
  17157. components.push("**", "*");
  17158. }
  17159. var optionalCount = 0;
  17160. for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
  17161. var component = components_1[_i];
  17162. if (component === "**") {
  17163. subpattern += doubleAsteriskRegexFragment;
  17164. }
  17165. else {
  17166. if (usage === "directories") {
  17167. subpattern += "(";
  17168. optionalCount++;
  17169. }
  17170. if (hasWrittenComponent) {
  17171. subpattern += ts.directorySeparator;
  17172. }
  17173. if (usage !== "exclude") {
  17174. var componentPattern = "";
  17175. // The * and ? wildcards should not match directories or files that start with . if they
  17176. // appear first in a component. Dotted directories and files can be included explicitly
  17177. // like so: **/.*/.*
  17178. if (component.charCodeAt(0) === 42 /* asterisk */) {
  17179. componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
  17180. component = component.substr(1);
  17181. }
  17182. else if (component.charCodeAt(0) === 63 /* question */) {
  17183. componentPattern += "[^./]";
  17184. component = component.substr(1);
  17185. }
  17186. componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
  17187. // Patterns should not include subfolders like node_modules unless they are
  17188. // explicitly included as part of the path.
  17189. //
  17190. // As an optimization, if the component pattern is the same as the component,
  17191. // then there definitely were no wildcard characters and we do not need to
  17192. // add the exclusion pattern.
  17193. if (componentPattern !== component) {
  17194. subpattern += implicitExcludePathRegexPattern;
  17195. }
  17196. subpattern += componentPattern;
  17197. }
  17198. else {
  17199. subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
  17200. }
  17201. }
  17202. hasWrittenComponent = true;
  17203. }
  17204. while (optionalCount > 0) {
  17205. subpattern += ")?";
  17206. optionalCount--;
  17207. }
  17208. return subpattern;
  17209. }
  17210. function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
  17211. return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
  17212. }
  17213. /** @param path directory of the tsconfig.json */
  17214. function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
  17215. path = ts.normalizePath(path);
  17216. currentDirectory = ts.normalizePath(currentDirectory);
  17217. var absolutePath = ts.combinePaths(currentDirectory, path);
  17218. return {
  17219. includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
  17220. includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
  17221. includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
  17222. excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
  17223. basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
  17224. };
  17225. }
  17226. ts.getFileMatcherPatterns = getFileMatcherPatterns;
  17227. function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
  17228. return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
  17229. }
  17230. ts.getRegexFromPattern = getRegexFromPattern;
  17231. /** @param path directory of the tsconfig.json */
  17232. function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
  17233. path = ts.normalizePath(path);
  17234. currentDirectory = ts.normalizePath(currentDirectory);
  17235. var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
  17236. var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
  17237. var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
  17238. var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
  17239. // Associate an array of results with each include regex. This keeps results in order of the "include" order.
  17240. // If there are no "includes", then just put everything in results[0].
  17241. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
  17242. var visited = ts.createMap();
  17243. var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  17244. for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
  17245. var basePath = _a[_i];
  17246. visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
  17247. }
  17248. return ts.flatten(results);
  17249. function visitDirectory(path, absolutePath, depth) {
  17250. var canonicalPath = toCanonical(realpath(absolutePath));
  17251. if (visited.has(canonicalPath))
  17252. return;
  17253. visited.set(canonicalPath, true);
  17254. var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
  17255. var _loop_1 = function (current) {
  17256. var name = ts.combinePaths(path, current);
  17257. var absoluteName = ts.combinePaths(absolutePath, current);
  17258. if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
  17259. return "continue";
  17260. if (excludeRegex && excludeRegex.test(absoluteName))
  17261. return "continue";
  17262. if (!includeFileRegexes) {
  17263. results[0].push(name);
  17264. }
  17265. else {
  17266. var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
  17267. if (includeIndex !== -1) {
  17268. results[includeIndex].push(name);
  17269. }
  17270. }
  17271. };
  17272. for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
  17273. var current = _b[_i];
  17274. _loop_1(current);
  17275. }
  17276. if (depth !== undefined) {
  17277. depth--;
  17278. if (depth === 0) {
  17279. return;
  17280. }
  17281. }
  17282. for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
  17283. var current = _d[_c];
  17284. var name = ts.combinePaths(path, current);
  17285. var absoluteName = ts.combinePaths(absolutePath, current);
  17286. if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
  17287. (!excludeRegex || !excludeRegex.test(absoluteName))) {
  17288. visitDirectory(name, absoluteName, depth);
  17289. }
  17290. }
  17291. }
  17292. }
  17293. ts.matchFiles = matchFiles;
  17294. /**
  17295. * Computes the unique non-wildcard base paths amongst the provided include patterns.
  17296. */
  17297. function getBasePaths(path, includes, useCaseSensitiveFileNames) {
  17298. // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
  17299. var basePaths = [path];
  17300. if (includes) {
  17301. // Storage for literal base paths amongst the include patterns.
  17302. var includeBasePaths = [];
  17303. for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
  17304. var include = includes_1[_i];
  17305. // We also need to check the relative paths by converting them to absolute and normalizing
  17306. // in case they escape the base path (e.g "..\somedirectory")
  17307. var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
  17308. // Append the literal and canonical candidate base paths.
  17309. includeBasePaths.push(getIncludeBasePath(absolute));
  17310. }
  17311. // Sort the offsets array using either the literal or canonical path representations.
  17312. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
  17313. var _loop_2 = function (includeBasePath) {
  17314. if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
  17315. basePaths.push(includeBasePath);
  17316. }
  17317. };
  17318. // Iterate over each include base path and include unique base paths that are not a
  17319. // subpath of an existing base path
  17320. for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
  17321. var includeBasePath = includeBasePaths_1[_a];
  17322. _loop_2(includeBasePath);
  17323. }
  17324. }
  17325. return basePaths;
  17326. }
  17327. function getIncludeBasePath(absolute) {
  17328. var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
  17329. if (wildcardOffset < 0) {
  17330. // No "*" or "?" in the path
  17331. return !ts.hasExtension(absolute)
  17332. ? absolute
  17333. : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
  17334. }
  17335. return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
  17336. }
  17337. function ensureScriptKind(fileName, scriptKind) {
  17338. // Using scriptKind as a condition handles both:
  17339. // - 'scriptKind' is unspecified and thus it is `undefined`
  17340. // - 'scriptKind' is set and it is `Unknown` (0)
  17341. // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
  17342. // to get the ScriptKind from the file name. If it cannot be resolved
  17343. // from the file name then the default 'TS' script kind is returned.
  17344. return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
  17345. }
  17346. ts.ensureScriptKind = ensureScriptKind;
  17347. function getScriptKindFromFileName(fileName) {
  17348. var ext = fileName.substr(fileName.lastIndexOf("."));
  17349. switch (ext.toLowerCase()) {
  17350. case ".js" /* Js */:
  17351. return 1 /* JS */;
  17352. case ".jsx" /* Jsx */:
  17353. return 2 /* JSX */;
  17354. case ".ts" /* Ts */:
  17355. return 3 /* TS */;
  17356. case ".tsx" /* Tsx */:
  17357. return 4 /* TSX */;
  17358. case ".json" /* Json */:
  17359. return 6 /* JSON */;
  17360. default:
  17361. return 0 /* Unknown */;
  17362. }
  17363. }
  17364. ts.getScriptKindFromFileName = getScriptKindFromFileName;
  17365. /**
  17366. * List of supported extensions in order of file resolution precedence.
  17367. */
  17368. ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
  17369. ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
  17370. /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
  17371. ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
  17372. ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
  17373. ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
  17374. var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
  17375. var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
  17376. function getSupportedExtensions(options, extraFileExtensions) {
  17377. var needJsExtensions = options && options.allowJs;
  17378. if (!extraFileExtensions || extraFileExtensions.length === 0) {
  17379. return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
  17380. }
  17381. var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
  17382. return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
  17383. }
  17384. ts.getSupportedExtensions = getSupportedExtensions;
  17385. function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
  17386. if (!options || !options.resolveJsonModule) {
  17387. return supportedExtensions;
  17388. }
  17389. if (supportedExtensions === allSupportedExtensions) {
  17390. return allSupportedExtensionsWithJson;
  17391. }
  17392. if (supportedExtensions === ts.supportedTSExtensions) {
  17393. return ts.supportedTSExtensionsWithJson;
  17394. }
  17395. return __spreadArrays(supportedExtensions, [".json" /* Json */]);
  17396. }
  17397. ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
  17398. function isJSLike(scriptKind) {
  17399. return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
  17400. }
  17401. function hasJSFileExtension(fileName) {
  17402. return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
  17403. }
  17404. ts.hasJSFileExtension = hasJSFileExtension;
  17405. function hasTSFileExtension(fileName) {
  17406. return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
  17407. }
  17408. ts.hasTSFileExtension = hasTSFileExtension;
  17409. function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
  17410. if (!fileName) {
  17411. return false;
  17412. }
  17413. var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
  17414. for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
  17415. var extension = _a[_i];
  17416. if (ts.fileExtensionIs(fileName, extension)) {
  17417. return true;
  17418. }
  17419. }
  17420. return false;
  17421. }
  17422. ts.isSupportedSourceFileName = isSupportedSourceFileName;
  17423. /**
  17424. * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
  17425. * aligned to the offset of the highest priority extension in the
  17426. * allSupportedExtensions array.
  17427. */
  17428. var ExtensionPriority;
  17429. (function (ExtensionPriority) {
  17430. ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
  17431. ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
  17432. ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
  17433. ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
  17434. })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
  17435. function getExtensionPriority(path, supportedExtensions) {
  17436. for (var i = supportedExtensions.length - 1; i >= 0; i--) {
  17437. if (ts.fileExtensionIs(path, supportedExtensions[i])) {
  17438. return adjustExtensionPriority(i, supportedExtensions);
  17439. }
  17440. }
  17441. // If its not in the list of supported extensions, this is likely a
  17442. // TypeScript file with a non-ts extension
  17443. return 0 /* Highest */;
  17444. }
  17445. ts.getExtensionPriority = getExtensionPriority;
  17446. /**
  17447. * Adjusts an extension priority to be the highest priority within the same range.
  17448. */
  17449. function adjustExtensionPriority(extensionPriority, supportedExtensions) {
  17450. if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
  17451. return 0 /* TypeScriptFiles */;
  17452. }
  17453. else if (extensionPriority < supportedExtensions.length) {
  17454. return 2 /* DeclarationAndJavaScriptFiles */;
  17455. }
  17456. else {
  17457. return supportedExtensions.length;
  17458. }
  17459. }
  17460. ts.adjustExtensionPriority = adjustExtensionPriority;
  17461. /**
  17462. * Gets the next lowest extension priority for a given priority.
  17463. */
  17464. function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
  17465. if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
  17466. return 2 /* DeclarationAndJavaScriptFiles */;
  17467. }
  17468. else {
  17469. return supportedExtensions.length;
  17470. }
  17471. }
  17472. ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
  17473. var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
  17474. function removeFileExtension(path) {
  17475. for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
  17476. var ext = extensionsToRemove_1[_i];
  17477. var extensionless = tryRemoveExtension(path, ext);
  17478. if (extensionless !== undefined) {
  17479. return extensionless;
  17480. }
  17481. }
  17482. return path;
  17483. }
  17484. ts.removeFileExtension = removeFileExtension;
  17485. function tryRemoveExtension(path, extension) {
  17486. return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
  17487. }
  17488. ts.tryRemoveExtension = tryRemoveExtension;
  17489. function removeExtension(path, extension) {
  17490. return path.substring(0, path.length - extension.length);
  17491. }
  17492. ts.removeExtension = removeExtension;
  17493. function changeExtension(path, newExtension) {
  17494. return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
  17495. }
  17496. ts.changeExtension = changeExtension;
  17497. function tryParsePattern(pattern) {
  17498. // This should be verified outside of here and a proper error thrown.
  17499. ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
  17500. var indexOfStar = pattern.indexOf("*");
  17501. return indexOfStar === -1 ? undefined : {
  17502. prefix: pattern.substr(0, indexOfStar),
  17503. suffix: pattern.substr(indexOfStar + 1)
  17504. };
  17505. }
  17506. ts.tryParsePattern = tryParsePattern;
  17507. function positionIsSynthesized(pos) {
  17508. // This is a fast way of testing the following conditions:
  17509. // pos === undefined || pos === null || isNaN(pos) || pos < 0;
  17510. return !(pos >= 0);
  17511. }
  17512. ts.positionIsSynthesized = positionIsSynthesized;
  17513. /** True if an extension is one of the supported TypeScript extensions. */
  17514. function extensionIsTS(ext) {
  17515. return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
  17516. }
  17517. ts.extensionIsTS = extensionIsTS;
  17518. function resolutionExtensionIsTSOrJson(ext) {
  17519. return extensionIsTS(ext) || ext === ".json" /* Json */;
  17520. }
  17521. ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
  17522. /**
  17523. * Gets the extension from a path.
  17524. * Path must have a valid extension.
  17525. */
  17526. function extensionFromPath(path) {
  17527. var ext = tryGetExtensionFromPath(path);
  17528. return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
  17529. }
  17530. ts.extensionFromPath = extensionFromPath;
  17531. function isAnySupportedFileExtension(path) {
  17532. return tryGetExtensionFromPath(path) !== undefined;
  17533. }
  17534. ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
  17535. function tryGetExtensionFromPath(path) {
  17536. return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
  17537. }
  17538. ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
  17539. function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
  17540. return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
  17541. }
  17542. ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
  17543. ts.emptyFileSystemEntries = {
  17544. files: ts.emptyArray,
  17545. directories: ts.emptyArray
  17546. };
  17547. /**
  17548. * patternStrings contains both pattern strings (containing "*") and regular strings.
  17549. * Return an exact match if possible, or a pattern match, or undefined.
  17550. * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
  17551. */
  17552. function matchPatternOrExact(patternStrings, candidate) {
  17553. var patterns = [];
  17554. for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
  17555. var patternString = patternStrings_1[_i];
  17556. if (!hasZeroOrOneAsteriskCharacter(patternString))
  17557. continue;
  17558. var pattern = tryParsePattern(patternString);
  17559. if (pattern) {
  17560. patterns.push(pattern);
  17561. }
  17562. else if (patternString === candidate) {
  17563. // pattern was matched as is - no need to search further
  17564. return patternString;
  17565. }
  17566. }
  17567. return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
  17568. }
  17569. ts.matchPatternOrExact = matchPatternOrExact;
  17570. function sliceAfter(arr, value) {
  17571. var index = arr.indexOf(value);
  17572. ts.Debug.assert(index !== -1);
  17573. return arr.slice(index);
  17574. }
  17575. ts.sliceAfter = sliceAfter;
  17576. function addRelatedInfo(diagnostic) {
  17577. var _a;
  17578. var relatedInformation = [];
  17579. for (var _i = 1; _i < arguments.length; _i++) {
  17580. relatedInformation[_i - 1] = arguments[_i];
  17581. }
  17582. if (!relatedInformation.length) {
  17583. return diagnostic;
  17584. }
  17585. if (!diagnostic.relatedInformation) {
  17586. diagnostic.relatedInformation = [];
  17587. }
  17588. (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
  17589. return diagnostic;
  17590. }
  17591. ts.addRelatedInfo = addRelatedInfo;
  17592. function minAndMax(arr, getValue) {
  17593. ts.Debug.assert(arr.length !== 0);
  17594. var min = getValue(arr[0]);
  17595. var max = min;
  17596. for (var i = 1; i < arr.length; i++) {
  17597. var value = getValue(arr[i]);
  17598. if (value < min) {
  17599. min = value;
  17600. }
  17601. else if (value > max) {
  17602. max = value;
  17603. }
  17604. }
  17605. return { min: min, max: max };
  17606. }
  17607. ts.minAndMax = minAndMax;
  17608. var NodeSet = /** @class */ (function () {
  17609. function NodeSet() {
  17610. this.map = ts.createMap();
  17611. }
  17612. NodeSet.prototype.add = function (node) {
  17613. this.map.set(String(ts.getNodeId(node)), node);
  17614. };
  17615. NodeSet.prototype.tryAdd = function (node) {
  17616. if (this.has(node))
  17617. return false;
  17618. this.add(node);
  17619. return true;
  17620. };
  17621. NodeSet.prototype.has = function (node) {
  17622. return this.map.has(String(ts.getNodeId(node)));
  17623. };
  17624. NodeSet.prototype.forEach = function (cb) {
  17625. this.map.forEach(cb);
  17626. };
  17627. NodeSet.prototype.some = function (pred) {
  17628. return forEachEntry(this.map, pred) || false;
  17629. };
  17630. return NodeSet;
  17631. }());
  17632. ts.NodeSet = NodeSet;
  17633. var NodeMap = /** @class */ (function () {
  17634. function NodeMap() {
  17635. this.map = ts.createMap();
  17636. }
  17637. NodeMap.prototype.get = function (node) {
  17638. var res = this.map.get(String(ts.getNodeId(node)));
  17639. return res && res.value;
  17640. };
  17641. NodeMap.prototype.getOrUpdate = function (node, setValue) {
  17642. var res = this.get(node);
  17643. if (res)
  17644. return res;
  17645. var value = setValue();
  17646. this.set(node, value);
  17647. return value;
  17648. };
  17649. NodeMap.prototype.set = function (node, value) {
  17650. this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
  17651. };
  17652. NodeMap.prototype.has = function (node) {
  17653. return this.map.has(String(ts.getNodeId(node)));
  17654. };
  17655. NodeMap.prototype.forEach = function (cb) {
  17656. this.map.forEach(function (_a) {
  17657. var node = _a.node, value = _a.value;
  17658. return cb(value, node);
  17659. });
  17660. };
  17661. return NodeMap;
  17662. }());
  17663. ts.NodeMap = NodeMap;
  17664. function rangeOfNode(node) {
  17665. return { pos: getTokenPosOfNode(node), end: node.end };
  17666. }
  17667. ts.rangeOfNode = rangeOfNode;
  17668. function rangeOfTypeParameters(typeParameters) {
  17669. // Include the `<>`
  17670. return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
  17671. }
  17672. ts.rangeOfTypeParameters = rangeOfTypeParameters;
  17673. function skipTypeChecking(sourceFile, options, host) {
  17674. // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
  17675. // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
  17676. // '/// <reference no-default-lib="true"/>' directive.
  17677. return (options.skipLibCheck && sourceFile.isDeclarationFile ||
  17678. options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
  17679. host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
  17680. }
  17681. ts.skipTypeChecking = skipTypeChecking;
  17682. function isJsonEqual(a, b) {
  17683. // eslint-disable-next-line no-null/no-null
  17684. return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
  17685. }
  17686. ts.isJsonEqual = isJsonEqual;
  17687. function getOrUpdate(map, key, getDefault) {
  17688. var got = map.get(key);
  17689. if (got === undefined) {
  17690. var value = getDefault();
  17691. map.set(key, value);
  17692. return value;
  17693. }
  17694. else {
  17695. return got;
  17696. }
  17697. }
  17698. ts.getOrUpdate = getOrUpdate;
  17699. /**
  17700. * Converts a bigint literal string, e.g. `0x1234n`,
  17701. * to its decimal string representation, e.g. `4660`.
  17702. */
  17703. function parsePseudoBigInt(stringValue) {
  17704. var log2Base;
  17705. switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
  17706. case 98 /* b */:
  17707. case 66 /* B */: // 0b or 0B
  17708. log2Base = 1;
  17709. break;
  17710. case 111 /* o */:
  17711. case 79 /* O */: // 0o or 0O
  17712. log2Base = 3;
  17713. break;
  17714. case 120 /* x */:
  17715. case 88 /* X */: // 0x or 0X
  17716. log2Base = 4;
  17717. break;
  17718. default: // already in decimal; omit trailing "n"
  17719. var nIndex = stringValue.length - 1;
  17720. // Skip leading 0s
  17721. var nonZeroStart = 0;
  17722. while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
  17723. nonZeroStart++;
  17724. }
  17725. return stringValue.slice(nonZeroStart, nIndex) || "0";
  17726. }
  17727. // Omit leading "0b", "0o", or "0x", and trailing "n"
  17728. var startIndex = 2, endIndex = stringValue.length - 1;
  17729. var bitsNeeded = (endIndex - startIndex) * log2Base;
  17730. // Stores the value specified by the string as a LE array of 16-bit integers
  17731. // using Uint16 instead of Uint32 so combining steps can use bitwise operators
  17732. var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
  17733. // Add the digits, one at a time
  17734. for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
  17735. var segment = bitOffset >>> 4;
  17736. var digitChar = stringValue.charCodeAt(i);
  17737. // Find character range: 0-9 < A-F < a-f
  17738. var digit = digitChar <= 57 /* _9 */
  17739. ? digitChar - 48 /* _0 */
  17740. : 10 + digitChar -
  17741. (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
  17742. var shiftedDigit = digit << (bitOffset & 15);
  17743. segments[segment] |= shiftedDigit;
  17744. var residual = shiftedDigit >>> 16;
  17745. if (residual)
  17746. segments[segment + 1] |= residual; // overflows segment
  17747. }
  17748. // Repeatedly divide segments by 10 and add remainder to base10Value
  17749. var base10Value = "";
  17750. var firstNonzeroSegment = segments.length - 1;
  17751. var segmentsRemaining = true;
  17752. while (segmentsRemaining) {
  17753. var mod10 = 0;
  17754. segmentsRemaining = false;
  17755. for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
  17756. var newSegment = mod10 << 16 | segments[segment];
  17757. var segmentValue = (newSegment / 10) | 0;
  17758. segments[segment] = segmentValue;
  17759. mod10 = newSegment - segmentValue * 10;
  17760. if (segmentValue && !segmentsRemaining) {
  17761. firstNonzeroSegment = segment;
  17762. segmentsRemaining = true;
  17763. }
  17764. }
  17765. base10Value = mod10 + base10Value;
  17766. }
  17767. return base10Value;
  17768. }
  17769. ts.parsePseudoBigInt = parsePseudoBigInt;
  17770. function pseudoBigIntToString(_a) {
  17771. var negative = _a.negative, base10Value = _a.base10Value;
  17772. return (negative && base10Value !== "0" ? "-" : "") + base10Value;
  17773. }
  17774. ts.pseudoBigIntToString = pseudoBigIntToString;
  17775. function isValidTypeOnlyAliasUseSite(useSite) {
  17776. return !!(useSite.flags & 8388608 /* Ambient */)
  17777. || isPartOfTypeQuery(useSite)
  17778. || isFirstIdentifierOfNonEmittingHeritageClause(useSite)
  17779. || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
  17780. || !isExpressionNode(useSite);
  17781. }
  17782. ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
  17783. function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
  17784. return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
  17785. }
  17786. ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
  17787. function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
  17788. while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
  17789. node = node.parent;
  17790. }
  17791. if (node.kind !== 154 /* ComputedPropertyName */) {
  17792. return false;
  17793. }
  17794. if (hasModifier(node.parent, 128 /* Abstract */)) {
  17795. return true;
  17796. }
  17797. var containerKind = node.parent.parent.kind;
  17798. return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
  17799. }
  17800. /** Returns true for the first identifier of 1) an `implements` clause, and 2) an `extends` clause of an interface. */
  17801. function isFirstIdentifierOfNonEmittingHeritageClause(node) {
  17802. var _a, _b;
  17803. // Number of parents to climb from identifier is 2 for `implements I`, 3 for `implements x.I`
  17804. var heritageClause = (_a = ts.tryCast(node.parent.parent, ts.isHeritageClause)) !== null && _a !== void 0 ? _a : ts.tryCast((_b = node.parent.parent) === null || _b === void 0 ? void 0 : _b.parent, ts.isHeritageClause);
  17805. return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
  17806. }
  17807. })(ts || (ts = {}));
  17808. var ts;
  17809. (function (ts) {
  17810. var SignatureFlags;
  17811. (function (SignatureFlags) {
  17812. SignatureFlags[SignatureFlags["None"] = 0] = "None";
  17813. SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
  17814. SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
  17815. SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
  17816. SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
  17817. SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
  17818. })(SignatureFlags || (SignatureFlags = {}));
  17819. var NodeConstructor;
  17820. var TokenConstructor;
  17821. var IdentifierConstructor;
  17822. var PrivateIdentifierConstructor;
  17823. var SourceFileConstructor;
  17824. function createNode(kind, pos, end) {
  17825. if (kind === 290 /* SourceFile */) {
  17826. return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
  17827. }
  17828. else if (kind === 75 /* Identifier */) {
  17829. return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
  17830. }
  17831. else if (kind === 76 /* PrivateIdentifier */) {
  17832. return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
  17833. }
  17834. else if (!ts.isNodeKind(kind)) {
  17835. return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
  17836. }
  17837. else {
  17838. return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
  17839. }
  17840. }
  17841. ts.createNode = createNode;
  17842. function visitNode(cbNode, node) {
  17843. return node && cbNode(node);
  17844. }
  17845. function visitNodes(cbNode, cbNodes, nodes) {
  17846. if (nodes) {
  17847. if (cbNodes) {
  17848. return cbNodes(nodes);
  17849. }
  17850. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17851. var node = nodes_1[_i];
  17852. var result = cbNode(node);
  17853. if (result) {
  17854. return result;
  17855. }
  17856. }
  17857. }
  17858. }
  17859. /*@internal*/
  17860. function isJSDocLikeText(text, start) {
  17861. return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
  17862. text.charCodeAt(start + 2) === 42 /* asterisk */ &&
  17863. text.charCodeAt(start + 3) !== 47 /* slash */;
  17864. }
  17865. ts.isJSDocLikeText = isJSDocLikeText;
  17866. /**
  17867. * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
  17868. * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
  17869. * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
  17870. * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
  17871. *
  17872. * @param node a given node to visit its children
  17873. * @param cbNode a callback to be invoked for all child nodes
  17874. * @param cbNodes a callback to be invoked for embedded array
  17875. *
  17876. * @remarks `forEachChild` must visit the children of a node in the order
  17877. * that they appear in the source code. The language service depends on this property to locate nodes by position.
  17878. */
  17879. function forEachChild(node, cbNode, cbNodes) {
  17880. if (!node || node.kind <= 152 /* LastToken */) {
  17881. return;
  17882. }
  17883. switch (node.kind) {
  17884. case 153 /* QualifiedName */:
  17885. return visitNode(cbNode, node.left) ||
  17886. visitNode(cbNode, node.right);
  17887. case 155 /* TypeParameter */:
  17888. return visitNode(cbNode, node.name) ||
  17889. visitNode(cbNode, node.constraint) ||
  17890. visitNode(cbNode, node.default) ||
  17891. visitNode(cbNode, node.expression);
  17892. case 282 /* ShorthandPropertyAssignment */:
  17893. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17894. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17895. visitNode(cbNode, node.name) ||
  17896. visitNode(cbNode, node.questionToken) ||
  17897. visitNode(cbNode, node.exclamationToken) ||
  17898. visitNode(cbNode, node.equalsToken) ||
  17899. visitNode(cbNode, node.objectAssignmentInitializer);
  17900. case 283 /* SpreadAssignment */:
  17901. return visitNode(cbNode, node.expression);
  17902. case 156 /* Parameter */:
  17903. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17904. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17905. visitNode(cbNode, node.dotDotDotToken) ||
  17906. visitNode(cbNode, node.name) ||
  17907. visitNode(cbNode, node.questionToken) ||
  17908. visitNode(cbNode, node.type) ||
  17909. visitNode(cbNode, node.initializer);
  17910. case 159 /* PropertyDeclaration */:
  17911. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17912. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17913. visitNode(cbNode, node.name) ||
  17914. visitNode(cbNode, node.questionToken) ||
  17915. visitNode(cbNode, node.exclamationToken) ||
  17916. visitNode(cbNode, node.type) ||
  17917. visitNode(cbNode, node.initializer);
  17918. case 158 /* PropertySignature */:
  17919. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17920. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17921. visitNode(cbNode, node.name) ||
  17922. visitNode(cbNode, node.questionToken) ||
  17923. visitNode(cbNode, node.type) ||
  17924. visitNode(cbNode, node.initializer);
  17925. case 281 /* PropertyAssignment */:
  17926. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17927. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17928. visitNode(cbNode, node.name) ||
  17929. visitNode(cbNode, node.questionToken) ||
  17930. visitNode(cbNode, node.initializer);
  17931. case 242 /* VariableDeclaration */:
  17932. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17933. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17934. visitNode(cbNode, node.name) ||
  17935. visitNode(cbNode, node.exclamationToken) ||
  17936. visitNode(cbNode, node.type) ||
  17937. visitNode(cbNode, node.initializer);
  17938. case 191 /* BindingElement */:
  17939. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17940. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17941. visitNode(cbNode, node.dotDotDotToken) ||
  17942. visitNode(cbNode, node.propertyName) ||
  17943. visitNode(cbNode, node.name) ||
  17944. visitNode(cbNode, node.initializer);
  17945. case 170 /* FunctionType */:
  17946. case 171 /* ConstructorType */:
  17947. case 165 /* CallSignature */:
  17948. case 166 /* ConstructSignature */:
  17949. case 167 /* IndexSignature */:
  17950. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17951. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17952. visitNodes(cbNode, cbNodes, node.typeParameters) ||
  17953. visitNodes(cbNode, cbNodes, node.parameters) ||
  17954. visitNode(cbNode, node.type);
  17955. case 161 /* MethodDeclaration */:
  17956. case 160 /* MethodSignature */:
  17957. case 162 /* Constructor */:
  17958. case 163 /* GetAccessor */:
  17959. case 164 /* SetAccessor */:
  17960. case 201 /* FunctionExpression */:
  17961. case 244 /* FunctionDeclaration */:
  17962. case 202 /* ArrowFunction */:
  17963. return visitNodes(cbNode, cbNodes, node.decorators) ||
  17964. visitNodes(cbNode, cbNodes, node.modifiers) ||
  17965. visitNode(cbNode, node.asteriskToken) ||
  17966. visitNode(cbNode, node.name) ||
  17967. visitNode(cbNode, node.questionToken) ||
  17968. visitNode(cbNode, node.exclamationToken) ||
  17969. visitNodes(cbNode, cbNodes, node.typeParameters) ||
  17970. visitNodes(cbNode, cbNodes, node.parameters) ||
  17971. visitNode(cbNode, node.type) ||
  17972. visitNode(cbNode, node.equalsGreaterThanToken) ||
  17973. visitNode(cbNode, node.body);
  17974. case 169 /* TypeReference */:
  17975. return visitNode(cbNode, node.typeName) ||
  17976. visitNodes(cbNode, cbNodes, node.typeArguments);
  17977. case 168 /* TypePredicate */:
  17978. return visitNode(cbNode, node.assertsModifier) ||
  17979. visitNode(cbNode, node.parameterName) ||
  17980. visitNode(cbNode, node.type);
  17981. case 172 /* TypeQuery */:
  17982. return visitNode(cbNode, node.exprName);
  17983. case 173 /* TypeLiteral */:
  17984. return visitNodes(cbNode, cbNodes, node.members);
  17985. case 174 /* ArrayType */:
  17986. return visitNode(cbNode, node.elementType);
  17987. case 175 /* TupleType */:
  17988. return visitNodes(cbNode, cbNodes, node.elementTypes);
  17989. case 178 /* UnionType */:
  17990. case 179 /* IntersectionType */:
  17991. return visitNodes(cbNode, cbNodes, node.types);
  17992. case 180 /* ConditionalType */:
  17993. return visitNode(cbNode, node.checkType) ||
  17994. visitNode(cbNode, node.extendsType) ||
  17995. visitNode(cbNode, node.trueType) ||
  17996. visitNode(cbNode, node.falseType);
  17997. case 181 /* InferType */:
  17998. return visitNode(cbNode, node.typeParameter);
  17999. case 188 /* ImportType */:
  18000. return visitNode(cbNode, node.argument) ||
  18001. visitNode(cbNode, node.qualifier) ||
  18002. visitNodes(cbNode, cbNodes, node.typeArguments);
  18003. case 182 /* ParenthesizedType */:
  18004. case 184 /* TypeOperator */:
  18005. return visitNode(cbNode, node.type);
  18006. case 185 /* IndexedAccessType */:
  18007. return visitNode(cbNode, node.objectType) ||
  18008. visitNode(cbNode, node.indexType);
  18009. case 186 /* MappedType */:
  18010. return visitNode(cbNode, node.readonlyToken) ||
  18011. visitNode(cbNode, node.typeParameter) ||
  18012. visitNode(cbNode, node.questionToken) ||
  18013. visitNode(cbNode, node.type);
  18014. case 187 /* LiteralType */:
  18015. return visitNode(cbNode, node.literal);
  18016. case 189 /* ObjectBindingPattern */:
  18017. case 190 /* ArrayBindingPattern */:
  18018. return visitNodes(cbNode, cbNodes, node.elements);
  18019. case 192 /* ArrayLiteralExpression */:
  18020. return visitNodes(cbNode, cbNodes, node.elements);
  18021. case 193 /* ObjectLiteralExpression */:
  18022. return visitNodes(cbNode, cbNodes, node.properties);
  18023. case 194 /* PropertyAccessExpression */:
  18024. return visitNode(cbNode, node.expression) ||
  18025. visitNode(cbNode, node.questionDotToken) ||
  18026. visitNode(cbNode, node.name);
  18027. case 195 /* ElementAccessExpression */:
  18028. return visitNode(cbNode, node.expression) ||
  18029. visitNode(cbNode, node.questionDotToken) ||
  18030. visitNode(cbNode, node.argumentExpression);
  18031. case 196 /* CallExpression */:
  18032. case 197 /* NewExpression */:
  18033. return visitNode(cbNode, node.expression) ||
  18034. visitNode(cbNode, node.questionDotToken) ||
  18035. visitNodes(cbNode, cbNodes, node.typeArguments) ||
  18036. visitNodes(cbNode, cbNodes, node.arguments);
  18037. case 198 /* TaggedTemplateExpression */:
  18038. return visitNode(cbNode, node.tag) ||
  18039. visitNode(cbNode, node.questionDotToken) ||
  18040. visitNodes(cbNode, cbNodes, node.typeArguments) ||
  18041. visitNode(cbNode, node.template);
  18042. case 199 /* TypeAssertionExpression */:
  18043. return visitNode(cbNode, node.type) ||
  18044. visitNode(cbNode, node.expression);
  18045. case 200 /* ParenthesizedExpression */:
  18046. return visitNode(cbNode, node.expression);
  18047. case 203 /* DeleteExpression */:
  18048. return visitNode(cbNode, node.expression);
  18049. case 204 /* TypeOfExpression */:
  18050. return visitNode(cbNode, node.expression);
  18051. case 205 /* VoidExpression */:
  18052. return visitNode(cbNode, node.expression);
  18053. case 207 /* PrefixUnaryExpression */:
  18054. return visitNode(cbNode, node.operand);
  18055. case 212 /* YieldExpression */:
  18056. return visitNode(cbNode, node.asteriskToken) ||
  18057. visitNode(cbNode, node.expression);
  18058. case 206 /* AwaitExpression */:
  18059. return visitNode(cbNode, node.expression);
  18060. case 208 /* PostfixUnaryExpression */:
  18061. return visitNode(cbNode, node.operand);
  18062. case 209 /* BinaryExpression */:
  18063. return visitNode(cbNode, node.left) ||
  18064. visitNode(cbNode, node.operatorToken) ||
  18065. visitNode(cbNode, node.right);
  18066. case 217 /* AsExpression */:
  18067. return visitNode(cbNode, node.expression) ||
  18068. visitNode(cbNode, node.type);
  18069. case 218 /* NonNullExpression */:
  18070. return visitNode(cbNode, node.expression);
  18071. case 219 /* MetaProperty */:
  18072. return visitNode(cbNode, node.name);
  18073. case 210 /* ConditionalExpression */:
  18074. return visitNode(cbNode, node.condition) ||
  18075. visitNode(cbNode, node.questionToken) ||
  18076. visitNode(cbNode, node.whenTrue) ||
  18077. visitNode(cbNode, node.colonToken) ||
  18078. visitNode(cbNode, node.whenFalse);
  18079. case 213 /* SpreadElement */:
  18080. return visitNode(cbNode, node.expression);
  18081. case 223 /* Block */:
  18082. case 250 /* ModuleBlock */:
  18083. return visitNodes(cbNode, cbNodes, node.statements);
  18084. case 290 /* SourceFile */:
  18085. return visitNodes(cbNode, cbNodes, node.statements) ||
  18086. visitNode(cbNode, node.endOfFileToken);
  18087. case 225 /* VariableStatement */:
  18088. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18089. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18090. visitNode(cbNode, node.declarationList);
  18091. case 243 /* VariableDeclarationList */:
  18092. return visitNodes(cbNode, cbNodes, node.declarations);
  18093. case 226 /* ExpressionStatement */:
  18094. return visitNode(cbNode, node.expression);
  18095. case 227 /* IfStatement */:
  18096. return visitNode(cbNode, node.expression) ||
  18097. visitNode(cbNode, node.thenStatement) ||
  18098. visitNode(cbNode, node.elseStatement);
  18099. case 228 /* DoStatement */:
  18100. return visitNode(cbNode, node.statement) ||
  18101. visitNode(cbNode, node.expression);
  18102. case 229 /* WhileStatement */:
  18103. return visitNode(cbNode, node.expression) ||
  18104. visitNode(cbNode, node.statement);
  18105. case 230 /* ForStatement */:
  18106. return visitNode(cbNode, node.initializer) ||
  18107. visitNode(cbNode, node.condition) ||
  18108. visitNode(cbNode, node.incrementor) ||
  18109. visitNode(cbNode, node.statement);
  18110. case 231 /* ForInStatement */:
  18111. return visitNode(cbNode, node.initializer) ||
  18112. visitNode(cbNode, node.expression) ||
  18113. visitNode(cbNode, node.statement);
  18114. case 232 /* ForOfStatement */:
  18115. return visitNode(cbNode, node.awaitModifier) ||
  18116. visitNode(cbNode, node.initializer) ||
  18117. visitNode(cbNode, node.expression) ||
  18118. visitNode(cbNode, node.statement);
  18119. case 233 /* ContinueStatement */:
  18120. case 234 /* BreakStatement */:
  18121. return visitNode(cbNode, node.label);
  18122. case 235 /* ReturnStatement */:
  18123. return visitNode(cbNode, node.expression);
  18124. case 236 /* WithStatement */:
  18125. return visitNode(cbNode, node.expression) ||
  18126. visitNode(cbNode, node.statement);
  18127. case 237 /* SwitchStatement */:
  18128. return visitNode(cbNode, node.expression) ||
  18129. visitNode(cbNode, node.caseBlock);
  18130. case 251 /* CaseBlock */:
  18131. return visitNodes(cbNode, cbNodes, node.clauses);
  18132. case 277 /* CaseClause */:
  18133. return visitNode(cbNode, node.expression) ||
  18134. visitNodes(cbNode, cbNodes, node.statements);
  18135. case 278 /* DefaultClause */:
  18136. return visitNodes(cbNode, cbNodes, node.statements);
  18137. case 238 /* LabeledStatement */:
  18138. return visitNode(cbNode, node.label) ||
  18139. visitNode(cbNode, node.statement);
  18140. case 239 /* ThrowStatement */:
  18141. return visitNode(cbNode, node.expression);
  18142. case 240 /* TryStatement */:
  18143. return visitNode(cbNode, node.tryBlock) ||
  18144. visitNode(cbNode, node.catchClause) ||
  18145. visitNode(cbNode, node.finallyBlock);
  18146. case 280 /* CatchClause */:
  18147. return visitNode(cbNode, node.variableDeclaration) ||
  18148. visitNode(cbNode, node.block);
  18149. case 157 /* Decorator */:
  18150. return visitNode(cbNode, node.expression);
  18151. case 245 /* ClassDeclaration */:
  18152. case 214 /* ClassExpression */:
  18153. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18154. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18155. visitNode(cbNode, node.name) ||
  18156. visitNodes(cbNode, cbNodes, node.typeParameters) ||
  18157. visitNodes(cbNode, cbNodes, node.heritageClauses) ||
  18158. visitNodes(cbNode, cbNodes, node.members);
  18159. case 246 /* InterfaceDeclaration */:
  18160. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18161. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18162. visitNode(cbNode, node.name) ||
  18163. visitNodes(cbNode, cbNodes, node.typeParameters) ||
  18164. visitNodes(cbNode, cbNodes, node.heritageClauses) ||
  18165. visitNodes(cbNode, cbNodes, node.members);
  18166. case 247 /* TypeAliasDeclaration */:
  18167. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18168. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18169. visitNode(cbNode, node.name) ||
  18170. visitNodes(cbNode, cbNodes, node.typeParameters) ||
  18171. visitNode(cbNode, node.type);
  18172. case 248 /* EnumDeclaration */:
  18173. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18174. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18175. visitNode(cbNode, node.name) ||
  18176. visitNodes(cbNode, cbNodes, node.members);
  18177. case 284 /* EnumMember */:
  18178. return visitNode(cbNode, node.name) ||
  18179. visitNode(cbNode, node.initializer);
  18180. case 249 /* ModuleDeclaration */:
  18181. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18182. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18183. visitNode(cbNode, node.name) ||
  18184. visitNode(cbNode, node.body);
  18185. case 253 /* ImportEqualsDeclaration */:
  18186. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18187. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18188. visitNode(cbNode, node.name) ||
  18189. visitNode(cbNode, node.moduleReference);
  18190. case 254 /* ImportDeclaration */:
  18191. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18192. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18193. visitNode(cbNode, node.importClause) ||
  18194. visitNode(cbNode, node.moduleSpecifier);
  18195. case 255 /* ImportClause */:
  18196. return visitNode(cbNode, node.name) ||
  18197. visitNode(cbNode, node.namedBindings);
  18198. case 252 /* NamespaceExportDeclaration */:
  18199. return visitNode(cbNode, node.name);
  18200. case 256 /* NamespaceImport */:
  18201. return visitNode(cbNode, node.name);
  18202. case 262 /* NamespaceExport */:
  18203. return visitNode(cbNode, node.name);
  18204. case 257 /* NamedImports */:
  18205. case 261 /* NamedExports */:
  18206. return visitNodes(cbNode, cbNodes, node.elements);
  18207. case 260 /* ExportDeclaration */:
  18208. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18209. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18210. visitNode(cbNode, node.exportClause) ||
  18211. visitNode(cbNode, node.moduleSpecifier);
  18212. case 258 /* ImportSpecifier */:
  18213. case 263 /* ExportSpecifier */:
  18214. return visitNode(cbNode, node.propertyName) ||
  18215. visitNode(cbNode, node.name);
  18216. case 259 /* ExportAssignment */:
  18217. return visitNodes(cbNode, cbNodes, node.decorators) ||
  18218. visitNodes(cbNode, cbNodes, node.modifiers) ||
  18219. visitNode(cbNode, node.expression);
  18220. case 211 /* TemplateExpression */:
  18221. return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
  18222. case 221 /* TemplateSpan */:
  18223. return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
  18224. case 154 /* ComputedPropertyName */:
  18225. return visitNode(cbNode, node.expression);
  18226. case 279 /* HeritageClause */:
  18227. return visitNodes(cbNode, cbNodes, node.types);
  18228. case 216 /* ExpressionWithTypeArguments */:
  18229. return visitNode(cbNode, node.expression) ||
  18230. visitNodes(cbNode, cbNodes, node.typeArguments);
  18231. case 265 /* ExternalModuleReference */:
  18232. return visitNode(cbNode, node.expression);
  18233. case 264 /* MissingDeclaration */:
  18234. return visitNodes(cbNode, cbNodes, node.decorators);
  18235. case 326 /* CommaListExpression */:
  18236. return visitNodes(cbNode, cbNodes, node.elements);
  18237. case 266 /* JsxElement */:
  18238. return visitNode(cbNode, node.openingElement) ||
  18239. visitNodes(cbNode, cbNodes, node.children) ||
  18240. visitNode(cbNode, node.closingElement);
  18241. case 270 /* JsxFragment */:
  18242. return visitNode(cbNode, node.openingFragment) ||
  18243. visitNodes(cbNode, cbNodes, node.children) ||
  18244. visitNode(cbNode, node.closingFragment);
  18245. case 267 /* JsxSelfClosingElement */:
  18246. case 268 /* JsxOpeningElement */:
  18247. return visitNode(cbNode, node.tagName) ||
  18248. visitNodes(cbNode, cbNodes, node.typeArguments) ||
  18249. visitNode(cbNode, node.attributes);
  18250. case 274 /* JsxAttributes */:
  18251. return visitNodes(cbNode, cbNodes, node.properties);
  18252. case 273 /* JsxAttribute */:
  18253. return visitNode(cbNode, node.name) ||
  18254. visitNode(cbNode, node.initializer);
  18255. case 275 /* JsxSpreadAttribute */:
  18256. return visitNode(cbNode, node.expression);
  18257. case 276 /* JsxExpression */:
  18258. return visitNode(cbNode, node.dotDotDotToken) ||
  18259. visitNode(cbNode, node.expression);
  18260. case 269 /* JsxClosingElement */:
  18261. return visitNode(cbNode, node.tagName);
  18262. case 176 /* OptionalType */:
  18263. case 177 /* RestType */:
  18264. case 294 /* JSDocTypeExpression */:
  18265. case 298 /* JSDocNonNullableType */:
  18266. case 297 /* JSDocNullableType */:
  18267. case 299 /* JSDocOptionalType */:
  18268. case 301 /* JSDocVariadicType */:
  18269. return visitNode(cbNode, node.type);
  18270. case 300 /* JSDocFunctionType */:
  18271. return visitNodes(cbNode, cbNodes, node.parameters) ||
  18272. visitNode(cbNode, node.type);
  18273. case 303 /* JSDocComment */:
  18274. return visitNodes(cbNode, cbNodes, node.tags);
  18275. case 316 /* JSDocParameterTag */:
  18276. case 322 /* JSDocPropertyTag */:
  18277. return visitNode(cbNode, node.tagName) ||
  18278. (node.isNameFirst
  18279. ? visitNode(cbNode, node.name) ||
  18280. visitNode(cbNode, node.typeExpression)
  18281. : visitNode(cbNode, node.typeExpression) ||
  18282. visitNode(cbNode, node.name));
  18283. case 308 /* JSDocAuthorTag */:
  18284. return visitNode(cbNode, node.tagName);
  18285. case 307 /* JSDocAugmentsTag */:
  18286. return visitNode(cbNode, node.tagName) ||
  18287. visitNode(cbNode, node.class);
  18288. case 320 /* JSDocTemplateTag */:
  18289. return visitNode(cbNode, node.tagName) ||
  18290. visitNode(cbNode, node.constraint) ||
  18291. visitNodes(cbNode, cbNodes, node.typeParameters);
  18292. case 321 /* JSDocTypedefTag */:
  18293. return visitNode(cbNode, node.tagName) ||
  18294. (node.typeExpression &&
  18295. node.typeExpression.kind === 294 /* JSDocTypeExpression */
  18296. ? visitNode(cbNode, node.typeExpression) ||
  18297. visitNode(cbNode, node.fullName)
  18298. : visitNode(cbNode, node.fullName) ||
  18299. visitNode(cbNode, node.typeExpression));
  18300. case 314 /* JSDocCallbackTag */:
  18301. return visitNode(cbNode, node.tagName) ||
  18302. visitNode(cbNode, node.fullName) ||
  18303. visitNode(cbNode, node.typeExpression);
  18304. case 317 /* JSDocReturnTag */:
  18305. case 319 /* JSDocTypeTag */:
  18306. case 318 /* JSDocThisTag */:
  18307. case 315 /* JSDocEnumTag */:
  18308. return visitNode(cbNode, node.tagName) ||
  18309. visitNode(cbNode, node.typeExpression);
  18310. case 305 /* JSDocSignature */:
  18311. return ts.forEach(node.typeParameters, cbNode) ||
  18312. ts.forEach(node.parameters, cbNode) ||
  18313. visitNode(cbNode, node.type);
  18314. case 304 /* JSDocTypeLiteral */:
  18315. return ts.forEach(node.jsDocPropertyTags, cbNode);
  18316. case 306 /* JSDocTag */:
  18317. case 309 /* JSDocClassTag */:
  18318. case 310 /* JSDocPublicTag */:
  18319. case 311 /* JSDocPrivateTag */:
  18320. case 312 /* JSDocProtectedTag */:
  18321. case 313 /* JSDocReadonlyTag */:
  18322. return visitNode(cbNode, node.tagName);
  18323. case 325 /* PartiallyEmittedExpression */:
  18324. return visitNode(cbNode, node.expression);
  18325. }
  18326. }
  18327. ts.forEachChild = forEachChild;
  18328. function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
  18329. if (setParentNodes === void 0) { setParentNodes = false; }
  18330. ts.performance.mark("beforeParse");
  18331. var result;
  18332. ts.perfLogger.logStartParseSourceFile(fileName);
  18333. if (languageVersion === 100 /* JSON */) {
  18334. result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
  18335. }
  18336. else {
  18337. result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
  18338. }
  18339. ts.perfLogger.logStopParseSourceFile();
  18340. ts.performance.mark("afterParse");
  18341. ts.performance.measure("Parse", "beforeParse", "afterParse");
  18342. return result;
  18343. }
  18344. ts.createSourceFile = createSourceFile;
  18345. function parseIsolatedEntityName(text, languageVersion) {
  18346. return Parser.parseIsolatedEntityName(text, languageVersion);
  18347. }
  18348. ts.parseIsolatedEntityName = parseIsolatedEntityName;
  18349. /**
  18350. * Parse json text into SyntaxTree and return node and parse errors if any
  18351. * @param fileName
  18352. * @param sourceText
  18353. */
  18354. function parseJsonText(fileName, sourceText) {
  18355. return Parser.parseJsonText(fileName, sourceText);
  18356. }
  18357. ts.parseJsonText = parseJsonText;
  18358. // See also `isExternalOrCommonJsModule` in utilities.ts
  18359. function isExternalModule(file) {
  18360. return file.externalModuleIndicator !== undefined;
  18361. }
  18362. ts.isExternalModule = isExternalModule;
  18363. // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
  18364. // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
  18365. // The SourceFile will be created with the compiler attempting to reuse as many nodes from
  18366. // this file as possible.
  18367. //
  18368. // Note: this function mutates nodes from this SourceFile. That means any existing nodes
  18369. // from this SourceFile that are being held onto may change as a result (including
  18370. // becoming detached from any SourceFile). It is recommended that this SourceFile not
  18371. // be used once 'update' is called on it.
  18372. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
  18373. if (aggressiveChecks === void 0) { aggressiveChecks = false; }
  18374. var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
  18375. // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import.
  18376. // We will manually port the flag to the new source file.
  18377. newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
  18378. return newSourceFile;
  18379. }
  18380. ts.updateSourceFile = updateSourceFile;
  18381. /* @internal */
  18382. function parseIsolatedJSDocComment(content, start, length) {
  18383. var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
  18384. if (result && result.jsDoc) {
  18385. // because the jsDocComment was parsed out of the source file, it might
  18386. // not be covered by the fixupParentReferences.
  18387. Parser.fixupParentReferences(result.jsDoc);
  18388. }
  18389. return result;
  18390. }
  18391. ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
  18392. /* @internal */
  18393. // Exposed only for testing.
  18394. function parseJSDocTypeExpressionForTests(content, start, length) {
  18395. return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
  18396. }
  18397. ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
  18398. // Implement the parser as a singleton module. We do this for perf reasons because creating
  18399. // parser instances can actually be expensive enough to impact us on projects with many source
  18400. // files.
  18401. var Parser;
  18402. (function (Parser) {
  18403. // Share a single scanner across all calls to parse a source file. This helps speed things
  18404. // up by avoiding the cost of creating/compiling scanners over and over again.
  18405. var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
  18406. var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
  18407. // capture constructors in 'initializeState' to avoid null checks
  18408. var NodeConstructor;
  18409. var TokenConstructor;
  18410. var IdentifierConstructor;
  18411. var PrivateIdentifierConstructor;
  18412. var SourceFileConstructor;
  18413. var sourceFile;
  18414. var parseDiagnostics;
  18415. var syntaxCursor;
  18416. var currentToken;
  18417. var sourceText;
  18418. var nodeCount;
  18419. var identifiers;
  18420. var privateIdentifiers;
  18421. var identifierCount;
  18422. var parsingContext;
  18423. var notParenthesizedArrow;
  18424. // Flags that dictate what parsing context we're in. For example:
  18425. // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
  18426. // that some tokens that would be considered identifiers may be considered keywords.
  18427. //
  18428. // When adding more parser context flags, consider which is the more common case that the
  18429. // flag will be in. This should be the 'false' state for that flag. The reason for this is
  18430. // that we don't store data in our nodes unless the value is in the *non-default* state. So,
  18431. // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
  18432. // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
  18433. // all nodes would need extra state on them to store this info.
  18434. //
  18435. // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
  18436. // grammar specification.
  18437. //
  18438. // An important thing about these context concepts. By default they are effectively inherited
  18439. // while parsing through every grammar production. i.e. if you don't change them, then when
  18440. // you parse a sub-production, it will have the same context values as the parent production.
  18441. // This is great most of the time. After all, consider all the 'expression' grammar productions
  18442. // and how nearly all of them pass along the 'in' and 'yield' context values:
  18443. //
  18444. // EqualityExpression[In, Yield] :
  18445. // RelationalExpression[?In, ?Yield]
  18446. // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
  18447. // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
  18448. // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
  18449. // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
  18450. //
  18451. // Where you have to be careful is then understanding what the points are in the grammar
  18452. // where the values are *not* passed along. For example:
  18453. //
  18454. // SingleNameBinding[Yield,GeneratorParameter]
  18455. // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
  18456. // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
  18457. //
  18458. // Here this is saying that if the GeneratorParameter context flag is set, that we should
  18459. // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
  18460. // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
  18461. // production. Conversely, if the GeneratorParameter context flag is not set, then we
  18462. // should leave the 'yield' context flag alone.
  18463. //
  18464. // Getting this all correct is tricky and requires careful reading of the grammar to
  18465. // understand when these values should be changed versus when they should be inherited.
  18466. //
  18467. // Note: it should not be necessary to save/restore these flags during speculative/lookahead
  18468. // parsing. These context flags are naturally stored and restored through normal recursive
  18469. // descent parsing and unwinding.
  18470. var contextFlags;
  18471. // Whether or not we've had a parse error since creating the last AST node. If we have
  18472. // encountered an error, it will be stored on the next AST node we create. Parse errors
  18473. // can be broken down into three categories:
  18474. //
  18475. // 1) An error that occurred during scanning. For example, an unterminated literal, or a
  18476. // character that was completely not understood.
  18477. //
  18478. // 2) A token was expected, but was not present. This type of error is commonly produced
  18479. // by the 'parseExpected' function.
  18480. //
  18481. // 3) A token was present that no parsing function was able to consume. This type of error
  18482. // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
  18483. // decides to skip the token.
  18484. //
  18485. // In all of these cases, we want to mark the next node as having had an error before it.
  18486. // With this mark, we can know in incremental settings if this node can be reused, or if
  18487. // we have to reparse it. If we don't keep this information around, we may just reuse the
  18488. // node. in that event we would then not produce the same errors as we did before, causing
  18489. // significant confusion problems.
  18490. //
  18491. // Note: it is necessary that this value be saved/restored during speculative/lookahead
  18492. // parsing. During lookahead parsing, we will often create a node. That node will have
  18493. // this value attached, and then this value will be set back to 'false'. If we decide to
  18494. // rewind, we must get back to the same value we had prior to the lookahead.
  18495. //
  18496. // Note: any errors at the end of the file that do not precede a regular node, should get
  18497. // attached to the EOF token.
  18498. var parseErrorBeforeNextFinishedNode = false;
  18499. function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
  18500. if (setParentNodes === void 0) { setParentNodes = false; }
  18501. scriptKind = ts.ensureScriptKind(fileName, scriptKind);
  18502. if (scriptKind === 6 /* JSON */) {
  18503. var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
  18504. ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
  18505. result_2.referencedFiles = ts.emptyArray;
  18506. result_2.typeReferenceDirectives = ts.emptyArray;
  18507. result_2.libReferenceDirectives = ts.emptyArray;
  18508. result_2.amdDependencies = ts.emptyArray;
  18509. result_2.hasNoDefaultLib = false;
  18510. result_2.pragmas = ts.emptyMap;
  18511. return result_2;
  18512. }
  18513. initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
  18514. var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
  18515. clearState();
  18516. return result;
  18517. }
  18518. Parser.parseSourceFile = parseSourceFile;
  18519. function parseIsolatedEntityName(content, languageVersion) {
  18520. // Choice of `isDeclarationFile` should be arbitrary
  18521. initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
  18522. // Prime the scanner.
  18523. nextToken();
  18524. var entityName = parseEntityName(/*allowReservedWords*/ true);
  18525. var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
  18526. clearState();
  18527. return isInvalid ? entityName : undefined;
  18528. }
  18529. Parser.parseIsolatedEntityName = parseIsolatedEntityName;
  18530. function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
  18531. if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
  18532. initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
  18533. // Set source file so that errors will be reported with this file name
  18534. sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
  18535. sourceFile.flags = contextFlags;
  18536. // Prime the scanner.
  18537. nextToken();
  18538. var pos = getNodePos();
  18539. if (token() === 1 /* EndOfFileToken */) {
  18540. sourceFile.statements = createNodeArray([], pos, pos);
  18541. sourceFile.endOfFileToken = parseTokenNode();
  18542. }
  18543. else {
  18544. var statement = createNode(226 /* ExpressionStatement */);
  18545. switch (token()) {
  18546. case 22 /* OpenBracketToken */:
  18547. statement.expression = parseArrayLiteralExpression();
  18548. break;
  18549. case 106 /* TrueKeyword */:
  18550. case 91 /* FalseKeyword */:
  18551. case 100 /* NullKeyword */:
  18552. statement.expression = parseTokenNode();
  18553. break;
  18554. case 40 /* MinusToken */:
  18555. if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
  18556. statement.expression = parsePrefixUnaryExpression();
  18557. }
  18558. else {
  18559. statement.expression = parseObjectLiteralExpression();
  18560. }
  18561. break;
  18562. case 8 /* NumericLiteral */:
  18563. case 10 /* StringLiteral */:
  18564. if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
  18565. statement.expression = parseLiteralNode();
  18566. break;
  18567. }
  18568. // falls through
  18569. default:
  18570. statement.expression = parseObjectLiteralExpression();
  18571. break;
  18572. }
  18573. finishNode(statement);
  18574. sourceFile.statements = createNodeArray([statement], pos);
  18575. sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
  18576. }
  18577. if (setParentNodes) {
  18578. fixupParentReferences(sourceFile);
  18579. }
  18580. sourceFile.nodeCount = nodeCount;
  18581. sourceFile.identifierCount = identifierCount;
  18582. sourceFile.identifiers = identifiers;
  18583. sourceFile.parseDiagnostics = parseDiagnostics;
  18584. var result = sourceFile;
  18585. clearState();
  18586. return result;
  18587. }
  18588. Parser.parseJsonText = parseJsonText;
  18589. function getLanguageVariant(scriptKind) {
  18590. // .tsx and .jsx files are treated as jsx language variant.
  18591. return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
  18592. }
  18593. function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
  18594. NodeConstructor = ts.objectAllocator.getNodeConstructor();
  18595. TokenConstructor = ts.objectAllocator.getTokenConstructor();
  18596. IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
  18597. PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
  18598. SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
  18599. sourceText = _sourceText;
  18600. syntaxCursor = _syntaxCursor;
  18601. parseDiagnostics = [];
  18602. parsingContext = 0;
  18603. identifiers = ts.createMap();
  18604. privateIdentifiers = ts.createMap();
  18605. identifierCount = 0;
  18606. nodeCount = 0;
  18607. switch (scriptKind) {
  18608. case 1 /* JS */:
  18609. case 2 /* JSX */:
  18610. contextFlags = 131072 /* JavaScriptFile */;
  18611. break;
  18612. case 6 /* JSON */:
  18613. contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
  18614. break;
  18615. default:
  18616. contextFlags = 0 /* None */;
  18617. break;
  18618. }
  18619. parseErrorBeforeNextFinishedNode = false;
  18620. // Initialize and prime the scanner before parsing the source elements.
  18621. scanner.setText(sourceText);
  18622. scanner.setOnError(scanError);
  18623. scanner.setScriptTarget(languageVersion);
  18624. scanner.setLanguageVariant(getLanguageVariant(scriptKind));
  18625. }
  18626. function clearState() {
  18627. // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
  18628. scanner.setText("");
  18629. scanner.setOnError(undefined);
  18630. // Clear any data. We don't want to accidentally hold onto it for too long.
  18631. parseDiagnostics = undefined;
  18632. sourceFile = undefined;
  18633. identifiers = undefined;
  18634. syntaxCursor = undefined;
  18635. sourceText = undefined;
  18636. notParenthesizedArrow = undefined;
  18637. }
  18638. function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
  18639. var isDeclarationFile = isDeclarationFileName(fileName);
  18640. if (isDeclarationFile) {
  18641. contextFlags |= 8388608 /* Ambient */;
  18642. }
  18643. sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
  18644. sourceFile.flags = contextFlags;
  18645. // Prime the scanner.
  18646. nextToken();
  18647. // A member of ReadonlyArray<T> isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
  18648. processCommentPragmas(sourceFile, sourceText);
  18649. processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
  18650. sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
  18651. ts.Debug.assert(token() === 1 /* EndOfFileToken */);
  18652. sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
  18653. setExternalModuleIndicator(sourceFile);
  18654. sourceFile.nodeCount = nodeCount;
  18655. sourceFile.identifierCount = identifierCount;
  18656. sourceFile.identifiers = identifiers;
  18657. sourceFile.parseDiagnostics = parseDiagnostics;
  18658. if (setParentNodes) {
  18659. fixupParentReferences(sourceFile);
  18660. }
  18661. return sourceFile;
  18662. function reportPragmaDiagnostic(pos, end, diagnostic) {
  18663. parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
  18664. }
  18665. }
  18666. function addJSDocComment(node) {
  18667. ts.Debug.assert(!node.jsDoc); // Should only be called once per node
  18668. var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
  18669. if (jsDoc.length)
  18670. node.jsDoc = jsDoc;
  18671. return node;
  18672. }
  18673. function fixupParentReferences(rootNode) {
  18674. // normally parent references are set during binding. However, for clients that only need
  18675. // a syntax tree, and no semantic features, then the binding process is an unnecessary
  18676. // overhead. This functions allows us to set all the parents, without all the expense of
  18677. // binding.
  18678. var stack = [rootNode];
  18679. while (stack.length) {
  18680. var parent = stack.pop();
  18681. bindParentToChildren(parent, gatherChildren(parent));
  18682. }
  18683. return;
  18684. function gatherChildren(node) {
  18685. var children = [];
  18686. forEachChild(node, function (n) { children.unshift(n); }); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
  18687. return children;
  18688. }
  18689. function bindParentToChildren(parent, children) {
  18690. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18691. var child = children_1[_i];
  18692. if (child.parent === parent)
  18693. continue; // already bound, assume subtree is bound
  18694. child.parent = parent;
  18695. stack.push(child);
  18696. if (ts.hasJSDocNodes(child)) {
  18697. for (var _a = 0, _b = child.jsDoc; _a < _b.length; _a++) {
  18698. var jsDoc = _b[_a];
  18699. jsDoc.parent = child;
  18700. stack.push(jsDoc);
  18701. }
  18702. }
  18703. }
  18704. }
  18705. }
  18706. Parser.fixupParentReferences = fixupParentReferences;
  18707. function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
  18708. // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
  18709. // this is quite rare comparing to other nodes and createNode should be as fast as possible
  18710. var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
  18711. nodeCount++;
  18712. sourceFile.text = sourceText;
  18713. sourceFile.bindDiagnostics = [];
  18714. sourceFile.bindSuggestionDiagnostics = undefined;
  18715. sourceFile.languageVersion = languageVersion;
  18716. sourceFile.fileName = ts.normalizePath(fileName);
  18717. sourceFile.languageVariant = getLanguageVariant(scriptKind);
  18718. sourceFile.isDeclarationFile = isDeclarationFile;
  18719. sourceFile.scriptKind = scriptKind;
  18720. return sourceFile;
  18721. }
  18722. function setContextFlag(val, flag) {
  18723. if (val) {
  18724. contextFlags |= flag;
  18725. }
  18726. else {
  18727. contextFlags &= ~flag;
  18728. }
  18729. }
  18730. function setDisallowInContext(val) {
  18731. setContextFlag(val, 4096 /* DisallowInContext */);
  18732. }
  18733. function setYieldContext(val) {
  18734. setContextFlag(val, 8192 /* YieldContext */);
  18735. }
  18736. function setDecoratorContext(val) {
  18737. setContextFlag(val, 16384 /* DecoratorContext */);
  18738. }
  18739. function setAwaitContext(val) {
  18740. setContextFlag(val, 32768 /* AwaitContext */);
  18741. }
  18742. function doOutsideOfContext(context, func) {
  18743. // contextFlagsToClear will contain only the context flags that are
  18744. // currently set that we need to temporarily clear
  18745. // We don't just blindly reset to the previous flags to ensure
  18746. // that we do not mutate cached flags for the incremental
  18747. // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
  18748. // HasAggregatedChildData).
  18749. var contextFlagsToClear = context & contextFlags;
  18750. if (contextFlagsToClear) {
  18751. // clear the requested context flags
  18752. setContextFlag(/*val*/ false, contextFlagsToClear);
  18753. var result = func();
  18754. // restore the context flags we just cleared
  18755. setContextFlag(/*val*/ true, contextFlagsToClear);
  18756. return result;
  18757. }
  18758. // no need to do anything special as we are not in any of the requested contexts
  18759. return func();
  18760. }
  18761. function doInsideOfContext(context, func) {
  18762. // contextFlagsToSet will contain only the context flags that
  18763. // are not currently set that we need to temporarily enable.
  18764. // We don't just blindly reset to the previous flags to ensure
  18765. // that we do not mutate cached flags for the incremental
  18766. // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
  18767. // HasAggregatedChildData).
  18768. var contextFlagsToSet = context & ~contextFlags;
  18769. if (contextFlagsToSet) {
  18770. // set the requested context flags
  18771. setContextFlag(/*val*/ true, contextFlagsToSet);
  18772. var result = func();
  18773. // reset the context flags we just set
  18774. setContextFlag(/*val*/ false, contextFlagsToSet);
  18775. return result;
  18776. }
  18777. // no need to do anything special as we are already in all of the requested contexts
  18778. return func();
  18779. }
  18780. function allowInAnd(func) {
  18781. return doOutsideOfContext(4096 /* DisallowInContext */, func);
  18782. }
  18783. function disallowInAnd(func) {
  18784. return doInsideOfContext(4096 /* DisallowInContext */, func);
  18785. }
  18786. function doInYieldContext(func) {
  18787. return doInsideOfContext(8192 /* YieldContext */, func);
  18788. }
  18789. function doInDecoratorContext(func) {
  18790. return doInsideOfContext(16384 /* DecoratorContext */, func);
  18791. }
  18792. function doInAwaitContext(func) {
  18793. return doInsideOfContext(32768 /* AwaitContext */, func);
  18794. }
  18795. function doOutsideOfAwaitContext(func) {
  18796. return doOutsideOfContext(32768 /* AwaitContext */, func);
  18797. }
  18798. function doInYieldAndAwaitContext(func) {
  18799. return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
  18800. }
  18801. function doOutsideOfYieldAndAwaitContext(func) {
  18802. return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
  18803. }
  18804. function inContext(flags) {
  18805. return (contextFlags & flags) !== 0;
  18806. }
  18807. function inYieldContext() {
  18808. return inContext(8192 /* YieldContext */);
  18809. }
  18810. function inDisallowInContext() {
  18811. return inContext(4096 /* DisallowInContext */);
  18812. }
  18813. function inDecoratorContext() {
  18814. return inContext(16384 /* DecoratorContext */);
  18815. }
  18816. function inAwaitContext() {
  18817. return inContext(32768 /* AwaitContext */);
  18818. }
  18819. function parseErrorAtCurrentToken(message, arg0) {
  18820. parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
  18821. }
  18822. function parseErrorAtPosition(start, length, message, arg0) {
  18823. // Don't report another error if it would just be at the same position as the last error.
  18824. var lastError = ts.lastOrUndefined(parseDiagnostics);
  18825. if (!lastError || start !== lastError.start) {
  18826. parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
  18827. }
  18828. // Mark that we've encountered an error. We'll set an appropriate bit on the next
  18829. // node we finish so that it can't be reused incrementally.
  18830. parseErrorBeforeNextFinishedNode = true;
  18831. }
  18832. function parseErrorAt(start, end, message, arg0) {
  18833. parseErrorAtPosition(start, end - start, message, arg0);
  18834. }
  18835. function parseErrorAtRange(range, message, arg0) {
  18836. parseErrorAt(range.pos, range.end, message, arg0);
  18837. }
  18838. function scanError(message, length) {
  18839. parseErrorAtPosition(scanner.getTextPos(), length, message);
  18840. }
  18841. function getNodePos() {
  18842. return scanner.getStartPos();
  18843. }
  18844. // Use this function to access the current token instead of reading the currentToken
  18845. // variable. Since function results aren't narrowed in control flow analysis, this ensures
  18846. // that the type checker doesn't make wrong assumptions about the type of the current
  18847. // token (e.g. a call to nextToken() changes the current token but the checker doesn't
  18848. // reason about this side effect). Mainstream VMs inline simple functions like this, so
  18849. // there is no performance penalty.
  18850. function token() {
  18851. return currentToken;
  18852. }
  18853. function nextTokenWithoutCheck() {
  18854. return currentToken = scanner.scan();
  18855. }
  18856. function nextToken() {
  18857. // if the keyword had an escape
  18858. if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
  18859. // issue a parse error for the escape
  18860. parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
  18861. }
  18862. return nextTokenWithoutCheck();
  18863. }
  18864. function nextTokenJSDoc() {
  18865. return currentToken = scanner.scanJsDocToken();
  18866. }
  18867. function reScanGreaterToken() {
  18868. return currentToken = scanner.reScanGreaterToken();
  18869. }
  18870. function reScanSlashToken() {
  18871. return currentToken = scanner.reScanSlashToken();
  18872. }
  18873. function reScanTemplateToken() {
  18874. return currentToken = scanner.reScanTemplateToken();
  18875. }
  18876. function reScanLessThanToken() {
  18877. return currentToken = scanner.reScanLessThanToken();
  18878. }
  18879. function scanJsxIdentifier() {
  18880. return currentToken = scanner.scanJsxIdentifier();
  18881. }
  18882. function scanJsxText() {
  18883. return currentToken = scanner.scanJsxToken();
  18884. }
  18885. function scanJsxAttributeValue() {
  18886. return currentToken = scanner.scanJsxAttributeValue();
  18887. }
  18888. function speculationHelper(callback, isLookAhead) {
  18889. // Keep track of the state we'll need to rollback to if lookahead fails (or if the
  18890. // caller asked us to always reset our state).
  18891. var saveToken = currentToken;
  18892. var saveParseDiagnosticsLength = parseDiagnostics.length;
  18893. var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
  18894. // Note: it is not actually necessary to save/restore the context flags here. That's
  18895. // because the saving/restoring of these flags happens naturally through the recursive
  18896. // descent nature of our parser. However, we still store this here just so we can
  18897. // assert that invariant holds.
  18898. var saveContextFlags = contextFlags;
  18899. // If we're only looking ahead, then tell the scanner to only lookahead as well.
  18900. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
  18901. // same.
  18902. var result = isLookAhead
  18903. ? scanner.lookAhead(callback)
  18904. : scanner.tryScan(callback);
  18905. ts.Debug.assert(saveContextFlags === contextFlags);
  18906. // If our callback returned something 'falsy' or we're just looking ahead,
  18907. // then unconditionally restore us to where we were.
  18908. if (!result || isLookAhead) {
  18909. currentToken = saveToken;
  18910. parseDiagnostics.length = saveParseDiagnosticsLength;
  18911. parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
  18912. }
  18913. return result;
  18914. }
  18915. /** Invokes the provided callback then unconditionally restores the parser to the state it
  18916. * was in immediately prior to invoking the callback. The result of invoking the callback
  18917. * is returned from this function.
  18918. */
  18919. function lookAhead(callback) {
  18920. return speculationHelper(callback, /*isLookAhead*/ true);
  18921. }
  18922. /** Invokes the provided callback. If the callback returns something falsy, then it restores
  18923. * the parser to the state it was in immediately prior to invoking the callback. If the
  18924. * callback returns something truthy, then the parser state is not rolled back. The result
  18925. * of invoking the callback is returned from this function.
  18926. */
  18927. function tryParse(callback) {
  18928. return speculationHelper(callback, /*isLookAhead*/ false);
  18929. }
  18930. // Ignore strict mode flag because we will report an error in type checker instead.
  18931. function isIdentifier() {
  18932. if (token() === 75 /* Identifier */) {
  18933. return true;
  18934. }
  18935. // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
  18936. // considered a keyword and is not an identifier.
  18937. if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
  18938. return false;
  18939. }
  18940. // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
  18941. // considered a keyword and is not an identifier.
  18942. if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
  18943. return false;
  18944. }
  18945. return token() > 112 /* LastReservedWord */;
  18946. }
  18947. function parseExpected(kind, diagnosticMessage, shouldAdvance) {
  18948. if (shouldAdvance === void 0) { shouldAdvance = true; }
  18949. if (token() === kind) {
  18950. if (shouldAdvance) {
  18951. nextToken();
  18952. }
  18953. return true;
  18954. }
  18955. // Report specific message if provided with one. Otherwise, report generic fallback message.
  18956. if (diagnosticMessage) {
  18957. parseErrorAtCurrentToken(diagnosticMessage);
  18958. }
  18959. else {
  18960. parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
  18961. }
  18962. return false;
  18963. }
  18964. function parseExpectedJSDoc(kind) {
  18965. if (token() === kind) {
  18966. nextTokenJSDoc();
  18967. return true;
  18968. }
  18969. parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
  18970. return false;
  18971. }
  18972. function parseOptional(t) {
  18973. if (token() === t) {
  18974. nextToken();
  18975. return true;
  18976. }
  18977. return false;
  18978. }
  18979. function parseOptionalToken(t) {
  18980. if (token() === t) {
  18981. return parseTokenNode();
  18982. }
  18983. return undefined;
  18984. }
  18985. function parseOptionalTokenJSDoc(t) {
  18986. if (token() === t) {
  18987. return parseTokenNodeJSDoc();
  18988. }
  18989. return undefined;
  18990. }
  18991. function parseExpectedToken(t, diagnosticMessage, arg0) {
  18992. return parseOptionalToken(t) ||
  18993. createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
  18994. }
  18995. function parseExpectedTokenJSDoc(t) {
  18996. return parseOptionalTokenJSDoc(t) ||
  18997. createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
  18998. }
  18999. function parseTokenNode() {
  19000. var node = createNode(token());
  19001. nextToken();
  19002. return finishNode(node);
  19003. }
  19004. function parseTokenNodeJSDoc() {
  19005. var node = createNode(token());
  19006. nextTokenJSDoc();
  19007. return finishNode(node);
  19008. }
  19009. function canParseSemicolon() {
  19010. // If there's a real semicolon, then we can always parse it out.
  19011. if (token() === 26 /* SemicolonToken */) {
  19012. return true;
  19013. }
  19014. // We can parse out an optional semicolon in ASI cases in the following cases.
  19015. return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
  19016. }
  19017. function parseSemicolon() {
  19018. if (canParseSemicolon()) {
  19019. if (token() === 26 /* SemicolonToken */) {
  19020. // consume the semicolon if it was explicitly provided.
  19021. nextToken();
  19022. }
  19023. return true;
  19024. }
  19025. else {
  19026. return parseExpected(26 /* SemicolonToken */);
  19027. }
  19028. }
  19029. function createNode(kind, pos) {
  19030. nodeCount++;
  19031. var p = pos >= 0 ? pos : scanner.getStartPos();
  19032. return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
  19033. kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
  19034. kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
  19035. new TokenConstructor(kind, p, p);
  19036. }
  19037. function createNodeWithJSDoc(kind, pos) {
  19038. var node = createNode(kind, pos);
  19039. if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) {
  19040. addJSDocComment(node);
  19041. }
  19042. return node;
  19043. }
  19044. function createNodeArray(elements, pos, end) {
  19045. // Since the element list of a node array is typically created by starting with an empty array and
  19046. // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
  19047. // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
  19048. var length = elements.length;
  19049. var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
  19050. array.pos = pos;
  19051. array.end = end === undefined ? scanner.getStartPos() : end;
  19052. return array;
  19053. }
  19054. function finishNode(node, end) {
  19055. node.end = end === undefined ? scanner.getStartPos() : end;
  19056. if (contextFlags) {
  19057. node.flags |= contextFlags;
  19058. }
  19059. // Keep track on the node if we encountered an error while parsing it. If we did, then
  19060. // we cannot reuse the node incrementally. Once we've marked this node, clear out the
  19061. // flag so that we don't mark any subsequent nodes.
  19062. if (parseErrorBeforeNextFinishedNode) {
  19063. parseErrorBeforeNextFinishedNode = false;
  19064. node.flags |= 65536 /* ThisNodeHasError */;
  19065. }
  19066. return node;
  19067. }
  19068. function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
  19069. if (reportAtCurrentPosition) {
  19070. parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
  19071. }
  19072. else if (diagnosticMessage) {
  19073. parseErrorAtCurrentToken(diagnosticMessage, arg0);
  19074. }
  19075. var result = createNode(kind);
  19076. if (kind === 75 /* Identifier */) {
  19077. result.escapedText = "";
  19078. }
  19079. else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
  19080. result.text = "";
  19081. }
  19082. return finishNode(result);
  19083. }
  19084. function internIdentifier(text) {
  19085. var identifier = identifiers.get(text);
  19086. if (identifier === undefined) {
  19087. identifiers.set(text, identifier = text);
  19088. }
  19089. return identifier;
  19090. }
  19091. // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
  19092. // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
  19093. // each identifier in order to reduce memory consumption.
  19094. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
  19095. identifierCount++;
  19096. if (isIdentifier) {
  19097. var node = createNode(75 /* Identifier */);
  19098. // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
  19099. if (token() !== 75 /* Identifier */) {
  19100. node.originalKeywordKind = token();
  19101. }
  19102. node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
  19103. nextTokenWithoutCheck();
  19104. return finishNode(node);
  19105. }
  19106. if (token() === 76 /* PrivateIdentifier */) {
  19107. parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
  19108. return createIdentifier(/*isIdentifier*/ true);
  19109. }
  19110. // Only for end of file because the error gets reported incorrectly on embedded script tags.
  19111. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
  19112. var isReservedWord = scanner.isReservedWord();
  19113. var msgArg = scanner.getTokenText();
  19114. var defaultMessage = isReservedWord ?
  19115. ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
  19116. ts.Diagnostics.Identifier_expected;
  19117. return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
  19118. }
  19119. function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
  19120. return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
  19121. }
  19122. function parseIdentifierName(diagnosticMessage) {
  19123. return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
  19124. }
  19125. function isLiteralPropertyName() {
  19126. return ts.tokenIsIdentifierOrKeyword(token()) ||
  19127. token() === 10 /* StringLiteral */ ||
  19128. token() === 8 /* NumericLiteral */;
  19129. }
  19130. function parsePropertyNameWorker(allowComputedPropertyNames) {
  19131. if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
  19132. var node = parseLiteralNode();
  19133. node.text = internIdentifier(node.text);
  19134. return node;
  19135. }
  19136. if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
  19137. return parseComputedPropertyName();
  19138. }
  19139. if (token() === 76 /* PrivateIdentifier */) {
  19140. return parsePrivateIdentifier();
  19141. }
  19142. return parseIdentifierName();
  19143. }
  19144. function parsePropertyName() {
  19145. return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
  19146. }
  19147. function parseComputedPropertyName() {
  19148. // PropertyName [Yield]:
  19149. // LiteralPropertyName
  19150. // ComputedPropertyName[?Yield]
  19151. var node = createNode(154 /* ComputedPropertyName */);
  19152. parseExpected(22 /* OpenBracketToken */);
  19153. // We parse any expression (including a comma expression). But the grammar
  19154. // says that only an assignment expression is allowed, so the grammar checker
  19155. // will error if it sees a comma expression.
  19156. node.expression = allowInAnd(parseExpression);
  19157. parseExpected(23 /* CloseBracketToken */);
  19158. return finishNode(node);
  19159. }
  19160. function internPrivateIdentifier(text) {
  19161. var privateIdentifier = privateIdentifiers.get(text);
  19162. if (privateIdentifier === undefined) {
  19163. privateIdentifiers.set(text, privateIdentifier = text);
  19164. }
  19165. return privateIdentifier;
  19166. }
  19167. function parsePrivateIdentifier() {
  19168. var node = createNode(76 /* PrivateIdentifier */);
  19169. node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
  19170. nextToken();
  19171. return finishNode(node);
  19172. }
  19173. function parseContextualModifier(t) {
  19174. return token() === t && tryParse(nextTokenCanFollowModifier);
  19175. }
  19176. function nextTokenIsOnSameLineAndCanFollowModifier() {
  19177. nextToken();
  19178. if (scanner.hasPrecedingLineBreak()) {
  19179. return false;
  19180. }
  19181. return canFollowModifier();
  19182. }
  19183. function nextTokenCanFollowModifier() {
  19184. switch (token()) {
  19185. case 81 /* ConstKeyword */:
  19186. // 'const' is only a modifier if followed by 'enum'.
  19187. return nextToken() === 88 /* EnumKeyword */;
  19188. case 89 /* ExportKeyword */:
  19189. nextToken();
  19190. if (token() === 84 /* DefaultKeyword */) {
  19191. return lookAhead(nextTokenCanFollowDefaultKeyword);
  19192. }
  19193. if (token() === 145 /* TypeKeyword */) {
  19194. return lookAhead(nextTokenCanFollowExportModifier);
  19195. }
  19196. return canFollowExportModifier();
  19197. case 84 /* DefaultKeyword */:
  19198. return nextTokenCanFollowDefaultKeyword();
  19199. case 120 /* StaticKeyword */:
  19200. case 131 /* GetKeyword */:
  19201. case 142 /* SetKeyword */:
  19202. nextToken();
  19203. return canFollowModifier();
  19204. default:
  19205. return nextTokenIsOnSameLineAndCanFollowModifier();
  19206. }
  19207. }
  19208. function canFollowExportModifier() {
  19209. return token() !== 41 /* AsteriskToken */
  19210. && token() !== 123 /* AsKeyword */
  19211. && token() !== 18 /* OpenBraceToken */
  19212. && canFollowModifier();
  19213. }
  19214. function nextTokenCanFollowExportModifier() {
  19215. nextToken();
  19216. return canFollowExportModifier();
  19217. }
  19218. function parseAnyContextualModifier() {
  19219. return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
  19220. }
  19221. function canFollowModifier() {
  19222. return token() === 22 /* OpenBracketToken */
  19223. || token() === 18 /* OpenBraceToken */
  19224. || token() === 41 /* AsteriskToken */
  19225. || token() === 25 /* DotDotDotToken */
  19226. || isLiteralPropertyName();
  19227. }
  19228. function nextTokenCanFollowDefaultKeyword() {
  19229. nextToken();
  19230. return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
  19231. token() === 114 /* InterfaceKeyword */ ||
  19232. (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
  19233. (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
  19234. }
  19235. // True if positioned at the start of a list element
  19236. function isListElement(parsingContext, inErrorRecovery) {
  19237. var node = currentNode(parsingContext);
  19238. if (node) {
  19239. return true;
  19240. }
  19241. switch (parsingContext) {
  19242. case 0 /* SourceElements */:
  19243. case 1 /* BlockStatements */:
  19244. case 3 /* SwitchClauseStatements */:
  19245. // If we're in error recovery, then we don't want to treat ';' as an empty statement.
  19246. // The problem is that ';' can show up in far too many contexts, and if we see one
  19247. // and assume it's a statement, then we may bail out inappropriately from whatever
  19248. // we're parsing. For example, if we have a semicolon in the middle of a class, then
  19249. // we really don't want to assume the class is over and we're on a statement in the
  19250. // outer module. We just want to consume and move on.
  19251. return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
  19252. case 2 /* SwitchClauses */:
  19253. return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
  19254. case 4 /* TypeMembers */:
  19255. return lookAhead(isTypeMemberStart);
  19256. case 5 /* ClassMembers */:
  19257. // We allow semicolons as class elements (as specified by ES6) as long as we're
  19258. // not in error recovery. If we're in error recovery, we don't want an errant
  19259. // semicolon to be treated as a class member (since they're almost always used
  19260. // for statements.
  19261. return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
  19262. case 6 /* EnumMembers */:
  19263. // Include open bracket computed properties. This technically also lets in indexers,
  19264. // which would be a candidate for improved error reporting.
  19265. return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
  19266. case 12 /* ObjectLiteralMembers */:
  19267. switch (token()) {
  19268. case 22 /* OpenBracketToken */:
  19269. case 41 /* AsteriskToken */:
  19270. case 25 /* DotDotDotToken */:
  19271. case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
  19272. return true;
  19273. default:
  19274. return isLiteralPropertyName();
  19275. }
  19276. case 18 /* RestProperties */:
  19277. return isLiteralPropertyName();
  19278. case 9 /* ObjectBindingElements */:
  19279. return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
  19280. case 7 /* HeritageClauseElement */:
  19281. // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
  19282. // That way we won't consume the body of a class in its heritage clause.
  19283. if (token() === 18 /* OpenBraceToken */) {
  19284. return lookAhead(isValidHeritageClauseObjectLiteral);
  19285. }
  19286. if (!inErrorRecovery) {
  19287. return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
  19288. }
  19289. else {
  19290. // If we're in error recovery we tighten up what we're willing to match.
  19291. // That way we don't treat something like "this" as a valid heritage clause
  19292. // element during recovery.
  19293. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
  19294. }
  19295. case 8 /* VariableDeclarations */:
  19296. return isIdentifierOrPrivateIdentifierOrPattern();
  19297. case 10 /* ArrayBindingElements */:
  19298. return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
  19299. case 19 /* TypeParameters */:
  19300. return isIdentifier();
  19301. case 15 /* ArrayLiteralMembers */:
  19302. switch (token()) {
  19303. case 27 /* CommaToken */:
  19304. case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
  19305. return true;
  19306. }
  19307. // falls through
  19308. case 11 /* ArgumentExpressions */:
  19309. return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
  19310. case 16 /* Parameters */:
  19311. return isStartOfParameter(/*isJSDocParameter*/ false);
  19312. case 17 /* JSDocParameters */:
  19313. return isStartOfParameter(/*isJSDocParameter*/ true);
  19314. case 20 /* TypeArguments */:
  19315. case 21 /* TupleElementTypes */:
  19316. return token() === 27 /* CommaToken */ || isStartOfType();
  19317. case 22 /* HeritageClauses */:
  19318. return isHeritageClause();
  19319. case 23 /* ImportOrExportSpecifiers */:
  19320. return ts.tokenIsIdentifierOrKeyword(token());
  19321. case 13 /* JsxAttributes */:
  19322. return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
  19323. case 14 /* JsxChildren */:
  19324. return true;
  19325. }
  19326. return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
  19327. }
  19328. function isValidHeritageClauseObjectLiteral() {
  19329. ts.Debug.assert(token() === 18 /* OpenBraceToken */);
  19330. if (nextToken() === 19 /* CloseBraceToken */) {
  19331. // if we see "extends {}" then only treat the {} as what we're extending (and not
  19332. // the class body) if we have:
  19333. //
  19334. // extends {} {
  19335. // extends {},
  19336. // extends {} extends
  19337. // extends {} implements
  19338. var next = nextToken();
  19339. return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
  19340. }
  19341. return true;
  19342. }
  19343. function nextTokenIsIdentifier() {
  19344. nextToken();
  19345. return isIdentifier();
  19346. }
  19347. function nextTokenIsIdentifierOrKeyword() {
  19348. nextToken();
  19349. return ts.tokenIsIdentifierOrKeyword(token());
  19350. }
  19351. function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
  19352. nextToken();
  19353. return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
  19354. }
  19355. function isHeritageClauseExtendsOrImplementsKeyword() {
  19356. if (token() === 113 /* ImplementsKeyword */ ||
  19357. token() === 90 /* ExtendsKeyword */) {
  19358. return lookAhead(nextTokenIsStartOfExpression);
  19359. }
  19360. return false;
  19361. }
  19362. function nextTokenIsStartOfExpression() {
  19363. nextToken();
  19364. return isStartOfExpression();
  19365. }
  19366. function nextTokenIsStartOfType() {
  19367. nextToken();
  19368. return isStartOfType();
  19369. }
  19370. // True if positioned at a list terminator
  19371. function isListTerminator(kind) {
  19372. if (token() === 1 /* EndOfFileToken */) {
  19373. // Being at the end of the file ends all lists.
  19374. return true;
  19375. }
  19376. switch (kind) {
  19377. case 1 /* BlockStatements */:
  19378. case 2 /* SwitchClauses */:
  19379. case 4 /* TypeMembers */:
  19380. case 5 /* ClassMembers */:
  19381. case 6 /* EnumMembers */:
  19382. case 12 /* ObjectLiteralMembers */:
  19383. case 9 /* ObjectBindingElements */:
  19384. case 23 /* ImportOrExportSpecifiers */:
  19385. return token() === 19 /* CloseBraceToken */;
  19386. case 3 /* SwitchClauseStatements */:
  19387. return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
  19388. case 7 /* HeritageClauseElement */:
  19389. return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
  19390. case 8 /* VariableDeclarations */:
  19391. return isVariableDeclaratorListTerminator();
  19392. case 19 /* TypeParameters */:
  19393. // Tokens other than '>' are here for better error recovery
  19394. return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
  19395. case 11 /* ArgumentExpressions */:
  19396. // Tokens other than ')' are here for better error recovery
  19397. return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
  19398. case 15 /* ArrayLiteralMembers */:
  19399. case 21 /* TupleElementTypes */:
  19400. case 10 /* ArrayBindingElements */:
  19401. return token() === 23 /* CloseBracketToken */;
  19402. case 17 /* JSDocParameters */:
  19403. case 16 /* Parameters */:
  19404. case 18 /* RestProperties */:
  19405. // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
  19406. return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
  19407. case 20 /* TypeArguments */:
  19408. // All other tokens should cause the type-argument to terminate except comma token
  19409. return token() !== 27 /* CommaToken */;
  19410. case 22 /* HeritageClauses */:
  19411. return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
  19412. case 13 /* JsxAttributes */:
  19413. return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
  19414. case 14 /* JsxChildren */:
  19415. return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
  19416. default:
  19417. return false;
  19418. }
  19419. }
  19420. function isVariableDeclaratorListTerminator() {
  19421. // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
  19422. // with parsing the list of variable declarators.
  19423. if (canParseSemicolon()) {
  19424. return true;
  19425. }
  19426. // in the case where we're parsing the variable declarator of a 'for-in' statement, we
  19427. // are done if we see an 'in' keyword in front of us. Same with for-of
  19428. if (isInOrOfKeyword(token())) {
  19429. return true;
  19430. }
  19431. // ERROR RECOVERY TWEAK:
  19432. // For better error recovery, if we see an '=>' then we just stop immediately. We've got an
  19433. // arrow function here and it's going to be very unlikely that we'll resynchronize and get
  19434. // another variable declaration.
  19435. if (token() === 38 /* EqualsGreaterThanToken */) {
  19436. return true;
  19437. }
  19438. // Keep trying to parse out variable declarators.
  19439. return false;
  19440. }
  19441. // True if positioned at element or terminator of the current list or any enclosing list
  19442. function isInSomeParsingContext() {
  19443. for (var kind = 0; kind < 24 /* Count */; kind++) {
  19444. if (parsingContext & (1 << kind)) {
  19445. if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
  19446. return true;
  19447. }
  19448. }
  19449. }
  19450. return false;
  19451. }
  19452. // Parses a list of elements
  19453. function parseList(kind, parseElement) {
  19454. var saveParsingContext = parsingContext;
  19455. parsingContext |= 1 << kind;
  19456. var list = [];
  19457. var listPos = getNodePos();
  19458. while (!isListTerminator(kind)) {
  19459. if (isListElement(kind, /*inErrorRecovery*/ false)) {
  19460. var element = parseListElement(kind, parseElement);
  19461. list.push(element);
  19462. continue;
  19463. }
  19464. if (abortParsingListOrMoveToNextToken(kind)) {
  19465. break;
  19466. }
  19467. }
  19468. parsingContext = saveParsingContext;
  19469. return createNodeArray(list, listPos);
  19470. }
  19471. function parseListElement(parsingContext, parseElement) {
  19472. var node = currentNode(parsingContext);
  19473. if (node) {
  19474. return consumeNode(node);
  19475. }
  19476. return parseElement();
  19477. }
  19478. function currentNode(parsingContext) {
  19479. // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
  19480. //
  19481. // If there is an outstanding parse error that we've encountered, but not attached to
  19482. // some node, then we cannot get a node from the old source tree. This is because we
  19483. // want to mark the next node we encounter as being unusable.
  19484. //
  19485. // Note: This may be too conservative. Perhaps we could reuse the node and set the bit
  19486. // on it (or its leftmost child) as having the error. For now though, being conservative
  19487. // is nice and likely won't ever affect perf.
  19488. if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
  19489. return undefined;
  19490. }
  19491. var node = syntaxCursor.currentNode(scanner.getStartPos());
  19492. // Can't reuse a missing node.
  19493. // Can't reuse a node that intersected the change range.
  19494. // Can't reuse a node that contains a parse error. This is necessary so that we
  19495. // produce the same set of errors again.
  19496. if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
  19497. return undefined;
  19498. }
  19499. // We can only reuse a node if it was parsed under the same strict mode that we're
  19500. // currently in. i.e. if we originally parsed a node in non-strict mode, but then
  19501. // the user added 'using strict' at the top of the file, then we can't use that node
  19502. // again as the presence of strict mode may cause us to parse the tokens in the file
  19503. // differently.
  19504. //
  19505. // Note: we *can* reuse tokens when the strict mode changes. That's because tokens
  19506. // are unaffected by strict mode. It's just the parser will decide what to do with it
  19507. // differently depending on what mode it is in.
  19508. //
  19509. // This also applies to all our other context flags as well.
  19510. var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
  19511. if (nodeContextFlags !== contextFlags) {
  19512. return undefined;
  19513. }
  19514. // Ok, we have a node that looks like it could be reused. Now verify that it is valid
  19515. // in the current list parsing context that we're currently at.
  19516. if (!canReuseNode(node, parsingContext)) {
  19517. return undefined;
  19518. }
  19519. if (node.jsDocCache) {
  19520. // jsDocCache may include tags from parent nodes, which might have been modified.
  19521. node.jsDocCache = undefined;
  19522. }
  19523. return node;
  19524. }
  19525. function consumeNode(node) {
  19526. // Move the scanner so it is after the node we just consumed.
  19527. scanner.setTextPos(node.end);
  19528. nextToken();
  19529. return node;
  19530. }
  19531. function isReusableParsingContext(parsingContext) {
  19532. switch (parsingContext) {
  19533. case 5 /* ClassMembers */:
  19534. case 2 /* SwitchClauses */:
  19535. case 0 /* SourceElements */:
  19536. case 1 /* BlockStatements */:
  19537. case 3 /* SwitchClauseStatements */:
  19538. case 6 /* EnumMembers */:
  19539. case 4 /* TypeMembers */:
  19540. case 8 /* VariableDeclarations */:
  19541. case 17 /* JSDocParameters */:
  19542. case 16 /* Parameters */:
  19543. return true;
  19544. }
  19545. return false;
  19546. }
  19547. function canReuseNode(node, parsingContext) {
  19548. switch (parsingContext) {
  19549. case 5 /* ClassMembers */:
  19550. return isReusableClassMember(node);
  19551. case 2 /* SwitchClauses */:
  19552. return isReusableSwitchClause(node);
  19553. case 0 /* SourceElements */:
  19554. case 1 /* BlockStatements */:
  19555. case 3 /* SwitchClauseStatements */:
  19556. return isReusableStatement(node);
  19557. case 6 /* EnumMembers */:
  19558. return isReusableEnumMember(node);
  19559. case 4 /* TypeMembers */:
  19560. return isReusableTypeMember(node);
  19561. case 8 /* VariableDeclarations */:
  19562. return isReusableVariableDeclaration(node);
  19563. case 17 /* JSDocParameters */:
  19564. case 16 /* Parameters */:
  19565. return isReusableParameter(node);
  19566. // Any other lists we do not care about reusing nodes in. But feel free to add if
  19567. // you can do so safely. Danger areas involve nodes that may involve speculative
  19568. // parsing. If speculative parsing is involved with the node, then the range the
  19569. // parser reached while looking ahead might be in the edited range (see the example
  19570. // in canReuseVariableDeclaratorNode for a good case of this).
  19571. // case ParsingContext.HeritageClauses:
  19572. // This would probably be safe to reuse. There is no speculative parsing with
  19573. // heritage clauses.
  19574. // case ParsingContext.TypeParameters:
  19575. // This would probably be safe to reuse. There is no speculative parsing with
  19576. // type parameters. Note that that's because type *parameters* only occur in
  19577. // unambiguous *type* contexts. While type *arguments* occur in very ambiguous
  19578. // *expression* contexts.
  19579. // case ParsingContext.TupleElementTypes:
  19580. // This would probably be safe to reuse. There is no speculative parsing with
  19581. // tuple types.
  19582. // Technically, type argument list types are probably safe to reuse. While
  19583. // speculative parsing is involved with them (since type argument lists are only
  19584. // produced from speculative parsing a < as a type argument list), we only have
  19585. // the types because speculative parsing succeeded. Thus, the lookahead never
  19586. // went past the end of the list and rewound.
  19587. // case ParsingContext.TypeArguments:
  19588. // Note: these are almost certainly not safe to ever reuse. Expressions commonly
  19589. // need a large amount of lookahead, and we should not reuse them as they may
  19590. // have actually intersected the edit.
  19591. // case ParsingContext.ArgumentExpressions:
  19592. // This is not safe to reuse for the same reason as the 'AssignmentExpression'
  19593. // cases. i.e. a property assignment may end with an expression, and thus might
  19594. // have lookahead far beyond it's old node.
  19595. // case ParsingContext.ObjectLiteralMembers:
  19596. // This is probably not safe to reuse. There can be speculative parsing with
  19597. // type names in a heritage clause. There can be generic names in the type
  19598. // name list, and there can be left hand side expressions (which can have type
  19599. // arguments.)
  19600. // case ParsingContext.HeritageClauseElement:
  19601. // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
  19602. // on any given element. Same for children.
  19603. // case ParsingContext.JsxAttributes:
  19604. // case ParsingContext.JsxChildren:
  19605. }
  19606. return false;
  19607. }
  19608. function isReusableClassMember(node) {
  19609. if (node) {
  19610. switch (node.kind) {
  19611. case 162 /* Constructor */:
  19612. case 167 /* IndexSignature */:
  19613. case 163 /* GetAccessor */:
  19614. case 164 /* SetAccessor */:
  19615. case 159 /* PropertyDeclaration */:
  19616. case 222 /* SemicolonClassElement */:
  19617. return true;
  19618. case 161 /* MethodDeclaration */:
  19619. // Method declarations are not necessarily reusable. An object-literal
  19620. // may have a method calls "constructor(...)" and we must reparse that
  19621. // into an actual .ConstructorDeclaration.
  19622. var methodDeclaration = node;
  19623. var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
  19624. methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
  19625. return !nameIsConstructor;
  19626. }
  19627. }
  19628. return false;
  19629. }
  19630. function isReusableSwitchClause(node) {
  19631. if (node) {
  19632. switch (node.kind) {
  19633. case 277 /* CaseClause */:
  19634. case 278 /* DefaultClause */:
  19635. return true;
  19636. }
  19637. }
  19638. return false;
  19639. }
  19640. function isReusableStatement(node) {
  19641. if (node) {
  19642. switch (node.kind) {
  19643. case 244 /* FunctionDeclaration */:
  19644. case 225 /* VariableStatement */:
  19645. case 223 /* Block */:
  19646. case 227 /* IfStatement */:
  19647. case 226 /* ExpressionStatement */:
  19648. case 239 /* ThrowStatement */:
  19649. case 235 /* ReturnStatement */:
  19650. case 237 /* SwitchStatement */:
  19651. case 234 /* BreakStatement */:
  19652. case 233 /* ContinueStatement */:
  19653. case 231 /* ForInStatement */:
  19654. case 232 /* ForOfStatement */:
  19655. case 230 /* ForStatement */:
  19656. case 229 /* WhileStatement */:
  19657. case 236 /* WithStatement */:
  19658. case 224 /* EmptyStatement */:
  19659. case 240 /* TryStatement */:
  19660. case 238 /* LabeledStatement */:
  19661. case 228 /* DoStatement */:
  19662. case 241 /* DebuggerStatement */:
  19663. case 254 /* ImportDeclaration */:
  19664. case 253 /* ImportEqualsDeclaration */:
  19665. case 260 /* ExportDeclaration */:
  19666. case 259 /* ExportAssignment */:
  19667. case 249 /* ModuleDeclaration */:
  19668. case 245 /* ClassDeclaration */:
  19669. case 246 /* InterfaceDeclaration */:
  19670. case 248 /* EnumDeclaration */:
  19671. case 247 /* TypeAliasDeclaration */:
  19672. return true;
  19673. }
  19674. }
  19675. return false;
  19676. }
  19677. function isReusableEnumMember(node) {
  19678. return node.kind === 284 /* EnumMember */;
  19679. }
  19680. function isReusableTypeMember(node) {
  19681. if (node) {
  19682. switch (node.kind) {
  19683. case 166 /* ConstructSignature */:
  19684. case 160 /* MethodSignature */:
  19685. case 167 /* IndexSignature */:
  19686. case 158 /* PropertySignature */:
  19687. case 165 /* CallSignature */:
  19688. return true;
  19689. }
  19690. }
  19691. return false;
  19692. }
  19693. function isReusableVariableDeclaration(node) {
  19694. if (node.kind !== 242 /* VariableDeclaration */) {
  19695. return false;
  19696. }
  19697. // Very subtle incremental parsing bug. Consider the following code:
  19698. //
  19699. // let v = new List < A, B
  19700. //
  19701. // This is actually legal code. It's a list of variable declarators "v = new List<A"
  19702. // on one side and "B" on the other. If you then change that to:
  19703. //
  19704. // let v = new List < A, B >()
  19705. //
  19706. // then we have a problem. "v = new List<A" doesn't intersect the change range, so we
  19707. // start reparsing at "B" and we completely fail to handle this properly.
  19708. //
  19709. // In order to prevent this, we do not allow a variable declarator to be reused if it
  19710. // has an initializer.
  19711. var variableDeclarator = node;
  19712. return variableDeclarator.initializer === undefined;
  19713. }
  19714. function isReusableParameter(node) {
  19715. if (node.kind !== 156 /* Parameter */) {
  19716. return false;
  19717. }
  19718. // See the comment in isReusableVariableDeclaration for why we do this.
  19719. var parameter = node;
  19720. return parameter.initializer === undefined;
  19721. }
  19722. // Returns true if we should abort parsing.
  19723. function abortParsingListOrMoveToNextToken(kind) {
  19724. parseErrorAtCurrentToken(parsingContextErrors(kind));
  19725. if (isInSomeParsingContext()) {
  19726. return true;
  19727. }
  19728. nextToken();
  19729. return false;
  19730. }
  19731. function parsingContextErrors(context) {
  19732. switch (context) {
  19733. case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
  19734. case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
  19735. case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
  19736. case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
  19737. case 18 /* RestProperties */: // fallthrough
  19738. case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
  19739. case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
  19740. case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
  19741. case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
  19742. case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
  19743. case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
  19744. case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
  19745. case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
  19746. case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
  19747. case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
  19748. case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
  19749. case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
  19750. case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
  19751. case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
  19752. case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
  19753. case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
  19754. case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
  19755. case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
  19756. case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
  19757. default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
  19758. }
  19759. }
  19760. // Parses a comma-delimited list of elements
  19761. function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
  19762. var saveParsingContext = parsingContext;
  19763. parsingContext |= 1 << kind;
  19764. var list = [];
  19765. var listPos = getNodePos();
  19766. var commaStart = -1; // Meaning the previous token was not a comma
  19767. while (true) {
  19768. if (isListElement(kind, /*inErrorRecovery*/ false)) {
  19769. var startPos = scanner.getStartPos();
  19770. list.push(parseListElement(kind, parseElement));
  19771. commaStart = scanner.getTokenPos();
  19772. if (parseOptional(27 /* CommaToken */)) {
  19773. // No need to check for a zero length node since we know we parsed a comma
  19774. continue;
  19775. }
  19776. commaStart = -1; // Back to the state where the last token was not a comma
  19777. if (isListTerminator(kind)) {
  19778. break;
  19779. }
  19780. // We didn't get a comma, and the list wasn't terminated, explicitly parse
  19781. // out a comma so we give a good error message.
  19782. parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
  19783. // If the token was a semicolon, and the caller allows that, then skip it and
  19784. // continue. This ensures we get back on track and don't result in tons of
  19785. // parse errors. For example, this can happen when people do things like use
  19786. // a semicolon to delimit object literal members. Note: we'll have already
  19787. // reported an error when we called parseExpected above.
  19788. if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
  19789. nextToken();
  19790. }
  19791. if (startPos === scanner.getStartPos()) {
  19792. // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
  19793. // Consume a token to advance the parser in some way and avoid an infinite loop
  19794. // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
  19795. // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
  19796. nextToken();
  19797. }
  19798. continue;
  19799. }
  19800. if (isListTerminator(kind)) {
  19801. break;
  19802. }
  19803. if (abortParsingListOrMoveToNextToken(kind)) {
  19804. break;
  19805. }
  19806. }
  19807. parsingContext = saveParsingContext;
  19808. var result = createNodeArray(list, listPos);
  19809. // Recording the trailing comma is deliberately done after the previous
  19810. // loop, and not just if we see a list terminator. This is because the list
  19811. // may have ended incorrectly, but it is still important to know if there
  19812. // was a trailing comma.
  19813. // Check if the last token was a comma.
  19814. if (commaStart >= 0) {
  19815. // Always preserve a trailing comma by marking it on the NodeArray
  19816. result.hasTrailingComma = true;
  19817. }
  19818. return result;
  19819. }
  19820. function getExpectedCommaDiagnostic(kind) {
  19821. return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
  19822. }
  19823. function createMissingList() {
  19824. var list = createNodeArray([], getNodePos());
  19825. list.isMissingList = true;
  19826. return list;
  19827. }
  19828. function isMissingList(arr) {
  19829. return !!arr.isMissingList;
  19830. }
  19831. function parseBracketedList(kind, parseElement, open, close) {
  19832. if (parseExpected(open)) {
  19833. var result = parseDelimitedList(kind, parseElement);
  19834. parseExpected(close);
  19835. return result;
  19836. }
  19837. return createMissingList();
  19838. }
  19839. function parseEntityName(allowReservedWords, diagnosticMessage) {
  19840. var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
  19841. var dotPos = scanner.getStartPos();
  19842. while (parseOptional(24 /* DotToken */)) {
  19843. if (token() === 29 /* LessThanToken */) {
  19844. // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
  19845. entity.jsdocDotPos = dotPos;
  19846. break;
  19847. }
  19848. dotPos = scanner.getStartPos();
  19849. entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
  19850. }
  19851. return entity;
  19852. }
  19853. function createQualifiedName(entity, name) {
  19854. var node = createNode(153 /* QualifiedName */, entity.pos);
  19855. node.left = entity;
  19856. node.right = name;
  19857. return finishNode(node);
  19858. }
  19859. function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
  19860. // Technically a keyword is valid here as all identifiers and keywords are identifier names.
  19861. // However, often we'll encounter this in error situations when the identifier or keyword
  19862. // is actually starting another valid construct.
  19863. //
  19864. // So, we check for the following specific case:
  19865. //
  19866. // name.
  19867. // identifierOrKeyword identifierNameOrKeyword
  19868. //
  19869. // Note: the newlines are important here. For example, if that above code
  19870. // were rewritten into:
  19871. //
  19872. // name.identifierOrKeyword
  19873. // identifierNameOrKeyword
  19874. //
  19875. // Then we would consider it valid. That's because ASI would take effect and
  19876. // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
  19877. // In the first case though, ASI will not take effect because there is not a
  19878. // line terminator after the identifier or keyword.
  19879. if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
  19880. var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
  19881. if (matchesPattern) {
  19882. // Report that we need an identifier. However, report it right after the dot,
  19883. // and not on the next token. This is because the next token might actually
  19884. // be an identifier and the error would be quite confusing.
  19885. return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
  19886. }
  19887. }
  19888. if (token() === 76 /* PrivateIdentifier */) {
  19889. var node = parsePrivateIdentifier();
  19890. return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
  19891. }
  19892. return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
  19893. }
  19894. function parseTemplateExpression() {
  19895. var template = createNode(211 /* TemplateExpression */);
  19896. template.head = parseTemplateHead();
  19897. ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
  19898. var list = [];
  19899. var listPos = getNodePos();
  19900. do {
  19901. list.push(parseTemplateSpan());
  19902. } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
  19903. template.templateSpans = createNodeArray(list, listPos);
  19904. return finishNode(template);
  19905. }
  19906. function parseTemplateSpan() {
  19907. var span = createNode(221 /* TemplateSpan */);
  19908. span.expression = allowInAnd(parseExpression);
  19909. var literal;
  19910. if (token() === 19 /* CloseBraceToken */) {
  19911. reScanTemplateToken();
  19912. literal = parseTemplateMiddleOrTemplateTail();
  19913. }
  19914. else {
  19915. literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
  19916. }
  19917. span.literal = literal;
  19918. return finishNode(span);
  19919. }
  19920. function parseLiteralNode() {
  19921. return parseLiteralLikeNode(token());
  19922. }
  19923. function parseTemplateHead() {
  19924. var fragment = parseLiteralLikeNode(token());
  19925. ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
  19926. return fragment;
  19927. }
  19928. function parseTemplateMiddleOrTemplateTail() {
  19929. var fragment = parseLiteralLikeNode(token());
  19930. ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
  19931. return fragment;
  19932. }
  19933. function parseLiteralLikeNode(kind) {
  19934. var node = createNode(kind);
  19935. node.text = scanner.getTokenValue();
  19936. switch (kind) {
  19937. case 14 /* NoSubstitutionTemplateLiteral */:
  19938. case 15 /* TemplateHead */:
  19939. case 16 /* TemplateMiddle */:
  19940. case 17 /* TemplateTail */:
  19941. var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
  19942. var tokenText = scanner.getTokenText();
  19943. node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
  19944. break;
  19945. }
  19946. if (scanner.hasExtendedUnicodeEscape()) {
  19947. node.hasExtendedUnicodeEscape = true;
  19948. }
  19949. if (scanner.isUnterminated()) {
  19950. node.isUnterminated = true;
  19951. }
  19952. // Octal literals are not allowed in strict mode or ES5
  19953. // Note that theoretically the following condition would hold true literals like 009,
  19954. // which is not octal.But because of how the scanner separates the tokens, we would
  19955. // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
  19956. // We also do not need to check for negatives because any prefix operator would be part of a
  19957. // parent unary expression.
  19958. if (node.kind === 8 /* NumericLiteral */) {
  19959. node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
  19960. }
  19961. nextToken();
  19962. finishNode(node);
  19963. return node;
  19964. }
  19965. // TYPES
  19966. function parseTypeReference() {
  19967. var node = createNode(169 /* TypeReference */);
  19968. node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
  19969. if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
  19970. node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
  19971. }
  19972. return finishNode(node);
  19973. }
  19974. // If true, we should abort parsing an error function.
  19975. function typeHasArrowFunctionBlockingParseError(node) {
  19976. switch (node.kind) {
  19977. case 169 /* TypeReference */:
  19978. return ts.nodeIsMissing(node.typeName);
  19979. case 170 /* FunctionType */:
  19980. case 171 /* ConstructorType */: {
  19981. var _a = node, parameters = _a.parameters, type = _a.type;
  19982. return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
  19983. }
  19984. case 182 /* ParenthesizedType */:
  19985. return typeHasArrowFunctionBlockingParseError(node.type);
  19986. default:
  19987. return false;
  19988. }
  19989. }
  19990. function parseThisTypePredicate(lhs) {
  19991. nextToken();
  19992. var node = createNode(168 /* TypePredicate */, lhs.pos);
  19993. node.parameterName = lhs;
  19994. node.type = parseType();
  19995. return finishNode(node);
  19996. }
  19997. function parseThisTypeNode() {
  19998. var node = createNode(183 /* ThisType */);
  19999. nextToken();
  20000. return finishNode(node);
  20001. }
  20002. function parseJSDocAllType(postFixEquals) {
  20003. var result = createNode(295 /* JSDocAllType */);
  20004. if (postFixEquals) {
  20005. return createPostfixType(299 /* JSDocOptionalType */, result);
  20006. }
  20007. else {
  20008. nextToken();
  20009. }
  20010. return finishNode(result);
  20011. }
  20012. function parseJSDocNonNullableType() {
  20013. var result = createNode(298 /* JSDocNonNullableType */);
  20014. nextToken();
  20015. result.type = parseNonArrayType();
  20016. return finishNode(result);
  20017. }
  20018. function parseJSDocUnknownOrNullableType() {
  20019. var pos = scanner.getStartPos();
  20020. // skip the ?
  20021. nextToken();
  20022. // Need to lookahead to decide if this is a nullable or unknown type.
  20023. // Here are cases where we'll pick the unknown type:
  20024. //
  20025. // Foo(?,
  20026. // { a: ? }
  20027. // Foo(?)
  20028. // Foo<?>
  20029. // Foo(?=
  20030. // (?|
  20031. if (token() === 27 /* CommaToken */ ||
  20032. token() === 19 /* CloseBraceToken */ ||
  20033. token() === 21 /* CloseParenToken */ ||
  20034. token() === 31 /* GreaterThanToken */ ||
  20035. token() === 62 /* EqualsToken */ ||
  20036. token() === 51 /* BarToken */) {
  20037. var result = createNode(296 /* JSDocUnknownType */, pos);
  20038. return finishNode(result);
  20039. }
  20040. else {
  20041. var result = createNode(297 /* JSDocNullableType */, pos);
  20042. result.type = parseType();
  20043. return finishNode(result);
  20044. }
  20045. }
  20046. function parseJSDocFunctionType() {
  20047. if (lookAhead(nextTokenIsOpenParen)) {
  20048. var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
  20049. nextToken();
  20050. fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
  20051. return finishNode(result);
  20052. }
  20053. var node = createNode(169 /* TypeReference */);
  20054. node.typeName = parseIdentifierName();
  20055. return finishNode(node);
  20056. }
  20057. function parseJSDocParameter() {
  20058. var parameter = createNode(156 /* Parameter */);
  20059. if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
  20060. parameter.name = parseIdentifierName();
  20061. parseExpected(58 /* ColonToken */);
  20062. }
  20063. parameter.type = parseJSDocType();
  20064. return finishNode(parameter);
  20065. }
  20066. function parseJSDocType() {
  20067. scanner.setInJSDocType(true);
  20068. var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
  20069. if (moduleSpecifier) {
  20070. var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
  20071. terminate: while (true) {
  20072. switch (token()) {
  20073. case 19 /* CloseBraceToken */:
  20074. case 1 /* EndOfFileToken */:
  20075. case 27 /* CommaToken */:
  20076. case 5 /* WhitespaceTrivia */:
  20077. break terminate;
  20078. default:
  20079. nextTokenJSDoc();
  20080. }
  20081. }
  20082. scanner.setInJSDocType(false);
  20083. return finishNode(moduleTag);
  20084. }
  20085. var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
  20086. var type = parseTypeOrTypePredicate();
  20087. scanner.setInJSDocType(false);
  20088. if (dotdotdot) {
  20089. var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
  20090. variadic.type = type;
  20091. type = finishNode(variadic);
  20092. }
  20093. if (token() === 62 /* EqualsToken */) {
  20094. return createPostfixType(299 /* JSDocOptionalType */, type);
  20095. }
  20096. return type;
  20097. }
  20098. function parseTypeQuery() {
  20099. var node = createNode(172 /* TypeQuery */);
  20100. parseExpected(108 /* TypeOfKeyword */);
  20101. node.exprName = parseEntityName(/*allowReservedWords*/ true);
  20102. return finishNode(node);
  20103. }
  20104. function parseTypeParameter() {
  20105. var node = createNode(155 /* TypeParameter */);
  20106. node.name = parseIdentifier();
  20107. if (parseOptional(90 /* ExtendsKeyword */)) {
  20108. // It's not uncommon for people to write improper constraints to a generic. If the
  20109. // user writes a constraint that is an expression and not an actual type, then parse
  20110. // it out as an expression (so we can recover well), but report that a type is needed
  20111. // instead.
  20112. if (isStartOfType() || !isStartOfExpression()) {
  20113. node.constraint = parseType();
  20114. }
  20115. else {
  20116. // It was not a type, and it looked like an expression. Parse out an expression
  20117. // here so we recover well. Note: it is important that we call parseUnaryExpression
  20118. // and not parseExpression here. If the user has:
  20119. //
  20120. // <T extends "">
  20121. //
  20122. // We do *not* want to consume the `>` as we're consuming the expression for "".
  20123. node.expression = parseUnaryExpressionOrHigher();
  20124. }
  20125. }
  20126. if (parseOptional(62 /* EqualsToken */)) {
  20127. node.default = parseType();
  20128. }
  20129. return finishNode(node);
  20130. }
  20131. function parseTypeParameters() {
  20132. if (token() === 29 /* LessThanToken */) {
  20133. return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
  20134. }
  20135. }
  20136. function parseParameterType() {
  20137. if (parseOptional(58 /* ColonToken */)) {
  20138. return parseType();
  20139. }
  20140. return undefined;
  20141. }
  20142. function isStartOfParameter(isJSDocParameter) {
  20143. return token() === 25 /* DotDotDotToken */ ||
  20144. isIdentifierOrPrivateIdentifierOrPattern() ||
  20145. ts.isModifierKind(token()) ||
  20146. token() === 59 /* AtToken */ ||
  20147. isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
  20148. }
  20149. function parseParameter() {
  20150. var node = createNodeWithJSDoc(156 /* Parameter */);
  20151. if (token() === 104 /* ThisKeyword */) {
  20152. node.name = createIdentifier(/*isIdentifier*/ true);
  20153. node.type = parseParameterType();
  20154. return finishNode(node);
  20155. }
  20156. node.decorators = parseDecorators();
  20157. node.modifiers = parseModifiers();
  20158. node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
  20159. // FormalParameter [Yield,Await]:
  20160. // BindingElement[?Yield,?Await]
  20161. node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
  20162. if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
  20163. // in cases like
  20164. // 'use strict'
  20165. // function foo(static)
  20166. // isParameter('static') === true, because of isModifier('static')
  20167. // however 'static' is not a legal identifier in a strict mode.
  20168. // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
  20169. // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
  20170. // to avoid this we'll advance cursor to the next token.
  20171. nextToken();
  20172. }
  20173. node.questionToken = parseOptionalToken(57 /* QuestionToken */);
  20174. node.type = parseParameterType();
  20175. node.initializer = parseInitializer();
  20176. return finishNode(node);
  20177. }
  20178. /**
  20179. * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
  20180. * @returns If return type parsing succeeds
  20181. */
  20182. function fillSignature(returnToken, flags, signature) {
  20183. if (!(flags & 32 /* JSDoc */)) {
  20184. signature.typeParameters = parseTypeParameters();
  20185. }
  20186. var parametersParsedSuccessfully = parseParameterList(signature, flags);
  20187. if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
  20188. signature.type = parseTypeOrTypePredicate();
  20189. if (typeHasArrowFunctionBlockingParseError(signature.type))
  20190. return false;
  20191. }
  20192. return parametersParsedSuccessfully;
  20193. }
  20194. function shouldParseReturnType(returnToken, isType) {
  20195. if (returnToken === 38 /* EqualsGreaterThanToken */) {
  20196. parseExpected(returnToken);
  20197. return true;
  20198. }
  20199. else if (parseOptional(58 /* ColonToken */)) {
  20200. return true;
  20201. }
  20202. else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
  20203. // This is easy to get backward, especially in type contexts, so parse the type anyway
  20204. parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
  20205. nextToken();
  20206. return true;
  20207. }
  20208. return false;
  20209. }
  20210. // Returns true on success.
  20211. function parseParameterList(signature, flags) {
  20212. // FormalParameters [Yield,Await]: (modified)
  20213. // [empty]
  20214. // FormalParameterList[?Yield,Await]
  20215. //
  20216. // FormalParameter[Yield,Await]: (modified)
  20217. // BindingElement[?Yield,Await]
  20218. //
  20219. // BindingElement [Yield,Await]: (modified)
  20220. // SingleNameBinding[?Yield,?Await]
  20221. // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
  20222. //
  20223. // SingleNameBinding [Yield,Await]:
  20224. // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
  20225. if (!parseExpected(20 /* OpenParenToken */)) {
  20226. signature.parameters = createMissingList();
  20227. return false;
  20228. }
  20229. var savedYieldContext = inYieldContext();
  20230. var savedAwaitContext = inAwaitContext();
  20231. setYieldContext(!!(flags & 1 /* Yield */));
  20232. setAwaitContext(!!(flags & 2 /* Await */));
  20233. signature.parameters = flags & 32 /* JSDoc */ ?
  20234. parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
  20235. parseDelimitedList(16 /* Parameters */, parseParameter);
  20236. setYieldContext(savedYieldContext);
  20237. setAwaitContext(savedAwaitContext);
  20238. return parseExpected(21 /* CloseParenToken */);
  20239. }
  20240. function parseTypeMemberSemicolon() {
  20241. // We allow type members to be separated by commas or (possibly ASI) semicolons.
  20242. // First check if it was a comma. If so, we're done with the member.
  20243. if (parseOptional(27 /* CommaToken */)) {
  20244. return;
  20245. }
  20246. // Didn't have a comma. We must have a (possible ASI) semicolon.
  20247. parseSemicolon();
  20248. }
  20249. function parseSignatureMember(kind) {
  20250. var node = createNodeWithJSDoc(kind);
  20251. if (kind === 166 /* ConstructSignature */) {
  20252. parseExpected(99 /* NewKeyword */);
  20253. }
  20254. fillSignature(58 /* ColonToken */, 4 /* Type */, node);
  20255. parseTypeMemberSemicolon();
  20256. return finishNode(node);
  20257. }
  20258. function isIndexSignature() {
  20259. return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
  20260. }
  20261. function isUnambiguouslyIndexSignature() {
  20262. // The only allowed sequence is:
  20263. //
  20264. // [id:
  20265. //
  20266. // However, for error recovery, we also check the following cases:
  20267. //
  20268. // [...
  20269. // [id,
  20270. // [id?,
  20271. // [id?:
  20272. // [id?]
  20273. // [public id
  20274. // [private id
  20275. // [protected id
  20276. // []
  20277. //
  20278. nextToken();
  20279. if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
  20280. return true;
  20281. }
  20282. if (ts.isModifierKind(token())) {
  20283. nextToken();
  20284. if (isIdentifier()) {
  20285. return true;
  20286. }
  20287. }
  20288. else if (!isIdentifier()) {
  20289. return false;
  20290. }
  20291. else {
  20292. // Skip the identifier
  20293. nextToken();
  20294. }
  20295. // A colon signifies a well formed indexer
  20296. // A comma should be a badly formed indexer because comma expressions are not allowed
  20297. // in computed properties.
  20298. if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
  20299. return true;
  20300. }
  20301. // Question mark could be an indexer with an optional property,
  20302. // or it could be a conditional expression in a computed property.
  20303. if (token() !== 57 /* QuestionToken */) {
  20304. return false;
  20305. }
  20306. // If any of the following tokens are after the question mark, it cannot
  20307. // be a conditional expression, so treat it as an indexer.
  20308. nextToken();
  20309. return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
  20310. }
  20311. function parseIndexSignatureDeclaration(node) {
  20312. node.kind = 167 /* IndexSignature */;
  20313. node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
  20314. node.type = parseTypeAnnotation();
  20315. parseTypeMemberSemicolon();
  20316. return finishNode(node);
  20317. }
  20318. function parsePropertyOrMethodSignature(node) {
  20319. node.name = parsePropertyName();
  20320. node.questionToken = parseOptionalToken(57 /* QuestionToken */);
  20321. if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
  20322. node.kind = 160 /* MethodSignature */;
  20323. // Method signatures don't exist in expression contexts. So they have neither
  20324. // [Yield] nor [Await]
  20325. fillSignature(58 /* ColonToken */, 4 /* Type */, node);
  20326. }
  20327. else {
  20328. node.kind = 158 /* PropertySignature */;
  20329. node.type = parseTypeAnnotation();
  20330. if (token() === 62 /* EqualsToken */) {
  20331. // Although type literal properties cannot not have initializers, we attempt
  20332. // to parse an initializer so we can report in the checker that an interface
  20333. // property or type literal property cannot have an initializer.
  20334. node.initializer = parseInitializer();
  20335. }
  20336. }
  20337. parseTypeMemberSemicolon();
  20338. return finishNode(node);
  20339. }
  20340. function isTypeMemberStart() {
  20341. // Return true if we have the start of a signature member
  20342. if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
  20343. return true;
  20344. }
  20345. var idToken = false;
  20346. // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
  20347. while (ts.isModifierKind(token())) {
  20348. idToken = true;
  20349. nextToken();
  20350. }
  20351. // Index signatures and computed property names are type members
  20352. if (token() === 22 /* OpenBracketToken */) {
  20353. return true;
  20354. }
  20355. // Try to get the first property-like token following all modifiers
  20356. if (isLiteralPropertyName()) {
  20357. idToken = true;
  20358. nextToken();
  20359. }
  20360. // If we were able to get any potential identifier, check that it is
  20361. // the start of a member declaration
  20362. if (idToken) {
  20363. return token() === 20 /* OpenParenToken */ ||
  20364. token() === 29 /* LessThanToken */ ||
  20365. token() === 57 /* QuestionToken */ ||
  20366. token() === 58 /* ColonToken */ ||
  20367. token() === 27 /* CommaToken */ ||
  20368. canParseSemicolon();
  20369. }
  20370. return false;
  20371. }
  20372. function parseTypeMember() {
  20373. if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
  20374. return parseSignatureMember(165 /* CallSignature */);
  20375. }
  20376. if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
  20377. return parseSignatureMember(166 /* ConstructSignature */);
  20378. }
  20379. var node = createNodeWithJSDoc(0 /* Unknown */);
  20380. node.modifiers = parseModifiers();
  20381. if (isIndexSignature()) {
  20382. return parseIndexSignatureDeclaration(node);
  20383. }
  20384. return parsePropertyOrMethodSignature(node);
  20385. }
  20386. function nextTokenIsOpenParenOrLessThan() {
  20387. nextToken();
  20388. return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
  20389. }
  20390. function nextTokenIsDot() {
  20391. return nextToken() === 24 /* DotToken */;
  20392. }
  20393. function nextTokenIsOpenParenOrLessThanOrDot() {
  20394. switch (nextToken()) {
  20395. case 20 /* OpenParenToken */:
  20396. case 29 /* LessThanToken */:
  20397. case 24 /* DotToken */:
  20398. return true;
  20399. }
  20400. return false;
  20401. }
  20402. function parseTypeLiteral() {
  20403. var node = createNode(173 /* TypeLiteral */);
  20404. node.members = parseObjectTypeMembers();
  20405. return finishNode(node);
  20406. }
  20407. function parseObjectTypeMembers() {
  20408. var members;
  20409. if (parseExpected(18 /* OpenBraceToken */)) {
  20410. members = parseList(4 /* TypeMembers */, parseTypeMember);
  20411. parseExpected(19 /* CloseBraceToken */);
  20412. }
  20413. else {
  20414. members = createMissingList();
  20415. }
  20416. return members;
  20417. }
  20418. function isStartOfMappedType() {
  20419. nextToken();
  20420. if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
  20421. return nextToken() === 138 /* ReadonlyKeyword */;
  20422. }
  20423. if (token() === 138 /* ReadonlyKeyword */) {
  20424. nextToken();
  20425. }
  20426. return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
  20427. }
  20428. function parseMappedTypeParameter() {
  20429. var node = createNode(155 /* TypeParameter */);
  20430. node.name = parseIdentifier();
  20431. parseExpected(97 /* InKeyword */);
  20432. node.constraint = parseType();
  20433. return finishNode(node);
  20434. }
  20435. function parseMappedType() {
  20436. var node = createNode(186 /* MappedType */);
  20437. parseExpected(18 /* OpenBraceToken */);
  20438. if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
  20439. node.readonlyToken = parseTokenNode();
  20440. if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
  20441. parseExpectedToken(138 /* ReadonlyKeyword */);
  20442. }
  20443. }
  20444. parseExpected(22 /* OpenBracketToken */);
  20445. node.typeParameter = parseMappedTypeParameter();
  20446. parseExpected(23 /* CloseBracketToken */);
  20447. if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
  20448. node.questionToken = parseTokenNode();
  20449. if (node.questionToken.kind !== 57 /* QuestionToken */) {
  20450. parseExpectedToken(57 /* QuestionToken */);
  20451. }
  20452. }
  20453. node.type = parseTypeAnnotation();
  20454. parseSemicolon();
  20455. parseExpected(19 /* CloseBraceToken */);
  20456. return finishNode(node);
  20457. }
  20458. function parseTupleElementType() {
  20459. var pos = getNodePos();
  20460. if (parseOptional(25 /* DotDotDotToken */)) {
  20461. var node = createNode(177 /* RestType */, pos);
  20462. node.type = parseType();
  20463. return finishNode(node);
  20464. }
  20465. var type = parseType();
  20466. if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
  20467. type.kind = 176 /* OptionalType */;
  20468. }
  20469. return type;
  20470. }
  20471. function parseTupleType() {
  20472. var node = createNode(175 /* TupleType */);
  20473. node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
  20474. return finishNode(node);
  20475. }
  20476. function parseParenthesizedType() {
  20477. var node = createNode(182 /* ParenthesizedType */);
  20478. parseExpected(20 /* OpenParenToken */);
  20479. node.type = parseType();
  20480. parseExpected(21 /* CloseParenToken */);
  20481. return finishNode(node);
  20482. }
  20483. function parseFunctionOrConstructorType() {
  20484. var pos = getNodePos();
  20485. var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
  20486. var node = createNodeWithJSDoc(kind, pos);
  20487. fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
  20488. return finishNode(node);
  20489. }
  20490. function parseKeywordAndNoDot() {
  20491. var node = parseTokenNode();
  20492. return token() === 24 /* DotToken */ ? undefined : node;
  20493. }
  20494. function parseLiteralTypeNode(negative) {
  20495. var node = createNode(187 /* LiteralType */);
  20496. var unaryMinusExpression;
  20497. if (negative) {
  20498. unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
  20499. unaryMinusExpression.operator = 40 /* MinusToken */;
  20500. nextToken();
  20501. }
  20502. var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
  20503. ? parseTokenNode()
  20504. : parseLiteralLikeNode(token());
  20505. if (negative) {
  20506. unaryMinusExpression.operand = expression;
  20507. finishNode(unaryMinusExpression);
  20508. expression = unaryMinusExpression;
  20509. }
  20510. node.literal = expression;
  20511. return finishNode(node);
  20512. }
  20513. function isStartOfTypeOfImportType() {
  20514. nextToken();
  20515. return token() === 96 /* ImportKeyword */;
  20516. }
  20517. function parseImportType() {
  20518. sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
  20519. var node = createNode(188 /* ImportType */);
  20520. if (parseOptional(108 /* TypeOfKeyword */)) {
  20521. node.isTypeOf = true;
  20522. }
  20523. parseExpected(96 /* ImportKeyword */);
  20524. parseExpected(20 /* OpenParenToken */);
  20525. node.argument = parseType();
  20526. parseExpected(21 /* CloseParenToken */);
  20527. if (parseOptional(24 /* DotToken */)) {
  20528. node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
  20529. }
  20530. if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
  20531. node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
  20532. }
  20533. return finishNode(node);
  20534. }
  20535. function nextTokenIsNumericOrBigIntLiteral() {
  20536. nextToken();
  20537. return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
  20538. }
  20539. function parseNonArrayType() {
  20540. switch (token()) {
  20541. case 125 /* AnyKeyword */:
  20542. case 148 /* UnknownKeyword */:
  20543. case 143 /* StringKeyword */:
  20544. case 140 /* NumberKeyword */:
  20545. case 151 /* BigIntKeyword */:
  20546. case 144 /* SymbolKeyword */:
  20547. case 128 /* BooleanKeyword */:
  20548. case 146 /* UndefinedKeyword */:
  20549. case 137 /* NeverKeyword */:
  20550. case 141 /* ObjectKeyword */:
  20551. // If these are followed by a dot, then parse these out as a dotted type reference instead.
  20552. return tryParse(parseKeywordAndNoDot) || parseTypeReference();
  20553. case 41 /* AsteriskToken */:
  20554. return parseJSDocAllType(/*postfixEquals*/ false);
  20555. case 65 /* AsteriskEqualsToken */:
  20556. return parseJSDocAllType(/*postfixEquals*/ true);
  20557. case 60 /* QuestionQuestionToken */:
  20558. // If there is '??', consider that is prefix '?' in JSDoc type.
  20559. scanner.reScanQuestionToken();
  20560. // falls through
  20561. case 57 /* QuestionToken */:
  20562. return parseJSDocUnknownOrNullableType();
  20563. case 94 /* FunctionKeyword */:
  20564. return parseJSDocFunctionType();
  20565. case 53 /* ExclamationToken */:
  20566. return parseJSDocNonNullableType();
  20567. case 14 /* NoSubstitutionTemplateLiteral */:
  20568. case 10 /* StringLiteral */:
  20569. case 8 /* NumericLiteral */:
  20570. case 9 /* BigIntLiteral */:
  20571. case 106 /* TrueKeyword */:
  20572. case 91 /* FalseKeyword */:
  20573. return parseLiteralTypeNode();
  20574. case 40 /* MinusToken */:
  20575. return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
  20576. case 110 /* VoidKeyword */:
  20577. case 100 /* NullKeyword */:
  20578. return parseTokenNode();
  20579. case 104 /* ThisKeyword */: {
  20580. var thisKeyword = parseThisTypeNode();
  20581. if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
  20582. return parseThisTypePredicate(thisKeyword);
  20583. }
  20584. else {
  20585. return thisKeyword;
  20586. }
  20587. }
  20588. case 108 /* TypeOfKeyword */:
  20589. return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
  20590. case 18 /* OpenBraceToken */:
  20591. return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
  20592. case 22 /* OpenBracketToken */:
  20593. return parseTupleType();
  20594. case 20 /* OpenParenToken */:
  20595. return parseParenthesizedType();
  20596. case 96 /* ImportKeyword */:
  20597. return parseImportType();
  20598. case 124 /* AssertsKeyword */:
  20599. return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
  20600. default:
  20601. return parseTypeReference();
  20602. }
  20603. }
  20604. function isStartOfType(inStartOfParameter) {
  20605. switch (token()) {
  20606. case 125 /* AnyKeyword */:
  20607. case 148 /* UnknownKeyword */:
  20608. case 143 /* StringKeyword */:
  20609. case 140 /* NumberKeyword */:
  20610. case 151 /* BigIntKeyword */:
  20611. case 128 /* BooleanKeyword */:
  20612. case 138 /* ReadonlyKeyword */:
  20613. case 144 /* SymbolKeyword */:
  20614. case 147 /* UniqueKeyword */:
  20615. case 110 /* VoidKeyword */:
  20616. case 146 /* UndefinedKeyword */:
  20617. case 100 /* NullKeyword */:
  20618. case 104 /* ThisKeyword */:
  20619. case 108 /* TypeOfKeyword */:
  20620. case 137 /* NeverKeyword */:
  20621. case 18 /* OpenBraceToken */:
  20622. case 22 /* OpenBracketToken */:
  20623. case 29 /* LessThanToken */:
  20624. case 51 /* BarToken */:
  20625. case 50 /* AmpersandToken */:
  20626. case 99 /* NewKeyword */:
  20627. case 10 /* StringLiteral */:
  20628. case 8 /* NumericLiteral */:
  20629. case 9 /* BigIntLiteral */:
  20630. case 106 /* TrueKeyword */:
  20631. case 91 /* FalseKeyword */:
  20632. case 141 /* ObjectKeyword */:
  20633. case 41 /* AsteriskToken */:
  20634. case 57 /* QuestionToken */:
  20635. case 53 /* ExclamationToken */:
  20636. case 25 /* DotDotDotToken */:
  20637. case 132 /* InferKeyword */:
  20638. case 96 /* ImportKeyword */:
  20639. case 124 /* AssertsKeyword */:
  20640. return true;
  20641. case 94 /* FunctionKeyword */:
  20642. return !inStartOfParameter;
  20643. case 40 /* MinusToken */:
  20644. return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
  20645. case 20 /* OpenParenToken */:
  20646. // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
  20647. // or something that starts a type. We don't want to consider things like '(1)' a type.
  20648. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
  20649. default:
  20650. return isIdentifier();
  20651. }
  20652. }
  20653. function isStartOfParenthesizedOrFunctionType() {
  20654. nextToken();
  20655. return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
  20656. }
  20657. function parsePostfixTypeOrHigher() {
  20658. var type = parseNonArrayType();
  20659. while (!scanner.hasPrecedingLineBreak()) {
  20660. switch (token()) {
  20661. case 53 /* ExclamationToken */:
  20662. type = createPostfixType(298 /* JSDocNonNullableType */, type);
  20663. break;
  20664. case 57 /* QuestionToken */:
  20665. // If not in JSDoc and next token is start of a type we have a conditional type
  20666. if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
  20667. return type;
  20668. }
  20669. type = createPostfixType(297 /* JSDocNullableType */, type);
  20670. break;
  20671. case 22 /* OpenBracketToken */:
  20672. parseExpected(22 /* OpenBracketToken */);
  20673. if (isStartOfType()) {
  20674. var node = createNode(185 /* IndexedAccessType */, type.pos);
  20675. node.objectType = type;
  20676. node.indexType = parseType();
  20677. parseExpected(23 /* CloseBracketToken */);
  20678. type = finishNode(node);
  20679. }
  20680. else {
  20681. var node = createNode(174 /* ArrayType */, type.pos);
  20682. node.elementType = type;
  20683. parseExpected(23 /* CloseBracketToken */);
  20684. type = finishNode(node);
  20685. }
  20686. break;
  20687. default:
  20688. return type;
  20689. }
  20690. }
  20691. return type;
  20692. }
  20693. function createPostfixType(kind, type) {
  20694. nextToken();
  20695. var postfix = createNode(kind, type.pos);
  20696. postfix.type = type;
  20697. return finishNode(postfix);
  20698. }
  20699. function parseTypeOperator(operator) {
  20700. var node = createNode(184 /* TypeOperator */);
  20701. parseExpected(operator);
  20702. node.operator = operator;
  20703. node.type = parseTypeOperatorOrHigher();
  20704. return finishNode(node);
  20705. }
  20706. function parseInferType() {
  20707. var node = createNode(181 /* InferType */);
  20708. parseExpected(132 /* InferKeyword */);
  20709. var typeParameter = createNode(155 /* TypeParameter */);
  20710. typeParameter.name = parseIdentifier();
  20711. node.typeParameter = finishNode(typeParameter);
  20712. return finishNode(node);
  20713. }
  20714. function parseTypeOperatorOrHigher() {
  20715. var operator = token();
  20716. switch (operator) {
  20717. case 134 /* KeyOfKeyword */:
  20718. case 147 /* UniqueKeyword */:
  20719. case 138 /* ReadonlyKeyword */:
  20720. return parseTypeOperator(operator);
  20721. case 132 /* InferKeyword */:
  20722. return parseInferType();
  20723. }
  20724. return parsePostfixTypeOrHigher();
  20725. }
  20726. function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  20727. var start = scanner.getStartPos();
  20728. var hasLeadingOperator = parseOptional(operator);
  20729. var type = parseConstituentType();
  20730. if (token() === operator || hasLeadingOperator) {
  20731. var types = [type];
  20732. while (parseOptional(operator)) {
  20733. types.push(parseConstituentType());
  20734. }
  20735. var node = createNode(kind, start);
  20736. node.types = createNodeArray(types, start);
  20737. type = finishNode(node);
  20738. }
  20739. return type;
  20740. }
  20741. function parseIntersectionTypeOrHigher() {
  20742. return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
  20743. }
  20744. function parseUnionTypeOrHigher() {
  20745. return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
  20746. }
  20747. function isStartOfFunctionType() {
  20748. if (token() === 29 /* LessThanToken */) {
  20749. return true;
  20750. }
  20751. return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
  20752. }
  20753. function skipParameterStart() {
  20754. if (ts.isModifierKind(token())) {
  20755. // Skip modifiers
  20756. parseModifiers();
  20757. }
  20758. if (isIdentifier() || token() === 104 /* ThisKeyword */) {
  20759. nextToken();
  20760. return true;
  20761. }
  20762. if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
  20763. // Return true if we can parse an array or object binding pattern with no errors
  20764. var previousErrorCount = parseDiagnostics.length;
  20765. parseIdentifierOrPattern();
  20766. return previousErrorCount === parseDiagnostics.length;
  20767. }
  20768. return false;
  20769. }
  20770. function isUnambiguouslyStartOfFunctionType() {
  20771. nextToken();
  20772. if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
  20773. // ( )
  20774. // ( ...
  20775. return true;
  20776. }
  20777. if (skipParameterStart()) {
  20778. // We successfully skipped modifiers (if any) and an identifier or binding pattern,
  20779. // now see if we have something that indicates a parameter declaration
  20780. if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
  20781. token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
  20782. // ( xxx :
  20783. // ( xxx ,
  20784. // ( xxx ?
  20785. // ( xxx =
  20786. return true;
  20787. }
  20788. if (token() === 21 /* CloseParenToken */) {
  20789. nextToken();
  20790. if (token() === 38 /* EqualsGreaterThanToken */) {
  20791. // ( xxx ) =>
  20792. return true;
  20793. }
  20794. }
  20795. }
  20796. return false;
  20797. }
  20798. function parseTypeOrTypePredicate() {
  20799. var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
  20800. var type = parseType();
  20801. if (typePredicateVariable) {
  20802. var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
  20803. node.assertsModifier = undefined;
  20804. node.parameterName = typePredicateVariable;
  20805. node.type = type;
  20806. return finishNode(node);
  20807. }
  20808. else {
  20809. return type;
  20810. }
  20811. }
  20812. function parseTypePredicatePrefix() {
  20813. var id = parseIdentifier();
  20814. if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
  20815. nextToken();
  20816. return id;
  20817. }
  20818. }
  20819. function parseAssertsTypePredicate() {
  20820. var node = createNode(168 /* TypePredicate */);
  20821. node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
  20822. node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
  20823. node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
  20824. return finishNode(node);
  20825. }
  20826. function parseType() {
  20827. // The rules about 'yield' only apply to actual code/expression contexts. They don't
  20828. // apply to 'type' contexts. So we disable these parameters here before moving on.
  20829. return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
  20830. }
  20831. function parseTypeWorker(noConditionalTypes) {
  20832. if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
  20833. return parseFunctionOrConstructorType();
  20834. }
  20835. var type = parseUnionTypeOrHigher();
  20836. if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
  20837. var node = createNode(180 /* ConditionalType */, type.pos);
  20838. node.checkType = type;
  20839. // The type following 'extends' is not permitted to be another conditional type
  20840. node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
  20841. parseExpected(57 /* QuestionToken */);
  20842. node.trueType = parseTypeWorker();
  20843. parseExpected(58 /* ColonToken */);
  20844. node.falseType = parseTypeWorker();
  20845. return finishNode(node);
  20846. }
  20847. return type;
  20848. }
  20849. function parseTypeAnnotation() {
  20850. return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
  20851. }
  20852. // EXPRESSIONS
  20853. function isStartOfLeftHandSideExpression() {
  20854. switch (token()) {
  20855. case 104 /* ThisKeyword */:
  20856. case 102 /* SuperKeyword */:
  20857. case 100 /* NullKeyword */:
  20858. case 106 /* TrueKeyword */:
  20859. case 91 /* FalseKeyword */:
  20860. case 8 /* NumericLiteral */:
  20861. case 9 /* BigIntLiteral */:
  20862. case 10 /* StringLiteral */:
  20863. case 14 /* NoSubstitutionTemplateLiteral */:
  20864. case 15 /* TemplateHead */:
  20865. case 20 /* OpenParenToken */:
  20866. case 22 /* OpenBracketToken */:
  20867. case 18 /* OpenBraceToken */:
  20868. case 94 /* FunctionKeyword */:
  20869. case 80 /* ClassKeyword */:
  20870. case 99 /* NewKeyword */:
  20871. case 43 /* SlashToken */:
  20872. case 67 /* SlashEqualsToken */:
  20873. case 75 /* Identifier */:
  20874. return true;
  20875. case 96 /* ImportKeyword */:
  20876. return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
  20877. default:
  20878. return isIdentifier();
  20879. }
  20880. }
  20881. function isStartOfExpression() {
  20882. if (isStartOfLeftHandSideExpression()) {
  20883. return true;
  20884. }
  20885. switch (token()) {
  20886. case 39 /* PlusToken */:
  20887. case 40 /* MinusToken */:
  20888. case 54 /* TildeToken */:
  20889. case 53 /* ExclamationToken */:
  20890. case 85 /* DeleteKeyword */:
  20891. case 108 /* TypeOfKeyword */:
  20892. case 110 /* VoidKeyword */:
  20893. case 45 /* PlusPlusToken */:
  20894. case 46 /* MinusMinusToken */:
  20895. case 29 /* LessThanToken */:
  20896. case 127 /* AwaitKeyword */:
  20897. case 121 /* YieldKeyword */:
  20898. case 76 /* PrivateIdentifier */:
  20899. // Yield/await always starts an expression. Either it is an identifier (in which case
  20900. // it is definitely an expression). Or it's a keyword (either because we're in
  20901. // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
  20902. return true;
  20903. default:
  20904. // Error tolerance. If we see the start of some binary operator, we consider
  20905. // that the start of an expression. That way we'll parse out a missing identifier,
  20906. // give a good message about an identifier being missing, and then consume the
  20907. // rest of the binary expression.
  20908. if (isBinaryOperator()) {
  20909. return true;
  20910. }
  20911. return isIdentifier();
  20912. }
  20913. }
  20914. function isStartOfExpressionStatement() {
  20915. // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
  20916. return token() !== 18 /* OpenBraceToken */ &&
  20917. token() !== 94 /* FunctionKeyword */ &&
  20918. token() !== 80 /* ClassKeyword */ &&
  20919. token() !== 59 /* AtToken */ &&
  20920. isStartOfExpression();
  20921. }
  20922. function parseExpression() {
  20923. // Expression[in]:
  20924. // AssignmentExpression[in]
  20925. // Expression[in] , AssignmentExpression[in]
  20926. // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
  20927. var saveDecoratorContext = inDecoratorContext();
  20928. if (saveDecoratorContext) {
  20929. setDecoratorContext(/*val*/ false);
  20930. }
  20931. var expr = parseAssignmentExpressionOrHigher();
  20932. var operatorToken;
  20933. while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
  20934. expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
  20935. }
  20936. if (saveDecoratorContext) {
  20937. setDecoratorContext(/*val*/ true);
  20938. }
  20939. return expr;
  20940. }
  20941. function parseInitializer() {
  20942. return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
  20943. }
  20944. function parseAssignmentExpressionOrHigher() {
  20945. // AssignmentExpression[in,yield]:
  20946. // 1) ConditionalExpression[?in,?yield]
  20947. // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
  20948. // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
  20949. // 4) ArrowFunctionExpression[?in,?yield]
  20950. // 5) AsyncArrowFunctionExpression[in,yield,await]
  20951. // 6) [+Yield] YieldExpression[?In]
  20952. //
  20953. // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
  20954. // (i.e. they're both BinaryExpressions with an assignment operator in it).
  20955. // First, do the simple check if we have a YieldExpression (production '6').
  20956. if (isYieldExpression()) {
  20957. return parseYieldExpression();
  20958. }
  20959. // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
  20960. // parameter list or is an async arrow function.
  20961. // AsyncArrowFunctionExpression:
  20962. // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
  20963. // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
  20964. // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
  20965. // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
  20966. //
  20967. // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
  20968. // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done
  20969. // with AssignmentExpression if we see one.
  20970. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
  20971. if (arrowExpression) {
  20972. return arrowExpression;
  20973. }
  20974. // Now try to see if we're in production '1', '2' or '3'. A conditional expression can
  20975. // start with a LogicalOrExpression, while the assignment productions can only start with
  20976. // LeftHandSideExpressions.
  20977. //
  20978. // So, first, we try to just parse out a BinaryExpression. If we get something that is a
  20979. // LeftHandSide or higher, then we can try to parse out the assignment expression part.
  20980. // Otherwise, we try to parse out the conditional expression bit. We want to allow any
  20981. // binary expression here, so we pass in the 'lowest' precedence here so that it matches
  20982. // and consumes anything.
  20983. var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
  20984. // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
  20985. // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
  20986. // identifier and the current token is an arrow.
  20987. if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
  20988. return parseSimpleArrowFunctionExpression(expr);
  20989. }
  20990. // Now see if we might be in cases '2' or '3'.
  20991. // If the expression was a LHS expression, and we have an assignment operator, then
  20992. // we're in '2' or '3'. Consume the assignment and return.
  20993. //
  20994. // Note: we call reScanGreaterToken so that we get an appropriately merged token
  20995. // for cases like `> > =` becoming `>>=`
  20996. if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
  20997. return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
  20998. }
  20999. // It wasn't an assignment or a lambda. This is a conditional expression:
  21000. return parseConditionalExpressionRest(expr);
  21001. }
  21002. function isYieldExpression() {
  21003. if (token() === 121 /* YieldKeyword */) {
  21004. // If we have a 'yield' keyword, and this is a context where yield expressions are
  21005. // allowed, then definitely parse out a yield expression.
  21006. if (inYieldContext()) {
  21007. return true;
  21008. }
  21009. // We're in a context where 'yield expr' is not allowed. However, if we can
  21010. // definitely tell that the user was trying to parse a 'yield expr' and not
  21011. // just a normal expr that start with a 'yield' identifier, then parse out
  21012. // a 'yield expr'. We can then report an error later that they are only
  21013. // allowed in generator expressions.
  21014. //
  21015. // for example, if we see 'yield(foo)', then we'll have to treat that as an
  21016. // invocation expression of something called 'yield'. However, if we have
  21017. // 'yield foo' then that is not legal as a normal expression, so we can
  21018. // definitely recognize this as a yield expression.
  21019. //
  21020. // for now we just check if the next token is an identifier. More heuristics
  21021. // can be added here later as necessary. We just need to make sure that we
  21022. // don't accidentally consume something legal.
  21023. return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
  21024. }
  21025. return false;
  21026. }
  21027. function nextTokenIsIdentifierOnSameLine() {
  21028. nextToken();
  21029. return !scanner.hasPrecedingLineBreak() && isIdentifier();
  21030. }
  21031. function parseYieldExpression() {
  21032. var node = createNode(212 /* YieldExpression */);
  21033. // YieldExpression[In] :
  21034. // yield
  21035. // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
  21036. // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
  21037. nextToken();
  21038. if (!scanner.hasPrecedingLineBreak() &&
  21039. (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
  21040. node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
  21041. node.expression = parseAssignmentExpressionOrHigher();
  21042. return finishNode(node);
  21043. }
  21044. else {
  21045. // if the next token is not on the same line as yield. or we don't have an '*' or
  21046. // the start of an expression, then this is just a simple "yield" expression.
  21047. return finishNode(node);
  21048. }
  21049. }
  21050. function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
  21051. ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
  21052. var node;
  21053. if (asyncModifier) {
  21054. node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
  21055. node.modifiers = asyncModifier;
  21056. }
  21057. else {
  21058. node = createNode(202 /* ArrowFunction */, identifier.pos);
  21059. }
  21060. var parameter = createNode(156 /* Parameter */, identifier.pos);
  21061. parameter.name = identifier;
  21062. finishNode(parameter);
  21063. node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
  21064. node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
  21065. node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
  21066. return addJSDocComment(finishNode(node));
  21067. }
  21068. function tryParseParenthesizedArrowFunctionExpression() {
  21069. var triState = isParenthesizedArrowFunctionExpression();
  21070. if (triState === 0 /* False */) {
  21071. // It's definitely not a parenthesized arrow function expression.
  21072. return undefined;
  21073. }
  21074. // If we definitely have an arrow function, then we can just parse one, not requiring a
  21075. // following => or { token. Otherwise, we *might* have an arrow function. Try to parse
  21076. // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
  21077. // expression instead.
  21078. var arrowFunction = triState === 1 /* True */
  21079. ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
  21080. : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
  21081. if (!arrowFunction) {
  21082. // Didn't appear to actually be a parenthesized arrow function. Just bail out.
  21083. return undefined;
  21084. }
  21085. var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
  21086. // If we have an arrow, then try to parse the body. Even if not, try to parse if we
  21087. // have an opening brace, just in case we're in an error state.
  21088. var lastToken = token();
  21089. arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
  21090. arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
  21091. ? parseArrowFunctionExpressionBody(isAsync)
  21092. : parseIdentifier();
  21093. return finishNode(arrowFunction);
  21094. }
  21095. // True -> We definitely expect a parenthesized arrow function here.
  21096. // False -> There *cannot* be a parenthesized arrow function here.
  21097. // Unknown -> There *might* be a parenthesized arrow function here.
  21098. // Speculatively look ahead to be sure, and rollback if not.
  21099. function isParenthesizedArrowFunctionExpression() {
  21100. if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
  21101. return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
  21102. }
  21103. if (token() === 38 /* EqualsGreaterThanToken */) {
  21104. // ERROR RECOVERY TWEAK:
  21105. // If we see a standalone => try to parse it as an arrow function expression as that's
  21106. // likely what the user intended to write.
  21107. return 1 /* True */;
  21108. }
  21109. // Definitely not a parenthesized arrow function.
  21110. return 0 /* False */;
  21111. }
  21112. function isParenthesizedArrowFunctionExpressionWorker() {
  21113. if (token() === 126 /* AsyncKeyword */) {
  21114. nextToken();
  21115. if (scanner.hasPrecedingLineBreak()) {
  21116. return 0 /* False */;
  21117. }
  21118. if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
  21119. return 0 /* False */;
  21120. }
  21121. }
  21122. var first = token();
  21123. var second = nextToken();
  21124. if (first === 20 /* OpenParenToken */) {
  21125. if (second === 21 /* CloseParenToken */) {
  21126. // Simple cases: "() =>", "(): ", and "() {".
  21127. // This is an arrow function with no parameters.
  21128. // The last one is not actually an arrow function,
  21129. // but this is probably what the user intended.
  21130. var third = nextToken();
  21131. switch (third) {
  21132. case 38 /* EqualsGreaterThanToken */:
  21133. case 58 /* ColonToken */:
  21134. case 18 /* OpenBraceToken */:
  21135. return 1 /* True */;
  21136. default:
  21137. return 0 /* False */;
  21138. }
  21139. }
  21140. // If encounter "([" or "({", this could be the start of a binding pattern.
  21141. // Examples:
  21142. // ([ x ]) => { }
  21143. // ({ x }) => { }
  21144. // ([ x ])
  21145. // ({ x })
  21146. if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
  21147. return 2 /* Unknown */;
  21148. }
  21149. // Simple case: "(..."
  21150. // This is an arrow function with a rest parameter.
  21151. if (second === 25 /* DotDotDotToken */) {
  21152. return 1 /* True */;
  21153. }
  21154. // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
  21155. // isn't actually allowed, but we want to treat it as a lambda so we can provide
  21156. // a good error message.
  21157. if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
  21158. return 1 /* True */;
  21159. }
  21160. // If we had "(" followed by something that's not an identifier,
  21161. // then this definitely doesn't look like a lambda. "this" is not
  21162. // valid, but we want to parse it and then give a semantic error.
  21163. if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
  21164. return 0 /* False */;
  21165. }
  21166. switch (nextToken()) {
  21167. case 58 /* ColonToken */:
  21168. // If we have something like "(a:", then we must have a
  21169. // type-annotated parameter in an arrow function expression.
  21170. return 1 /* True */;
  21171. case 57 /* QuestionToken */:
  21172. nextToken();
  21173. // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
  21174. if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
  21175. return 1 /* True */;
  21176. }
  21177. // Otherwise it is definitely not a lambda.
  21178. return 0 /* False */;
  21179. case 27 /* CommaToken */:
  21180. case 62 /* EqualsToken */:
  21181. case 21 /* CloseParenToken */:
  21182. // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
  21183. return 2 /* Unknown */;
  21184. }
  21185. // It is definitely not an arrow function
  21186. return 0 /* False */;
  21187. }
  21188. else {
  21189. ts.Debug.assert(first === 29 /* LessThanToken */);
  21190. // If we have "<" not followed by an identifier,
  21191. // then this definitely is not an arrow function.
  21192. if (!isIdentifier()) {
  21193. return 0 /* False */;
  21194. }
  21195. // JSX overrides
  21196. if (sourceFile.languageVariant === 1 /* JSX */) {
  21197. var isArrowFunctionInJsx = lookAhead(function () {
  21198. var third = nextToken();
  21199. if (third === 90 /* ExtendsKeyword */) {
  21200. var fourth = nextToken();
  21201. switch (fourth) {
  21202. case 62 /* EqualsToken */:
  21203. case 31 /* GreaterThanToken */:
  21204. return false;
  21205. default:
  21206. return true;
  21207. }
  21208. }
  21209. else if (third === 27 /* CommaToken */) {
  21210. return true;
  21211. }
  21212. return false;
  21213. });
  21214. if (isArrowFunctionInJsx) {
  21215. return 1 /* True */;
  21216. }
  21217. return 0 /* False */;
  21218. }
  21219. // This *could* be a parenthesized arrow function.
  21220. return 2 /* Unknown */;
  21221. }
  21222. }
  21223. function parsePossibleParenthesizedArrowFunctionExpressionHead() {
  21224. var tokenPos = scanner.getTokenPos();
  21225. if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
  21226. return undefined;
  21227. }
  21228. var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
  21229. if (!result) {
  21230. (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
  21231. }
  21232. return result;
  21233. }
  21234. function tryParseAsyncSimpleArrowFunctionExpression() {
  21235. // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
  21236. if (token() === 126 /* AsyncKeyword */) {
  21237. if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
  21238. var asyncModifier = parseModifiersForArrowFunction();
  21239. var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
  21240. return parseSimpleArrowFunctionExpression(expr, asyncModifier);
  21241. }
  21242. }
  21243. return undefined;
  21244. }
  21245. function isUnParenthesizedAsyncArrowFunctionWorker() {
  21246. // AsyncArrowFunctionExpression:
  21247. // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
  21248. // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
  21249. if (token() === 126 /* AsyncKeyword */) {
  21250. nextToken();
  21251. // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
  21252. // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
  21253. if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
  21254. return 0 /* False */;
  21255. }
  21256. // Check for un-parenthesized AsyncArrowFunction
  21257. var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
  21258. if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
  21259. return 1 /* True */;
  21260. }
  21261. }
  21262. return 0 /* False */;
  21263. }
  21264. function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
  21265. var node = createNodeWithJSDoc(202 /* ArrowFunction */);
  21266. node.modifiers = parseModifiersForArrowFunction();
  21267. var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
  21268. // Arrow functions are never generators.
  21269. //
  21270. // If we're speculatively parsing a signature for a parenthesized arrow function, then
  21271. // we have to have a complete parameter list. Otherwise we might see something like
  21272. // a => (b => c)
  21273. // And think that "(b =>" was actually a parenthesized arrow function with a missing
  21274. // close paren.
  21275. if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
  21276. return undefined;
  21277. }
  21278. // Parsing a signature isn't enough.
  21279. // Parenthesized arrow signatures often look like other valid expressions.
  21280. // For instance:
  21281. // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
  21282. // - "(x,y)" is a comma expression parsed as a signature with two parameters.
  21283. // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
  21284. // - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
  21285. //
  21286. // So we need just a bit of lookahead to ensure that it can only be a signature.
  21287. var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
  21288. if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
  21289. // Returning undefined here will cause our caller to rewind to where we started from.
  21290. return undefined;
  21291. }
  21292. return node;
  21293. }
  21294. function parseArrowFunctionExpressionBody(isAsync) {
  21295. if (token() === 18 /* OpenBraceToken */) {
  21296. return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
  21297. }
  21298. if (token() !== 26 /* SemicolonToken */ &&
  21299. token() !== 94 /* FunctionKeyword */ &&
  21300. token() !== 80 /* ClassKeyword */ &&
  21301. isStartOfStatement() &&
  21302. !isStartOfExpressionStatement()) {
  21303. // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
  21304. //
  21305. // Here we try to recover from a potential error situation in the case where the
  21306. // user meant to supply a block. For example, if the user wrote:
  21307. //
  21308. // a =>
  21309. // let v = 0;
  21310. // }
  21311. //
  21312. // they may be missing an open brace. Check to see if that's the case so we can
  21313. // try to recover better. If we don't do this, then the next close curly we see may end
  21314. // up preemptively closing the containing construct.
  21315. //
  21316. // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
  21317. return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
  21318. }
  21319. return isAsync
  21320. ? doInAwaitContext(parseAssignmentExpressionOrHigher)
  21321. : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
  21322. }
  21323. function parseConditionalExpressionRest(leftOperand) {
  21324. // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
  21325. var questionToken = parseOptionalToken(57 /* QuestionToken */);
  21326. if (!questionToken) {
  21327. return leftOperand;
  21328. }
  21329. // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
  21330. // we do not that for the 'whenFalse' part.
  21331. var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
  21332. node.condition = leftOperand;
  21333. node.questionToken = questionToken;
  21334. node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
  21335. node.colonToken = parseExpectedToken(58 /* ColonToken */);
  21336. node.whenFalse = ts.nodeIsPresent(node.colonToken)
  21337. ? parseAssignmentExpressionOrHigher()
  21338. : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
  21339. return finishNode(node);
  21340. }
  21341. function parseBinaryExpressionOrHigher(precedence) {
  21342. var leftOperand = parseUnaryExpressionOrHigher();
  21343. return parseBinaryExpressionRest(precedence, leftOperand);
  21344. }
  21345. function isInOrOfKeyword(t) {
  21346. return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
  21347. }
  21348. function parseBinaryExpressionRest(precedence, leftOperand) {
  21349. while (true) {
  21350. // We either have a binary operator here, or we're finished. We call
  21351. // reScanGreaterToken so that we merge token sequences like > and = into >=
  21352. reScanGreaterToken();
  21353. var newPrecedence = ts.getBinaryOperatorPrecedence(token());
  21354. // Check the precedence to see if we should "take" this operator
  21355. // - For left associative operator (all operator but **), consume the operator,
  21356. // recursively call the function below, and parse binaryExpression as a rightOperand
  21357. // of the caller if the new precedence of the operator is greater then or equal to the current precedence.
  21358. // For example:
  21359. // a - b - c;
  21360. // ^token; leftOperand = b. Return b to the caller as a rightOperand
  21361. // a * b - c
  21362. // ^token; leftOperand = b. Return b to the caller as a rightOperand
  21363. // a - b * c;
  21364. // ^token; leftOperand = b. Return b * c to the caller as a rightOperand
  21365. // - For right associative operator (**), consume the operator, recursively call the function
  21366. // and parse binaryExpression as a rightOperand of the caller if the new precedence of
  21367. // the operator is strictly grater than the current precedence
  21368. // For example:
  21369. // a ** b ** c;
  21370. // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
  21371. // a - b ** c;
  21372. // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
  21373. // a ** b - c
  21374. // ^token; leftOperand = b. Return b to the caller as a rightOperand
  21375. var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
  21376. newPrecedence >= precedence :
  21377. newPrecedence > precedence;
  21378. if (!consumeCurrentOperator) {
  21379. break;
  21380. }
  21381. if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
  21382. break;
  21383. }
  21384. if (token() === 123 /* AsKeyword */) {
  21385. // Make sure we *do* perform ASI for constructs like this:
  21386. // var x = foo
  21387. // as (Bar)
  21388. // This should be parsed as an initialized variable, followed
  21389. // by a function call to 'as' with the argument 'Bar'
  21390. if (scanner.hasPrecedingLineBreak()) {
  21391. break;
  21392. }
  21393. else {
  21394. nextToken();
  21395. leftOperand = makeAsExpression(leftOperand, parseType());
  21396. }
  21397. }
  21398. else {
  21399. leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
  21400. }
  21401. }
  21402. return leftOperand;
  21403. }
  21404. function isBinaryOperator() {
  21405. if (inDisallowInContext() && token() === 97 /* InKeyword */) {
  21406. return false;
  21407. }
  21408. return ts.getBinaryOperatorPrecedence(token()) > 0;
  21409. }
  21410. function makeBinaryExpression(left, operatorToken, right) {
  21411. var node = createNode(209 /* BinaryExpression */, left.pos);
  21412. node.left = left;
  21413. node.operatorToken = operatorToken;
  21414. node.right = right;
  21415. return finishNode(node);
  21416. }
  21417. function makeAsExpression(left, right) {
  21418. var node = createNode(217 /* AsExpression */, left.pos);
  21419. node.expression = left;
  21420. node.type = right;
  21421. return finishNode(node);
  21422. }
  21423. function parsePrefixUnaryExpression() {
  21424. var node = createNode(207 /* PrefixUnaryExpression */);
  21425. node.operator = token();
  21426. nextToken();
  21427. node.operand = parseSimpleUnaryExpression();
  21428. return finishNode(node);
  21429. }
  21430. function parseDeleteExpression() {
  21431. var node = createNode(203 /* DeleteExpression */);
  21432. nextToken();
  21433. node.expression = parseSimpleUnaryExpression();
  21434. return finishNode(node);
  21435. }
  21436. function parseTypeOfExpression() {
  21437. var node = createNode(204 /* TypeOfExpression */);
  21438. nextToken();
  21439. node.expression = parseSimpleUnaryExpression();
  21440. return finishNode(node);
  21441. }
  21442. function parseVoidExpression() {
  21443. var node = createNode(205 /* VoidExpression */);
  21444. nextToken();
  21445. node.expression = parseSimpleUnaryExpression();
  21446. return finishNode(node);
  21447. }
  21448. function isAwaitExpression() {
  21449. if (token() === 127 /* AwaitKeyword */) {
  21450. if (inAwaitContext()) {
  21451. return true;
  21452. }
  21453. // here we are using similar heuristics as 'isYieldExpression'
  21454. return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
  21455. }
  21456. return false;
  21457. }
  21458. function parseAwaitExpression() {
  21459. var node = createNode(206 /* AwaitExpression */);
  21460. nextToken();
  21461. node.expression = parseSimpleUnaryExpression();
  21462. return finishNode(node);
  21463. }
  21464. /**
  21465. * Parse ES7 exponential expression and await expression
  21466. *
  21467. * ES7 ExponentiationExpression:
  21468. * 1) UnaryExpression[?Yield]
  21469. * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
  21470. *
  21471. */
  21472. function parseUnaryExpressionOrHigher() {
  21473. /**
  21474. * ES7 UpdateExpression:
  21475. * 1) LeftHandSideExpression[?Yield]
  21476. * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++
  21477. * 3) LeftHandSideExpression[?Yield][no LineTerminator here]--
  21478. * 4) ++UnaryExpression[?Yield]
  21479. * 5) --UnaryExpression[?Yield]
  21480. */
  21481. if (isUpdateExpression()) {
  21482. var updateExpression = parseUpdateExpression();
  21483. return token() === 42 /* AsteriskAsteriskToken */ ?
  21484. parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
  21485. updateExpression;
  21486. }
  21487. /**
  21488. * ES7 UnaryExpression:
  21489. * 1) UpdateExpression[?yield]
  21490. * 2) delete UpdateExpression[?yield]
  21491. * 3) void UpdateExpression[?yield]
  21492. * 4) typeof UpdateExpression[?yield]
  21493. * 5) + UpdateExpression[?yield]
  21494. * 6) - UpdateExpression[?yield]
  21495. * 7) ~ UpdateExpression[?yield]
  21496. * 8) ! UpdateExpression[?yield]
  21497. */
  21498. var unaryOperator = token();
  21499. var simpleUnaryExpression = parseSimpleUnaryExpression();
  21500. if (token() === 42 /* AsteriskAsteriskToken */) {
  21501. var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
  21502. var end = simpleUnaryExpression.end;
  21503. if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
  21504. parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
  21505. }
  21506. else {
  21507. parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator));
  21508. }
  21509. }
  21510. return simpleUnaryExpression;
  21511. }
  21512. /**
  21513. * Parse ES7 simple-unary expression or higher:
  21514. *
  21515. * ES7 UnaryExpression:
  21516. * 1) UpdateExpression[?yield]
  21517. * 2) delete UnaryExpression[?yield]
  21518. * 3) void UnaryExpression[?yield]
  21519. * 4) typeof UnaryExpression[?yield]
  21520. * 5) + UnaryExpression[?yield]
  21521. * 6) - UnaryExpression[?yield]
  21522. * 7) ~ UnaryExpression[?yield]
  21523. * 8) ! UnaryExpression[?yield]
  21524. * 9) [+Await] await UnaryExpression[?yield]
  21525. */
  21526. function parseSimpleUnaryExpression() {
  21527. switch (token()) {
  21528. case 39 /* PlusToken */:
  21529. case 40 /* MinusToken */:
  21530. case 54 /* TildeToken */:
  21531. case 53 /* ExclamationToken */:
  21532. return parsePrefixUnaryExpression();
  21533. case 85 /* DeleteKeyword */:
  21534. return parseDeleteExpression();
  21535. case 108 /* TypeOfKeyword */:
  21536. return parseTypeOfExpression();
  21537. case 110 /* VoidKeyword */:
  21538. return parseVoidExpression();
  21539. case 29 /* LessThanToken */:
  21540. // This is modified UnaryExpression grammar in TypeScript
  21541. // UnaryExpression (modified):
  21542. // < type > UnaryExpression
  21543. return parseTypeAssertion();
  21544. case 127 /* AwaitKeyword */:
  21545. if (isAwaitExpression()) {
  21546. return parseAwaitExpression();
  21547. }
  21548. // falls through
  21549. default:
  21550. return parseUpdateExpression();
  21551. }
  21552. }
  21553. /**
  21554. * Check if the current token can possibly be an ES7 increment expression.
  21555. *
  21556. * ES7 UpdateExpression:
  21557. * LeftHandSideExpression[?Yield]
  21558. * LeftHandSideExpression[?Yield][no LineTerminator here]++
  21559. * LeftHandSideExpression[?Yield][no LineTerminator here]--
  21560. * ++LeftHandSideExpression[?Yield]
  21561. * --LeftHandSideExpression[?Yield]
  21562. */
  21563. function isUpdateExpression() {
  21564. // This function is called inside parseUnaryExpression to decide
  21565. // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
  21566. switch (token()) {
  21567. case 39 /* PlusToken */:
  21568. case 40 /* MinusToken */:
  21569. case 54 /* TildeToken */:
  21570. case 53 /* ExclamationToken */:
  21571. case 85 /* DeleteKeyword */:
  21572. case 108 /* TypeOfKeyword */:
  21573. case 110 /* VoidKeyword */:
  21574. case 127 /* AwaitKeyword */:
  21575. return false;
  21576. case 29 /* LessThanToken */:
  21577. // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
  21578. if (sourceFile.languageVariant !== 1 /* JSX */) {
  21579. return false;
  21580. }
  21581. // We are in JSX context and the token is part of JSXElement.
  21582. // falls through
  21583. default:
  21584. return true;
  21585. }
  21586. }
  21587. /**
  21588. * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
  21589. *
  21590. * ES7 UpdateExpression[yield]:
  21591. * 1) LeftHandSideExpression[?yield]
  21592. * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
  21593. * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
  21594. * 4) ++LeftHandSideExpression[?yield]
  21595. * 5) --LeftHandSideExpression[?yield]
  21596. * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
  21597. */
  21598. function parseUpdateExpression() {
  21599. if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
  21600. var node = createNode(207 /* PrefixUnaryExpression */);
  21601. node.operator = token();
  21602. nextToken();
  21603. node.operand = parseLeftHandSideExpressionOrHigher();
  21604. return finishNode(node);
  21605. }
  21606. else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
  21607. // JSXElement is part of primaryExpression
  21608. return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
  21609. }
  21610. var expression = parseLeftHandSideExpressionOrHigher();
  21611. ts.Debug.assert(ts.isLeftHandSideExpression(expression));
  21612. if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
  21613. var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
  21614. node.operand = expression;
  21615. node.operator = token();
  21616. nextToken();
  21617. return finishNode(node);
  21618. }
  21619. return expression;
  21620. }
  21621. function parseLeftHandSideExpressionOrHigher() {
  21622. // Original Ecma:
  21623. // LeftHandSideExpression: See 11.2
  21624. // NewExpression
  21625. // CallExpression
  21626. //
  21627. // Our simplification:
  21628. //
  21629. // LeftHandSideExpression: See 11.2
  21630. // MemberExpression
  21631. // CallExpression
  21632. //
  21633. // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
  21634. // MemberExpression to make our lives easier.
  21635. //
  21636. // to best understand the below code, it's important to see how CallExpression expands
  21637. // out into its own productions:
  21638. //
  21639. // CallExpression:
  21640. // MemberExpression Arguments
  21641. // CallExpression Arguments
  21642. // CallExpression[Expression]
  21643. // CallExpression.IdentifierName
  21644. // import (AssignmentExpression)
  21645. // super Arguments
  21646. // super.IdentifierName
  21647. //
  21648. // Because of the recursion in these calls, we need to bottom out first. There are three
  21649. // bottom out states we can run into: 1) We see 'super' which must start either of
  21650. // the last two CallExpression productions. 2) We see 'import' which must start import call.
  21651. // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
  21652. // or starts the beginning of the first four CallExpression productions.
  21653. var expression;
  21654. if (token() === 96 /* ImportKeyword */) {
  21655. if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
  21656. // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
  21657. // For example:
  21658. // var foo3 = require("subfolder
  21659. // import * as foo1 from "module-from-node
  21660. // We want this import to be a statement rather than import call expression
  21661. sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
  21662. expression = parseTokenNode();
  21663. }
  21664. else if (lookAhead(nextTokenIsDot)) {
  21665. // This is an 'import.*' metaproperty (i.e. 'import.meta')
  21666. var fullStart = scanner.getStartPos();
  21667. nextToken(); // advance past the 'import'
  21668. nextToken(); // advance past the dot
  21669. var node = createNode(219 /* MetaProperty */, fullStart);
  21670. node.keywordToken = 96 /* ImportKeyword */;
  21671. node.name = parseIdentifierName();
  21672. expression = finishNode(node);
  21673. sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
  21674. }
  21675. else {
  21676. expression = parseMemberExpressionOrHigher();
  21677. }
  21678. }
  21679. else {
  21680. expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
  21681. }
  21682. // Now, we *may* be complete. However, we might have consumed the start of a
  21683. // CallExpression or OptionalExpression. As such, we need to consume the rest
  21684. // of it here to be complete.
  21685. return parseCallExpressionRest(expression);
  21686. }
  21687. function parseMemberExpressionOrHigher() {
  21688. // Note: to make our lives simpler, we decompose the NewExpression productions and
  21689. // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
  21690. // like so:
  21691. //
  21692. // PrimaryExpression : See 11.1
  21693. // this
  21694. // Identifier
  21695. // Literal
  21696. // ArrayLiteral
  21697. // ObjectLiteral
  21698. // (Expression)
  21699. // FunctionExpression
  21700. // new MemberExpression Arguments?
  21701. //
  21702. // MemberExpression : See 11.2
  21703. // PrimaryExpression
  21704. // MemberExpression[Expression]
  21705. // MemberExpression.IdentifierName
  21706. //
  21707. // CallExpression : See 11.2
  21708. // MemberExpression
  21709. // CallExpression Arguments
  21710. // CallExpression[Expression]
  21711. // CallExpression.IdentifierName
  21712. //
  21713. // Technically this is ambiguous. i.e. CallExpression defines:
  21714. //
  21715. // CallExpression:
  21716. // CallExpression Arguments
  21717. //
  21718. // If you see: "new Foo()"
  21719. //
  21720. // Then that could be treated as a single ObjectCreationExpression, or it could be
  21721. // treated as the invocation of "new Foo". We disambiguate that in code (to match
  21722. // the original grammar) by making sure that if we see an ObjectCreationExpression
  21723. // we always consume arguments if they are there. So we treat "new Foo()" as an
  21724. // object creation only, and not at all as an invocation. Another way to think
  21725. // about this is that for every "new" that we see, we will consume an argument list if
  21726. // it is there as part of the *associated* object creation node. Any additional
  21727. // argument lists we see, will become invocation expressions.
  21728. //
  21729. // Because there are no other places in the grammar now that refer to FunctionExpression
  21730. // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
  21731. // production.
  21732. //
  21733. // Because CallExpression and MemberExpression are left recursive, we need to bottom out
  21734. // of the recursion immediately. So we parse out a primary expression to start with.
  21735. var expression = parsePrimaryExpression();
  21736. return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
  21737. }
  21738. function parseSuperExpression() {
  21739. var expression = parseTokenNode();
  21740. if (token() === 29 /* LessThanToken */) {
  21741. var startPos = getNodePos();
  21742. var typeArguments = tryParse(parseTypeArgumentsInExpression);
  21743. if (typeArguments !== undefined) {
  21744. parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
  21745. }
  21746. }
  21747. if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
  21748. return expression;
  21749. }
  21750. // If we have seen "super" it must be followed by '(' or '.'.
  21751. // If it wasn't then just try to parse out a '.' and report an error.
  21752. var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
  21753. node.expression = expression;
  21754. parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
  21755. // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
  21756. node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
  21757. return finishNode(node);
  21758. }
  21759. function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
  21760. var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
  21761. var result;
  21762. if (opening.kind === 268 /* JsxOpeningElement */) {
  21763. var node = createNode(266 /* JsxElement */, opening.pos);
  21764. node.openingElement = opening;
  21765. node.children = parseJsxChildren(node.openingElement);
  21766. node.closingElement = parseJsxClosingElement(inExpressionContext);
  21767. if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
  21768. parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
  21769. }
  21770. result = finishNode(node);
  21771. }
  21772. else if (opening.kind === 271 /* JsxOpeningFragment */) {
  21773. var node = createNode(270 /* JsxFragment */, opening.pos);
  21774. node.openingFragment = opening;
  21775. node.children = parseJsxChildren(node.openingFragment);
  21776. node.closingFragment = parseJsxClosingFragment(inExpressionContext);
  21777. result = finishNode(node);
  21778. }
  21779. else {
  21780. ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
  21781. // Nothing else to do for self-closing elements
  21782. result = opening;
  21783. }
  21784. // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
  21785. // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag
  21786. // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
  21787. // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
  21788. // does less damage and we can report a better error.
  21789. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
  21790. // of one sort or another.
  21791. if (inExpressionContext && token() === 29 /* LessThanToken */) {
  21792. var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
  21793. if (invalidElement) {
  21794. parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
  21795. var badNode = createNode(209 /* BinaryExpression */, result.pos);
  21796. badNode.end = invalidElement.end;
  21797. badNode.left = result;
  21798. badNode.right = invalidElement;
  21799. badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
  21800. badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
  21801. return badNode;
  21802. }
  21803. }
  21804. return result;
  21805. }
  21806. function parseJsxText() {
  21807. var node = createNode(11 /* JsxText */);
  21808. node.text = scanner.getTokenValue();
  21809. node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
  21810. currentToken = scanner.scanJsxToken();
  21811. return finishNode(node);
  21812. }
  21813. function parseJsxChild(openingTag, token) {
  21814. switch (token) {
  21815. case 1 /* EndOfFileToken */:
  21816. // If we hit EOF, issue the error at the tag that lacks the closing element
  21817. // rather than at the end of the file (which is useless)
  21818. if (ts.isJsxOpeningFragment(openingTag)) {
  21819. parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
  21820. }
  21821. else {
  21822. parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
  21823. }
  21824. return undefined;
  21825. case 30 /* LessThanSlashToken */:
  21826. case 7 /* ConflictMarkerTrivia */:
  21827. return undefined;
  21828. case 11 /* JsxText */:
  21829. case 12 /* JsxTextAllWhiteSpaces */:
  21830. return parseJsxText();
  21831. case 18 /* OpenBraceToken */:
  21832. return parseJsxExpression(/*inExpressionContext*/ false);
  21833. case 29 /* LessThanToken */:
  21834. return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
  21835. default:
  21836. return ts.Debug.assertNever(token);
  21837. }
  21838. }
  21839. function parseJsxChildren(openingTag) {
  21840. var list = [];
  21841. var listPos = getNodePos();
  21842. var saveParsingContext = parsingContext;
  21843. parsingContext |= 1 << 14 /* JsxChildren */;
  21844. while (true) {
  21845. var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
  21846. if (!child)
  21847. break;
  21848. list.push(child);
  21849. }
  21850. parsingContext = saveParsingContext;
  21851. return createNodeArray(list, listPos);
  21852. }
  21853. function parseJsxAttributes() {
  21854. var jsxAttributes = createNode(274 /* JsxAttributes */);
  21855. jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
  21856. return finishNode(jsxAttributes);
  21857. }
  21858. function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
  21859. var fullStart = scanner.getStartPos();
  21860. parseExpected(29 /* LessThanToken */);
  21861. if (token() === 31 /* GreaterThanToken */) {
  21862. // See below for explanation of scanJsxText
  21863. var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
  21864. scanJsxText();
  21865. return finishNode(node_1);
  21866. }
  21867. var tagName = parseJsxElementName();
  21868. var typeArguments = tryParseTypeArguments();
  21869. var attributes = parseJsxAttributes();
  21870. var node;
  21871. if (token() === 31 /* GreaterThanToken */) {
  21872. // Closing tag, so scan the immediately-following text with the JSX scanning instead
  21873. // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
  21874. // scanning errors
  21875. node = createNode(268 /* JsxOpeningElement */, fullStart);
  21876. scanJsxText();
  21877. }
  21878. else {
  21879. parseExpected(43 /* SlashToken */);
  21880. if (inExpressionContext) {
  21881. parseExpected(31 /* GreaterThanToken */);
  21882. }
  21883. else {
  21884. parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
  21885. scanJsxText();
  21886. }
  21887. node = createNode(267 /* JsxSelfClosingElement */, fullStart);
  21888. }
  21889. node.tagName = tagName;
  21890. node.typeArguments = typeArguments;
  21891. node.attributes = attributes;
  21892. return finishNode(node);
  21893. }
  21894. function parseJsxElementName() {
  21895. scanJsxIdentifier();
  21896. // JsxElement can have name in the form of
  21897. // propertyAccessExpression
  21898. // primaryExpression in the form of an identifier and "this" keyword
  21899. // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
  21900. // We only want to consider "this" as a primaryExpression
  21901. var expression = token() === 104 /* ThisKeyword */ ?
  21902. parseTokenNode() : parseIdentifierName();
  21903. while (parseOptional(24 /* DotToken */)) {
  21904. var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
  21905. propertyAccess.expression = expression;
  21906. propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
  21907. expression = finishNode(propertyAccess);
  21908. }
  21909. return expression;
  21910. }
  21911. function parseJsxExpression(inExpressionContext) {
  21912. var node = createNode(276 /* JsxExpression */);
  21913. if (!parseExpected(18 /* OpenBraceToken */)) {
  21914. return undefined;
  21915. }
  21916. if (token() !== 19 /* CloseBraceToken */) {
  21917. node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
  21918. // Only an AssignmentExpression is valid here per the JSX spec,
  21919. // but we can unambiguously parse a comma sequence and provide
  21920. // a better error message in grammar checking.
  21921. node.expression = parseExpression();
  21922. }
  21923. if (inExpressionContext) {
  21924. parseExpected(19 /* CloseBraceToken */);
  21925. }
  21926. else {
  21927. if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
  21928. scanJsxText();
  21929. }
  21930. }
  21931. return finishNode(node);
  21932. }
  21933. function parseJsxAttribute() {
  21934. if (token() === 18 /* OpenBraceToken */) {
  21935. return parseJsxSpreadAttribute();
  21936. }
  21937. scanJsxIdentifier();
  21938. var node = createNode(273 /* JsxAttribute */);
  21939. node.name = parseIdentifierName();
  21940. if (token() === 62 /* EqualsToken */) {
  21941. switch (scanJsxAttributeValue()) {
  21942. case 10 /* StringLiteral */:
  21943. node.initializer = parseLiteralNode();
  21944. break;
  21945. default:
  21946. node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
  21947. break;
  21948. }
  21949. }
  21950. return finishNode(node);
  21951. }
  21952. function parseJsxSpreadAttribute() {
  21953. var node = createNode(275 /* JsxSpreadAttribute */);
  21954. parseExpected(18 /* OpenBraceToken */);
  21955. parseExpected(25 /* DotDotDotToken */);
  21956. node.expression = parseExpression();
  21957. parseExpected(19 /* CloseBraceToken */);
  21958. return finishNode(node);
  21959. }
  21960. function parseJsxClosingElement(inExpressionContext) {
  21961. var node = createNode(269 /* JsxClosingElement */);
  21962. parseExpected(30 /* LessThanSlashToken */);
  21963. node.tagName = parseJsxElementName();
  21964. if (inExpressionContext) {
  21965. parseExpected(31 /* GreaterThanToken */);
  21966. }
  21967. else {
  21968. parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
  21969. scanJsxText();
  21970. }
  21971. return finishNode(node);
  21972. }
  21973. function parseJsxClosingFragment(inExpressionContext) {
  21974. var node = createNode(272 /* JsxClosingFragment */);
  21975. parseExpected(30 /* LessThanSlashToken */);
  21976. if (ts.tokenIsIdentifierOrKeyword(token())) {
  21977. parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
  21978. }
  21979. if (inExpressionContext) {
  21980. parseExpected(31 /* GreaterThanToken */);
  21981. }
  21982. else {
  21983. parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
  21984. scanJsxText();
  21985. }
  21986. return finishNode(node);
  21987. }
  21988. function parseTypeAssertion() {
  21989. var node = createNode(199 /* TypeAssertionExpression */);
  21990. parseExpected(29 /* LessThanToken */);
  21991. node.type = parseType();
  21992. parseExpected(31 /* GreaterThanToken */);
  21993. node.expression = parseSimpleUnaryExpression();
  21994. return finishNode(node);
  21995. }
  21996. function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
  21997. nextToken();
  21998. return ts.tokenIsIdentifierOrKeyword(token())
  21999. || token() === 22 /* OpenBracketToken */
  22000. || isTemplateStartOfTaggedTemplate();
  22001. }
  22002. function isStartOfOptionalPropertyOrElementAccessChain() {
  22003. return token() === 28 /* QuestionDotToken */
  22004. && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
  22005. }
  22006. function parsePropertyAccessExpressionRest(expression, questionDotToken) {
  22007. var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
  22008. propertyAccess.expression = expression;
  22009. propertyAccess.questionDotToken = questionDotToken;
  22010. propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
  22011. if (questionDotToken || expression.flags & 32 /* OptionalChain */) {
  22012. propertyAccess.flags |= 32 /* OptionalChain */;
  22013. if (ts.isPrivateIdentifier(propertyAccess.name)) {
  22014. parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
  22015. }
  22016. }
  22017. return finishNode(propertyAccess);
  22018. }
  22019. function parseElementAccessExpressionRest(expression, questionDotToken) {
  22020. var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
  22021. indexedAccess.expression = expression;
  22022. indexedAccess.questionDotToken = questionDotToken;
  22023. if (token() === 23 /* CloseBracketToken */) {
  22024. indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
  22025. }
  22026. else {
  22027. var argument = allowInAnd(parseExpression);
  22028. if (ts.isStringOrNumericLiteralLike(argument)) {
  22029. argument.text = internIdentifier(argument.text);
  22030. }
  22031. indexedAccess.argumentExpression = argument;
  22032. }
  22033. parseExpected(23 /* CloseBracketToken */);
  22034. if (questionDotToken || expression.flags & 32 /* OptionalChain */) {
  22035. indexedAccess.flags |= 32 /* OptionalChain */;
  22036. }
  22037. return finishNode(indexedAccess);
  22038. }
  22039. function parseMemberExpressionRest(expression, allowOptionalChain) {
  22040. while (true) {
  22041. var questionDotToken = void 0;
  22042. var isPropertyAccess = false;
  22043. if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
  22044. questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
  22045. isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
  22046. }
  22047. else {
  22048. isPropertyAccess = parseOptional(24 /* DotToken */);
  22049. }
  22050. if (isPropertyAccess) {
  22051. expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
  22052. continue;
  22053. }
  22054. if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
  22055. nextToken();
  22056. var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
  22057. nonNullExpression.expression = expression;
  22058. expression = finishNode(nonNullExpression);
  22059. continue;
  22060. }
  22061. // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
  22062. if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
  22063. expression = parseElementAccessExpressionRest(expression, questionDotToken);
  22064. continue;
  22065. }
  22066. if (isTemplateStartOfTaggedTemplate()) {
  22067. expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
  22068. continue;
  22069. }
  22070. return expression;
  22071. }
  22072. }
  22073. function isTemplateStartOfTaggedTemplate() {
  22074. return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
  22075. }
  22076. function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
  22077. var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
  22078. tagExpression.tag = tag;
  22079. tagExpression.questionDotToken = questionDotToken;
  22080. tagExpression.typeArguments = typeArguments;
  22081. tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
  22082. ? parseLiteralNode()
  22083. : parseTemplateExpression();
  22084. if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
  22085. tagExpression.flags |= 32 /* OptionalChain */;
  22086. }
  22087. return finishNode(tagExpression);
  22088. }
  22089. function parseCallExpressionRest(expression) {
  22090. while (true) {
  22091. expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
  22092. var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
  22093. // handle 'foo<<T>()'
  22094. if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
  22095. // See if this is the start of a generic invocation. If so, consume it and
  22096. // keep checking for postfix expressions. Otherwise, it's just a '<' that's
  22097. // part of an arithmetic expression. Break out so we consume it higher in the
  22098. // stack.
  22099. var typeArguments = tryParse(parseTypeArgumentsInExpression);
  22100. if (typeArguments) {
  22101. if (isTemplateStartOfTaggedTemplate()) {
  22102. expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
  22103. continue;
  22104. }
  22105. var callExpr = createNode(196 /* CallExpression */, expression.pos);
  22106. callExpr.expression = expression;
  22107. callExpr.questionDotToken = questionDotToken;
  22108. callExpr.typeArguments = typeArguments;
  22109. callExpr.arguments = parseArgumentList();
  22110. if (questionDotToken || expression.flags & 32 /* OptionalChain */) {
  22111. callExpr.flags |= 32 /* OptionalChain */;
  22112. }
  22113. expression = finishNode(callExpr);
  22114. continue;
  22115. }
  22116. }
  22117. else if (token() === 20 /* OpenParenToken */) {
  22118. var callExpr = createNode(196 /* CallExpression */, expression.pos);
  22119. callExpr.expression = expression;
  22120. callExpr.questionDotToken = questionDotToken;
  22121. callExpr.arguments = parseArgumentList();
  22122. if (questionDotToken || expression.flags & 32 /* OptionalChain */) {
  22123. callExpr.flags |= 32 /* OptionalChain */;
  22124. }
  22125. expression = finishNode(callExpr);
  22126. continue;
  22127. }
  22128. if (questionDotToken) {
  22129. // We failed to parse anything, so report a missing identifier here.
  22130. var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
  22131. propertyAccess.expression = expression;
  22132. propertyAccess.questionDotToken = questionDotToken;
  22133. propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
  22134. propertyAccess.flags |= 32 /* OptionalChain */;
  22135. expression = finishNode(propertyAccess);
  22136. }
  22137. break;
  22138. }
  22139. return expression;
  22140. }
  22141. function parseArgumentList() {
  22142. parseExpected(20 /* OpenParenToken */);
  22143. var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
  22144. parseExpected(21 /* CloseParenToken */);
  22145. return result;
  22146. }
  22147. function parseTypeArgumentsInExpression() {
  22148. if (reScanLessThanToken() !== 29 /* LessThanToken */) {
  22149. return undefined;
  22150. }
  22151. nextToken();
  22152. var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
  22153. if (!parseExpected(31 /* GreaterThanToken */)) {
  22154. // If it doesn't have the closing `>` then it's definitely not an type argument list.
  22155. return undefined;
  22156. }
  22157. // If we have a '<', then only parse this as a argument list if the type arguments
  22158. // are complete and we have an open paren. if we don't, rewind and return nothing.
  22159. return typeArguments && canFollowTypeArgumentsInExpression()
  22160. ? typeArguments
  22161. : undefined;
  22162. }
  22163. function canFollowTypeArgumentsInExpression() {
  22164. switch (token()) {
  22165. case 20 /* OpenParenToken */: // foo<x>(
  22166. case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
  22167. case 15 /* TemplateHead */: // foo<T> `...${100}...`
  22168. // these are the only tokens can legally follow a type argument
  22169. // list. So we definitely want to treat them as type arg lists.
  22170. // falls through
  22171. case 24 /* DotToken */: // foo<x>.
  22172. case 21 /* CloseParenToken */: // foo<x>)
  22173. case 23 /* CloseBracketToken */: // foo<x>]
  22174. case 58 /* ColonToken */: // foo<x>:
  22175. case 26 /* SemicolonToken */: // foo<x>;
  22176. case 57 /* QuestionToken */: // foo<x>?
  22177. case 34 /* EqualsEqualsToken */: // foo<x> ==
  22178. case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
  22179. case 35 /* ExclamationEqualsToken */: // foo<x> !=
  22180. case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
  22181. case 55 /* AmpersandAmpersandToken */: // foo<x> &&
  22182. case 56 /* BarBarToken */: // foo<x> ||
  22183. case 60 /* QuestionQuestionToken */: // foo<x> ??
  22184. case 52 /* CaretToken */: // foo<x> ^
  22185. case 50 /* AmpersandToken */: // foo<x> &
  22186. case 51 /* BarToken */: // foo<x> |
  22187. case 19 /* CloseBraceToken */: // foo<x> }
  22188. case 1 /* EndOfFileToken */: // foo<x>
  22189. // these cases can't legally follow a type arg list. However, they're not legal
  22190. // expressions either. The user is probably in the middle of a generic type. So
  22191. // treat it as such.
  22192. return true;
  22193. case 27 /* CommaToken */: // foo<x>,
  22194. case 18 /* OpenBraceToken */: // foo<x> {
  22195. // We don't want to treat these as type arguments. Otherwise we'll parse this
  22196. // as an invocation expression. Instead, we want to parse out the expression
  22197. // in isolation from the type arguments.
  22198. // falls through
  22199. default:
  22200. // Anything else treat as an expression.
  22201. return false;
  22202. }
  22203. }
  22204. function parsePrimaryExpression() {
  22205. switch (token()) {
  22206. case 8 /* NumericLiteral */:
  22207. case 9 /* BigIntLiteral */:
  22208. case 10 /* StringLiteral */:
  22209. case 14 /* NoSubstitutionTemplateLiteral */:
  22210. return parseLiteralNode();
  22211. case 104 /* ThisKeyword */:
  22212. case 102 /* SuperKeyword */:
  22213. case 100 /* NullKeyword */:
  22214. case 106 /* TrueKeyword */:
  22215. case 91 /* FalseKeyword */:
  22216. return parseTokenNode();
  22217. case 20 /* OpenParenToken */:
  22218. return parseParenthesizedExpression();
  22219. case 22 /* OpenBracketToken */:
  22220. return parseArrayLiteralExpression();
  22221. case 18 /* OpenBraceToken */:
  22222. return parseObjectLiteralExpression();
  22223. case 126 /* AsyncKeyword */:
  22224. // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
  22225. // If we encounter `async [no LineTerminator here] function` then this is an async
  22226. // function; otherwise, its an identifier.
  22227. if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
  22228. break;
  22229. }
  22230. return parseFunctionExpression();
  22231. case 80 /* ClassKeyword */:
  22232. return parseClassExpression();
  22233. case 94 /* FunctionKeyword */:
  22234. return parseFunctionExpression();
  22235. case 99 /* NewKeyword */:
  22236. return parseNewExpressionOrNewDotTarget();
  22237. case 43 /* SlashToken */:
  22238. case 67 /* SlashEqualsToken */:
  22239. if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
  22240. return parseLiteralNode();
  22241. }
  22242. break;
  22243. case 15 /* TemplateHead */:
  22244. return parseTemplateExpression();
  22245. }
  22246. return parseIdentifier(ts.Diagnostics.Expression_expected);
  22247. }
  22248. function parseParenthesizedExpression() {
  22249. var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
  22250. parseExpected(20 /* OpenParenToken */);
  22251. node.expression = allowInAnd(parseExpression);
  22252. parseExpected(21 /* CloseParenToken */);
  22253. return finishNode(node);
  22254. }
  22255. function parseSpreadElement() {
  22256. var node = createNode(213 /* SpreadElement */);
  22257. parseExpected(25 /* DotDotDotToken */);
  22258. node.expression = parseAssignmentExpressionOrHigher();
  22259. return finishNode(node);
  22260. }
  22261. function parseArgumentOrArrayLiteralElement() {
  22262. return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
  22263. token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
  22264. parseAssignmentExpressionOrHigher();
  22265. }
  22266. function parseArgumentExpression() {
  22267. return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
  22268. }
  22269. function parseArrayLiteralExpression() {
  22270. var node = createNode(192 /* ArrayLiteralExpression */);
  22271. parseExpected(22 /* OpenBracketToken */);
  22272. if (scanner.hasPrecedingLineBreak()) {
  22273. node.multiLine = true;
  22274. }
  22275. node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
  22276. parseExpected(23 /* CloseBracketToken */);
  22277. return finishNode(node);
  22278. }
  22279. function parseObjectLiteralElement() {
  22280. var node = createNodeWithJSDoc(0 /* Unknown */);
  22281. if (parseOptionalToken(25 /* DotDotDotToken */)) {
  22282. node.kind = 283 /* SpreadAssignment */;
  22283. node.expression = parseAssignmentExpressionOrHigher();
  22284. return finishNode(node);
  22285. }
  22286. node.decorators = parseDecorators();
  22287. node.modifiers = parseModifiers();
  22288. if (parseContextualModifier(131 /* GetKeyword */)) {
  22289. return parseAccessorDeclaration(node, 163 /* GetAccessor */);
  22290. }
  22291. if (parseContextualModifier(142 /* SetKeyword */)) {
  22292. return parseAccessorDeclaration(node, 164 /* SetAccessor */);
  22293. }
  22294. var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
  22295. var tokenIsIdentifier = isIdentifier();
  22296. node.name = parsePropertyName();
  22297. // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
  22298. node.questionToken = parseOptionalToken(57 /* QuestionToken */);
  22299. node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
  22300. if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
  22301. return parseMethodDeclaration(node, asteriskToken);
  22302. }
  22303. // check if it is short-hand property assignment or normal property assignment
  22304. // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
  22305. // CoverInitializedName[Yield] :
  22306. // IdentifierReference[?Yield] Initializer[In, ?Yield]
  22307. // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
  22308. var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
  22309. if (isShorthandPropertyAssignment) {
  22310. node.kind = 282 /* ShorthandPropertyAssignment */;
  22311. var equalsToken = parseOptionalToken(62 /* EqualsToken */);
  22312. if (equalsToken) {
  22313. node.equalsToken = equalsToken;
  22314. node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
  22315. }
  22316. }
  22317. else {
  22318. node.kind = 281 /* PropertyAssignment */;
  22319. parseExpected(58 /* ColonToken */);
  22320. node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
  22321. }
  22322. return finishNode(node);
  22323. }
  22324. function parseObjectLiteralExpression() {
  22325. var node = createNode(193 /* ObjectLiteralExpression */);
  22326. parseExpected(18 /* OpenBraceToken */);
  22327. if (scanner.hasPrecedingLineBreak()) {
  22328. node.multiLine = true;
  22329. }
  22330. node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
  22331. parseExpected(19 /* CloseBraceToken */);
  22332. return finishNode(node);
  22333. }
  22334. function parseFunctionExpression() {
  22335. // GeneratorExpression:
  22336. // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
  22337. //
  22338. // FunctionExpression:
  22339. // function BindingIdentifier[opt](FormalParameters){ FunctionBody }
  22340. var saveDecoratorContext = inDecoratorContext();
  22341. if (saveDecoratorContext) {
  22342. setDecoratorContext(/*val*/ false);
  22343. }
  22344. var node = createNodeWithJSDoc(201 /* FunctionExpression */);
  22345. node.modifiers = parseModifiers();
  22346. parseExpected(94 /* FunctionKeyword */);
  22347. node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
  22348. var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
  22349. var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
  22350. node.name =
  22351. isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
  22352. isGenerator ? doInYieldContext(parseOptionalIdentifier) :
  22353. isAsync ? doInAwaitContext(parseOptionalIdentifier) :
  22354. parseOptionalIdentifier();
  22355. fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
  22356. node.body = parseFunctionBlock(isGenerator | isAsync);
  22357. if (saveDecoratorContext) {
  22358. setDecoratorContext(/*val*/ true);
  22359. }
  22360. return finishNode(node);
  22361. }
  22362. function parseOptionalIdentifier() {
  22363. return isIdentifier() ? parseIdentifier() : undefined;
  22364. }
  22365. function parseNewExpressionOrNewDotTarget() {
  22366. var fullStart = scanner.getStartPos();
  22367. parseExpected(99 /* NewKeyword */);
  22368. if (parseOptional(24 /* DotToken */)) {
  22369. var node_2 = createNode(219 /* MetaProperty */, fullStart);
  22370. node_2.keywordToken = 99 /* NewKeyword */;
  22371. node_2.name = parseIdentifierName();
  22372. return finishNode(node_2);
  22373. }
  22374. var expression = parsePrimaryExpression();
  22375. var typeArguments;
  22376. while (true) {
  22377. expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
  22378. typeArguments = tryParse(parseTypeArgumentsInExpression);
  22379. if (isTemplateStartOfTaggedTemplate()) {
  22380. ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
  22381. expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
  22382. typeArguments = undefined;
  22383. }
  22384. break;
  22385. }
  22386. var node = createNode(197 /* NewExpression */, fullStart);
  22387. node.expression = expression;
  22388. node.typeArguments = typeArguments;
  22389. if (node.typeArguments || token() === 20 /* OpenParenToken */) {
  22390. node.arguments = parseArgumentList();
  22391. }
  22392. return finishNode(node);
  22393. }
  22394. // STATEMENTS
  22395. function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
  22396. var node = createNode(223 /* Block */);
  22397. var openBracePosition = scanner.getTokenPos();
  22398. if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
  22399. if (scanner.hasPrecedingLineBreak()) {
  22400. node.multiLine = true;
  22401. }
  22402. node.statements = parseList(1 /* BlockStatements */, parseStatement);
  22403. if (!parseExpected(19 /* CloseBraceToken */)) {
  22404. var lastError = ts.lastOrUndefined(parseDiagnostics);
  22405. if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
  22406. ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
  22407. }
  22408. }
  22409. }
  22410. else {
  22411. node.statements = createMissingList();
  22412. }
  22413. return finishNode(node);
  22414. }
  22415. function parseFunctionBlock(flags, diagnosticMessage) {
  22416. var savedYieldContext = inYieldContext();
  22417. setYieldContext(!!(flags & 1 /* Yield */));
  22418. var savedAwaitContext = inAwaitContext();
  22419. setAwaitContext(!!(flags & 2 /* Await */));
  22420. // We may be in a [Decorator] context when parsing a function expression or
  22421. // arrow function. The body of the function is not in [Decorator] context.
  22422. var saveDecoratorContext = inDecoratorContext();
  22423. if (saveDecoratorContext) {
  22424. setDecoratorContext(/*val*/ false);
  22425. }
  22426. var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
  22427. if (saveDecoratorContext) {
  22428. setDecoratorContext(/*val*/ true);
  22429. }
  22430. setYieldContext(savedYieldContext);
  22431. setAwaitContext(savedAwaitContext);
  22432. return block;
  22433. }
  22434. function parseEmptyStatement() {
  22435. var node = createNode(224 /* EmptyStatement */);
  22436. parseExpected(26 /* SemicolonToken */);
  22437. return finishNode(node);
  22438. }
  22439. function parseIfStatement() {
  22440. var node = createNode(227 /* IfStatement */);
  22441. parseExpected(95 /* IfKeyword */);
  22442. parseExpected(20 /* OpenParenToken */);
  22443. node.expression = allowInAnd(parseExpression);
  22444. parseExpected(21 /* CloseParenToken */);
  22445. node.thenStatement = parseStatement();
  22446. node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
  22447. return finishNode(node);
  22448. }
  22449. function parseDoStatement() {
  22450. var node = createNode(228 /* DoStatement */);
  22451. parseExpected(86 /* DoKeyword */);
  22452. node.statement = parseStatement();
  22453. parseExpected(111 /* WhileKeyword */);
  22454. parseExpected(20 /* OpenParenToken */);
  22455. node.expression = allowInAnd(parseExpression);
  22456. parseExpected(21 /* CloseParenToken */);
  22457. // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
  22458. // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
  22459. // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
  22460. // do;while(0)x will have a semicolon inserted before x.
  22461. parseOptional(26 /* SemicolonToken */);
  22462. return finishNode(node);
  22463. }
  22464. function parseWhileStatement() {
  22465. var node = createNode(229 /* WhileStatement */);
  22466. parseExpected(111 /* WhileKeyword */);
  22467. parseExpected(20 /* OpenParenToken */);
  22468. node.expression = allowInAnd(parseExpression);
  22469. parseExpected(21 /* CloseParenToken */);
  22470. node.statement = parseStatement();
  22471. return finishNode(node);
  22472. }
  22473. function parseForOrForInOrForOfStatement() {
  22474. var pos = getNodePos();
  22475. parseExpected(93 /* ForKeyword */);
  22476. var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
  22477. parseExpected(20 /* OpenParenToken */);
  22478. var initializer;
  22479. if (token() !== 26 /* SemicolonToken */) {
  22480. if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
  22481. initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
  22482. }
  22483. else {
  22484. initializer = disallowInAnd(parseExpression);
  22485. }
  22486. }
  22487. var forOrForInOrForOfStatement;
  22488. if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
  22489. var forOfStatement = createNode(232 /* ForOfStatement */, pos);
  22490. forOfStatement.awaitModifier = awaitToken;
  22491. forOfStatement.initializer = initializer;
  22492. forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
  22493. parseExpected(21 /* CloseParenToken */);
  22494. forOrForInOrForOfStatement = forOfStatement;
  22495. }
  22496. else if (parseOptional(97 /* InKeyword */)) {
  22497. var forInStatement = createNode(231 /* ForInStatement */, pos);
  22498. forInStatement.initializer = initializer;
  22499. forInStatement.expression = allowInAnd(parseExpression);
  22500. parseExpected(21 /* CloseParenToken */);
  22501. forOrForInOrForOfStatement = forInStatement;
  22502. }
  22503. else {
  22504. var forStatement = createNode(230 /* ForStatement */, pos);
  22505. forStatement.initializer = initializer;
  22506. parseExpected(26 /* SemicolonToken */);
  22507. if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
  22508. forStatement.condition = allowInAnd(parseExpression);
  22509. }
  22510. parseExpected(26 /* SemicolonToken */);
  22511. if (token() !== 21 /* CloseParenToken */) {
  22512. forStatement.incrementor = allowInAnd(parseExpression);
  22513. }
  22514. parseExpected(21 /* CloseParenToken */);
  22515. forOrForInOrForOfStatement = forStatement;
  22516. }
  22517. forOrForInOrForOfStatement.statement = parseStatement();
  22518. return finishNode(forOrForInOrForOfStatement);
  22519. }
  22520. function parseBreakOrContinueStatement(kind) {
  22521. var node = createNode(kind);
  22522. parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
  22523. if (!canParseSemicolon()) {
  22524. node.label = parseIdentifier();
  22525. }
  22526. parseSemicolon();
  22527. return finishNode(node);
  22528. }
  22529. function parseReturnStatement() {
  22530. var node = createNode(235 /* ReturnStatement */);
  22531. parseExpected(101 /* ReturnKeyword */);
  22532. if (!canParseSemicolon()) {
  22533. node.expression = allowInAnd(parseExpression);
  22534. }
  22535. parseSemicolon();
  22536. return finishNode(node);
  22537. }
  22538. function parseWithStatement() {
  22539. var node = createNode(236 /* WithStatement */);
  22540. parseExpected(112 /* WithKeyword */);
  22541. parseExpected(20 /* OpenParenToken */);
  22542. node.expression = allowInAnd(parseExpression);
  22543. parseExpected(21 /* CloseParenToken */);
  22544. node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
  22545. return finishNode(node);
  22546. }
  22547. function parseCaseClause() {
  22548. var node = createNode(277 /* CaseClause */);
  22549. parseExpected(78 /* CaseKeyword */);
  22550. node.expression = allowInAnd(parseExpression);
  22551. parseExpected(58 /* ColonToken */);
  22552. node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
  22553. return finishNode(node);
  22554. }
  22555. function parseDefaultClause() {
  22556. var node = createNode(278 /* DefaultClause */);
  22557. parseExpected(84 /* DefaultKeyword */);
  22558. parseExpected(58 /* ColonToken */);
  22559. node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
  22560. return finishNode(node);
  22561. }
  22562. function parseCaseOrDefaultClause() {
  22563. return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
  22564. }
  22565. function parseSwitchStatement() {
  22566. var node = createNode(237 /* SwitchStatement */);
  22567. parseExpected(103 /* SwitchKeyword */);
  22568. parseExpected(20 /* OpenParenToken */);
  22569. node.expression = allowInAnd(parseExpression);
  22570. parseExpected(21 /* CloseParenToken */);
  22571. var caseBlock = createNode(251 /* CaseBlock */);
  22572. parseExpected(18 /* OpenBraceToken */);
  22573. caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
  22574. parseExpected(19 /* CloseBraceToken */);
  22575. node.caseBlock = finishNode(caseBlock);
  22576. return finishNode(node);
  22577. }
  22578. function parseThrowStatement() {
  22579. // ThrowStatement[Yield] :
  22580. // throw [no LineTerminator here]Expression[In, ?Yield];
  22581. // Because of automatic semicolon insertion, we need to report error if this
  22582. // throw could be terminated with a semicolon. Note: we can't call 'parseExpression'
  22583. // directly as that might consume an expression on the following line.
  22584. // We just return 'undefined' in that case. The actual error will be reported in the
  22585. // grammar walker.
  22586. var node = createNode(239 /* ThrowStatement */);
  22587. parseExpected(105 /* ThrowKeyword */);
  22588. node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
  22589. parseSemicolon();
  22590. return finishNode(node);
  22591. }
  22592. // TODO: Review for error recovery
  22593. function parseTryStatement() {
  22594. var node = createNode(240 /* TryStatement */);
  22595. parseExpected(107 /* TryKeyword */);
  22596. node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
  22597. node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
  22598. // If we don't have a catch clause, then we must have a finally clause. Try to parse
  22599. // one out no matter what.
  22600. if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
  22601. parseExpected(92 /* FinallyKeyword */);
  22602. node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
  22603. }
  22604. return finishNode(node);
  22605. }
  22606. function parseCatchClause() {
  22607. var result = createNode(280 /* CatchClause */);
  22608. parseExpected(79 /* CatchKeyword */);
  22609. if (parseOptional(20 /* OpenParenToken */)) {
  22610. result.variableDeclaration = parseVariableDeclaration();
  22611. parseExpected(21 /* CloseParenToken */);
  22612. }
  22613. else {
  22614. // Keep shape of node to avoid degrading performance.
  22615. result.variableDeclaration = undefined;
  22616. }
  22617. result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
  22618. return finishNode(result);
  22619. }
  22620. function parseDebuggerStatement() {
  22621. var node = createNode(241 /* DebuggerStatement */);
  22622. parseExpected(83 /* DebuggerKeyword */);
  22623. parseSemicolon();
  22624. return finishNode(node);
  22625. }
  22626. function parseExpressionOrLabeledStatement() {
  22627. // Avoiding having to do the lookahead for a labeled statement by just trying to parse
  22628. // out an expression, seeing if it is identifier and then seeing if it is followed by
  22629. // a colon.
  22630. var node = createNodeWithJSDoc(0 /* Unknown */);
  22631. var expression = allowInAnd(parseExpression);
  22632. if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
  22633. node.kind = 238 /* LabeledStatement */;
  22634. node.label = expression;
  22635. node.statement = parseStatement();
  22636. }
  22637. else {
  22638. node.kind = 226 /* ExpressionStatement */;
  22639. node.expression = expression;
  22640. parseSemicolon();
  22641. }
  22642. return finishNode(node);
  22643. }
  22644. function nextTokenIsIdentifierOrKeywordOnSameLine() {
  22645. nextToken();
  22646. return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
  22647. }
  22648. function nextTokenIsClassKeywordOnSameLine() {
  22649. nextToken();
  22650. return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
  22651. }
  22652. function nextTokenIsFunctionKeywordOnSameLine() {
  22653. nextToken();
  22654. return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
  22655. }
  22656. function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
  22657. nextToken();
  22658. return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
  22659. }
  22660. function isDeclaration() {
  22661. while (true) {
  22662. switch (token()) {
  22663. case 109 /* VarKeyword */:
  22664. case 115 /* LetKeyword */:
  22665. case 81 /* ConstKeyword */:
  22666. case 94 /* FunctionKeyword */:
  22667. case 80 /* ClassKeyword */:
  22668. case 88 /* EnumKeyword */:
  22669. return true;
  22670. // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
  22671. // however, an identifier cannot be followed by another identifier on the same line. This is what we
  22672. // count on to parse out the respective declarations. For instance, we exploit this to say that
  22673. //
  22674. // namespace n
  22675. //
  22676. // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
  22677. //
  22678. // namespace
  22679. // n
  22680. //
  22681. // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
  22682. // We need to look one token ahead to see if it permissible to try parsing a declaration.
  22683. //
  22684. // *Note*: 'interface' is actually a strict mode reserved word. So while
  22685. //
  22686. // "use strict"
  22687. // interface
  22688. // I {}
  22689. //
  22690. // could be legal, it would add complexity for very little gain.
  22691. case 114 /* InterfaceKeyword */:
  22692. case 145 /* TypeKeyword */:
  22693. return nextTokenIsIdentifierOnSameLine();
  22694. case 135 /* ModuleKeyword */:
  22695. case 136 /* NamespaceKeyword */:
  22696. return nextTokenIsIdentifierOrStringLiteralOnSameLine();
  22697. case 122 /* AbstractKeyword */:
  22698. case 126 /* AsyncKeyword */:
  22699. case 130 /* DeclareKeyword */:
  22700. case 117 /* PrivateKeyword */:
  22701. case 118 /* ProtectedKeyword */:
  22702. case 119 /* PublicKeyword */:
  22703. case 138 /* ReadonlyKeyword */:
  22704. nextToken();
  22705. // ASI takes effect for this modifier.
  22706. if (scanner.hasPrecedingLineBreak()) {
  22707. return false;
  22708. }
  22709. continue;
  22710. case 150 /* GlobalKeyword */:
  22711. nextToken();
  22712. return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
  22713. case 96 /* ImportKeyword */:
  22714. nextToken();
  22715. return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
  22716. token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
  22717. case 89 /* ExportKeyword */:
  22718. var currentToken_1 = nextToken();
  22719. if (currentToken_1 === 145 /* TypeKeyword */) {
  22720. currentToken_1 = lookAhead(nextToken);
  22721. }
  22722. if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
  22723. currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
  22724. currentToken_1 === 123 /* AsKeyword */) {
  22725. return true;
  22726. }
  22727. continue;
  22728. case 120 /* StaticKeyword */:
  22729. nextToken();
  22730. continue;
  22731. default:
  22732. return false;
  22733. }
  22734. }
  22735. }
  22736. function isStartOfDeclaration() {
  22737. return lookAhead(isDeclaration);
  22738. }
  22739. function isStartOfStatement() {
  22740. switch (token()) {
  22741. case 59 /* AtToken */:
  22742. case 26 /* SemicolonToken */:
  22743. case 18 /* OpenBraceToken */:
  22744. case 109 /* VarKeyword */:
  22745. case 115 /* LetKeyword */:
  22746. case 94 /* FunctionKeyword */:
  22747. case 80 /* ClassKeyword */:
  22748. case 88 /* EnumKeyword */:
  22749. case 95 /* IfKeyword */:
  22750. case 86 /* DoKeyword */:
  22751. case 111 /* WhileKeyword */:
  22752. case 93 /* ForKeyword */:
  22753. case 82 /* ContinueKeyword */:
  22754. case 77 /* BreakKeyword */:
  22755. case 101 /* ReturnKeyword */:
  22756. case 112 /* WithKeyword */:
  22757. case 103 /* SwitchKeyword */:
  22758. case 105 /* ThrowKeyword */:
  22759. case 107 /* TryKeyword */:
  22760. case 83 /* DebuggerKeyword */:
  22761. // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
  22762. // however, we say they are here so that we may gracefully parse them and error later.
  22763. // falls through
  22764. case 79 /* CatchKeyword */:
  22765. case 92 /* FinallyKeyword */:
  22766. return true;
  22767. case 96 /* ImportKeyword */:
  22768. return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
  22769. case 81 /* ConstKeyword */:
  22770. case 89 /* ExportKeyword */:
  22771. return isStartOfDeclaration();
  22772. case 126 /* AsyncKeyword */:
  22773. case 130 /* DeclareKeyword */:
  22774. case 114 /* InterfaceKeyword */:
  22775. case 135 /* ModuleKeyword */:
  22776. case 136 /* NamespaceKeyword */:
  22777. case 145 /* TypeKeyword */:
  22778. case 150 /* GlobalKeyword */:
  22779. // When these don't start a declaration, they're an identifier in an expression statement
  22780. return true;
  22781. case 119 /* PublicKeyword */:
  22782. case 117 /* PrivateKeyword */:
  22783. case 118 /* ProtectedKeyword */:
  22784. case 120 /* StaticKeyword */:
  22785. case 138 /* ReadonlyKeyword */:
  22786. // When these don't start a declaration, they may be the start of a class member if an identifier
  22787. // immediately follows. Otherwise they're an identifier in an expression statement.
  22788. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
  22789. default:
  22790. return isStartOfExpression();
  22791. }
  22792. }
  22793. function nextTokenIsIdentifierOrStartOfDestructuring() {
  22794. nextToken();
  22795. return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
  22796. }
  22797. function isLetDeclaration() {
  22798. // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
  22799. // or [.
  22800. return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
  22801. }
  22802. function parseStatement() {
  22803. switch (token()) {
  22804. case 26 /* SemicolonToken */:
  22805. return parseEmptyStatement();
  22806. case 18 /* OpenBraceToken */:
  22807. return parseBlock(/*ignoreMissingOpenBrace*/ false);
  22808. case 109 /* VarKeyword */:
  22809. return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
  22810. case 115 /* LetKeyword */:
  22811. if (isLetDeclaration()) {
  22812. return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
  22813. }
  22814. break;
  22815. case 94 /* FunctionKeyword */:
  22816. return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
  22817. case 80 /* ClassKeyword */:
  22818. return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
  22819. case 95 /* IfKeyword */:
  22820. return parseIfStatement();
  22821. case 86 /* DoKeyword */:
  22822. return parseDoStatement();
  22823. case 111 /* WhileKeyword */:
  22824. return parseWhileStatement();
  22825. case 93 /* ForKeyword */:
  22826. return parseForOrForInOrForOfStatement();
  22827. case 82 /* ContinueKeyword */:
  22828. return parseBreakOrContinueStatement(233 /* ContinueStatement */);
  22829. case 77 /* BreakKeyword */:
  22830. return parseBreakOrContinueStatement(234 /* BreakStatement */);
  22831. case 101 /* ReturnKeyword */:
  22832. return parseReturnStatement();
  22833. case 112 /* WithKeyword */:
  22834. return parseWithStatement();
  22835. case 103 /* SwitchKeyword */:
  22836. return parseSwitchStatement();
  22837. case 105 /* ThrowKeyword */:
  22838. return parseThrowStatement();
  22839. case 107 /* TryKeyword */:
  22840. // Include 'catch' and 'finally' for error recovery.
  22841. // falls through
  22842. case 79 /* CatchKeyword */:
  22843. case 92 /* FinallyKeyword */:
  22844. return parseTryStatement();
  22845. case 83 /* DebuggerKeyword */:
  22846. return parseDebuggerStatement();
  22847. case 59 /* AtToken */:
  22848. return parseDeclaration();
  22849. case 126 /* AsyncKeyword */:
  22850. case 114 /* InterfaceKeyword */:
  22851. case 145 /* TypeKeyword */:
  22852. case 135 /* ModuleKeyword */:
  22853. case 136 /* NamespaceKeyword */:
  22854. case 130 /* DeclareKeyword */:
  22855. case 81 /* ConstKeyword */:
  22856. case 88 /* EnumKeyword */:
  22857. case 89 /* ExportKeyword */:
  22858. case 96 /* ImportKeyword */:
  22859. case 117 /* PrivateKeyword */:
  22860. case 118 /* ProtectedKeyword */:
  22861. case 119 /* PublicKeyword */:
  22862. case 122 /* AbstractKeyword */:
  22863. case 120 /* StaticKeyword */:
  22864. case 138 /* ReadonlyKeyword */:
  22865. case 150 /* GlobalKeyword */:
  22866. if (isStartOfDeclaration()) {
  22867. return parseDeclaration();
  22868. }
  22869. break;
  22870. }
  22871. return parseExpressionOrLabeledStatement();
  22872. }
  22873. function isDeclareModifier(modifier) {
  22874. return modifier.kind === 130 /* DeclareKeyword */;
  22875. }
  22876. function parseDeclaration() {
  22877. var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
  22878. // `parseListElement` attempted to get the reused node at this position,
  22879. // but the ambient context flag was not yet set, so the node appeared
  22880. // not reusable in that context.
  22881. var isAmbient = ts.some(modifiers, isDeclareModifier);
  22882. if (isAmbient) {
  22883. var node_3 = tryReuseAmbientDeclaration();
  22884. if (node_3) {
  22885. return node_3;
  22886. }
  22887. }
  22888. var node = createNodeWithJSDoc(0 /* Unknown */);
  22889. node.decorators = parseDecorators();
  22890. node.modifiers = parseModifiers();
  22891. if (isAmbient) {
  22892. for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
  22893. var m = _a[_i];
  22894. m.flags |= 8388608 /* Ambient */;
  22895. }
  22896. return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
  22897. }
  22898. else {
  22899. return parseDeclarationWorker(node);
  22900. }
  22901. }
  22902. function tryReuseAmbientDeclaration() {
  22903. return doInsideOfContext(8388608 /* Ambient */, function () {
  22904. var node = currentNode(parsingContext);
  22905. if (node) {
  22906. return consumeNode(node);
  22907. }
  22908. });
  22909. }
  22910. function parseDeclarationWorker(node) {
  22911. switch (token()) {
  22912. case 109 /* VarKeyword */:
  22913. case 115 /* LetKeyword */:
  22914. case 81 /* ConstKeyword */:
  22915. return parseVariableStatement(node);
  22916. case 94 /* FunctionKeyword */:
  22917. return parseFunctionDeclaration(node);
  22918. case 80 /* ClassKeyword */:
  22919. return parseClassDeclaration(node);
  22920. case 114 /* InterfaceKeyword */:
  22921. return parseInterfaceDeclaration(node);
  22922. case 145 /* TypeKeyword */:
  22923. return parseTypeAliasDeclaration(node);
  22924. case 88 /* EnumKeyword */:
  22925. return parseEnumDeclaration(node);
  22926. case 150 /* GlobalKeyword */:
  22927. case 135 /* ModuleKeyword */:
  22928. case 136 /* NamespaceKeyword */:
  22929. return parseModuleDeclaration(node);
  22930. case 96 /* ImportKeyword */:
  22931. return parseImportDeclarationOrImportEqualsDeclaration(node);
  22932. case 89 /* ExportKeyword */:
  22933. nextToken();
  22934. switch (token()) {
  22935. case 84 /* DefaultKeyword */:
  22936. case 62 /* EqualsToken */:
  22937. return parseExportAssignment(node);
  22938. case 123 /* AsKeyword */:
  22939. return parseNamespaceExportDeclaration(node);
  22940. default:
  22941. return parseExportDeclaration(node);
  22942. }
  22943. default:
  22944. if (node.decorators || node.modifiers) {
  22945. // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
  22946. // would follow. For recovery and error reporting purposes, return an incomplete declaration.
  22947. var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
  22948. missing.pos = node.pos;
  22949. missing.decorators = node.decorators;
  22950. missing.modifiers = node.modifiers;
  22951. return finishNode(missing);
  22952. }
  22953. return undefined; // TODO: GH#18217
  22954. }
  22955. }
  22956. function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
  22957. nextToken();
  22958. return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
  22959. }
  22960. function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
  22961. if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
  22962. parseSemicolon();
  22963. return;
  22964. }
  22965. return parseFunctionBlock(flags, diagnosticMessage);
  22966. }
  22967. // DECLARATIONS
  22968. function parseArrayBindingElement() {
  22969. if (token() === 27 /* CommaToken */) {
  22970. return createNode(215 /* OmittedExpression */);
  22971. }
  22972. var node = createNode(191 /* BindingElement */);
  22973. node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
  22974. node.name = parseIdentifierOrPattern();
  22975. node.initializer = parseInitializer();
  22976. return finishNode(node);
  22977. }
  22978. function parseObjectBindingElement() {
  22979. var node = createNode(191 /* BindingElement */);
  22980. node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
  22981. var tokenIsIdentifier = isIdentifier();
  22982. var propertyName = parsePropertyName();
  22983. if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
  22984. node.name = propertyName;
  22985. }
  22986. else {
  22987. parseExpected(58 /* ColonToken */);
  22988. node.propertyName = propertyName;
  22989. node.name = parseIdentifierOrPattern();
  22990. }
  22991. node.initializer = parseInitializer();
  22992. return finishNode(node);
  22993. }
  22994. function parseObjectBindingPattern() {
  22995. var node = createNode(189 /* ObjectBindingPattern */);
  22996. parseExpected(18 /* OpenBraceToken */);
  22997. node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
  22998. parseExpected(19 /* CloseBraceToken */);
  22999. return finishNode(node);
  23000. }
  23001. function parseArrayBindingPattern() {
  23002. var node = createNode(190 /* ArrayBindingPattern */);
  23003. parseExpected(22 /* OpenBracketToken */);
  23004. node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
  23005. parseExpected(23 /* CloseBracketToken */);
  23006. return finishNode(node);
  23007. }
  23008. function isIdentifierOrPrivateIdentifierOrPattern() {
  23009. return token() === 18 /* OpenBraceToken */
  23010. || token() === 22 /* OpenBracketToken */
  23011. || token() === 76 /* PrivateIdentifier */
  23012. || isIdentifier();
  23013. }
  23014. function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
  23015. if (token() === 22 /* OpenBracketToken */) {
  23016. return parseArrayBindingPattern();
  23017. }
  23018. if (token() === 18 /* OpenBraceToken */) {
  23019. return parseObjectBindingPattern();
  23020. }
  23021. return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
  23022. }
  23023. function parseVariableDeclarationAllowExclamation() {
  23024. return parseVariableDeclaration(/*allowExclamation*/ true);
  23025. }
  23026. function parseVariableDeclaration(allowExclamation) {
  23027. var node = createNode(242 /* VariableDeclaration */);
  23028. node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
  23029. if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
  23030. token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
  23031. node.exclamationToken = parseTokenNode();
  23032. }
  23033. node.type = parseTypeAnnotation();
  23034. if (!isInOrOfKeyword(token())) {
  23035. node.initializer = parseInitializer();
  23036. }
  23037. return finishNode(node);
  23038. }
  23039. function parseVariableDeclarationList(inForStatementInitializer) {
  23040. var node = createNode(243 /* VariableDeclarationList */);
  23041. switch (token()) {
  23042. case 109 /* VarKeyword */:
  23043. break;
  23044. case 115 /* LetKeyword */:
  23045. node.flags |= 1 /* Let */;
  23046. break;
  23047. case 81 /* ConstKeyword */:
  23048. node.flags |= 2 /* Const */;
  23049. break;
  23050. default:
  23051. ts.Debug.fail();
  23052. }
  23053. nextToken();
  23054. // The user may have written the following:
  23055. //
  23056. // for (let of X) { }
  23057. //
  23058. // In this case, we want to parse an empty declaration list, and then parse 'of'
  23059. // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
  23060. // So we need to look ahead to determine if 'of' should be treated as a keyword in
  23061. // this context.
  23062. // The checker will then give an error that there is an empty declaration list.
  23063. if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
  23064. node.declarations = createMissingList();
  23065. }
  23066. else {
  23067. var savedDisallowIn = inDisallowInContext();
  23068. setDisallowInContext(inForStatementInitializer);
  23069. node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
  23070. setDisallowInContext(savedDisallowIn);
  23071. }
  23072. return finishNode(node);
  23073. }
  23074. function canFollowContextualOfKeyword() {
  23075. return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
  23076. }
  23077. function parseVariableStatement(node) {
  23078. node.kind = 225 /* VariableStatement */;
  23079. node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
  23080. parseSemicolon();
  23081. return finishNode(node);
  23082. }
  23083. function parseFunctionDeclaration(node) {
  23084. node.kind = 244 /* FunctionDeclaration */;
  23085. parseExpected(94 /* FunctionKeyword */);
  23086. node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
  23087. node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
  23088. var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
  23089. var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
  23090. fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
  23091. node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
  23092. return finishNode(node);
  23093. }
  23094. function parseConstructorName() {
  23095. if (token() === 129 /* ConstructorKeyword */) {
  23096. return parseExpected(129 /* ConstructorKeyword */);
  23097. }
  23098. if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
  23099. return tryParse(function () {
  23100. var literalNode = parseLiteralNode();
  23101. return literalNode.text === "constructor" ? literalNode : undefined;
  23102. });
  23103. }
  23104. }
  23105. function tryParseConstructorDeclaration(node) {
  23106. return tryParse(function () {
  23107. if (parseConstructorName()) {
  23108. node.kind = 162 /* Constructor */;
  23109. fillSignature(58 /* ColonToken */, 0 /* None */, node);
  23110. node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
  23111. return finishNode(node);
  23112. }
  23113. });
  23114. }
  23115. function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
  23116. node.kind = 161 /* MethodDeclaration */;
  23117. node.asteriskToken = asteriskToken;
  23118. var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
  23119. var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
  23120. fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
  23121. node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
  23122. return finishNode(node);
  23123. }
  23124. function parsePropertyDeclaration(node) {
  23125. node.kind = 159 /* PropertyDeclaration */;
  23126. if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
  23127. node.exclamationToken = parseTokenNode();
  23128. }
  23129. node.type = parseTypeAnnotation();
  23130. node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
  23131. parseSemicolon();
  23132. return finishNode(node);
  23133. }
  23134. function parsePropertyOrMethodDeclaration(node) {
  23135. var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
  23136. node.name = parsePropertyName();
  23137. // Note: this is not legal as per the grammar. But we allow it in the parser and
  23138. // report an error in the grammar checker.
  23139. node.questionToken = parseOptionalToken(57 /* QuestionToken */);
  23140. if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
  23141. return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
  23142. }
  23143. return parsePropertyDeclaration(node);
  23144. }
  23145. function parseAccessorDeclaration(node, kind) {
  23146. node.kind = kind;
  23147. node.name = parsePropertyName();
  23148. fillSignature(58 /* ColonToken */, 0 /* None */, node);
  23149. node.body = parseFunctionBlockOrSemicolon(0 /* None */);
  23150. return finishNode(node);
  23151. }
  23152. function isClassMemberStart() {
  23153. var idToken;
  23154. if (token() === 59 /* AtToken */) {
  23155. return true;
  23156. }
  23157. // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
  23158. while (ts.isModifierKind(token())) {
  23159. idToken = token();
  23160. // If the idToken is a class modifier (protected, private, public, and static), it is
  23161. // certain that we are starting to parse class member. This allows better error recovery
  23162. // Example:
  23163. // public foo() ... // true
  23164. // public @dec blah ... // true; we will then report an error later
  23165. // export public ... // true; we will then report an error later
  23166. if (ts.isClassMemberModifier(idToken)) {
  23167. return true;
  23168. }
  23169. nextToken();
  23170. }
  23171. if (token() === 41 /* AsteriskToken */) {
  23172. return true;
  23173. }
  23174. // Try to get the first property-like token following all modifiers.
  23175. // This can either be an identifier or the 'get' or 'set' keywords.
  23176. if (isLiteralPropertyName()) {
  23177. idToken = token();
  23178. nextToken();
  23179. }
  23180. // Index signatures and computed properties are class members; we can parse.
  23181. if (token() === 22 /* OpenBracketToken */) {
  23182. return true;
  23183. }
  23184. // If we were able to get any potential identifier...
  23185. if (idToken !== undefined) {
  23186. // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
  23187. if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
  23188. return true;
  23189. }
  23190. // If it *is* a keyword, but not an accessor, check a little farther along
  23191. // to see if it should actually be parsed as a class member.
  23192. switch (token()) {
  23193. case 20 /* OpenParenToken */: // Method declaration
  23194. case 29 /* LessThanToken */: // Generic Method declaration
  23195. case 53 /* ExclamationToken */: // Non-null assertion on property name
  23196. case 58 /* ColonToken */: // Type Annotation for declaration
  23197. case 62 /* EqualsToken */: // Initializer for declaration
  23198. case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
  23199. return true;
  23200. default:
  23201. // Covers
  23202. // - Semicolons (declaration termination)
  23203. // - Closing braces (end-of-class, must be declaration)
  23204. // - End-of-files (not valid, but permitted so that it gets caught later on)
  23205. // - Line-breaks (enabling *automatic semicolon insertion*)
  23206. return canParseSemicolon();
  23207. }
  23208. }
  23209. return false;
  23210. }
  23211. function parseDecorators() {
  23212. var list;
  23213. var listPos = getNodePos();
  23214. while (true) {
  23215. var decoratorStart = getNodePos();
  23216. if (!parseOptional(59 /* AtToken */)) {
  23217. break;
  23218. }
  23219. var decorator = createNode(157 /* Decorator */, decoratorStart);
  23220. decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
  23221. finishNode(decorator);
  23222. (list || (list = [])).push(decorator);
  23223. }
  23224. return list && createNodeArray(list, listPos);
  23225. }
  23226. /*
  23227. * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
  23228. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
  23229. * and turns it into a standalone declaration), then it is better to parse it and report an error later.
  23230. *
  23231. * In such situations, 'permitInvalidConstAsModifier' should be set to true.
  23232. */
  23233. function parseModifiers(permitInvalidConstAsModifier) {
  23234. var list;
  23235. var listPos = getNodePos();
  23236. while (true) {
  23237. var modifierStart = scanner.getStartPos();
  23238. var modifierKind = token();
  23239. if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
  23240. // We need to ensure that any subsequent modifiers appear on the same line
  23241. // so that when 'const' is a standalone declaration, we don't issue an error.
  23242. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
  23243. break;
  23244. }
  23245. }
  23246. else {
  23247. if (!parseAnyContextualModifier()) {
  23248. break;
  23249. }
  23250. }
  23251. var modifier = finishNode(createNode(modifierKind, modifierStart));
  23252. (list || (list = [])).push(modifier);
  23253. }
  23254. return list && createNodeArray(list, listPos);
  23255. }
  23256. function parseModifiersForArrowFunction() {
  23257. var modifiers;
  23258. if (token() === 126 /* AsyncKeyword */) {
  23259. var modifierStart = scanner.getStartPos();
  23260. var modifierKind = token();
  23261. nextToken();
  23262. var modifier = finishNode(createNode(modifierKind, modifierStart));
  23263. modifiers = createNodeArray([modifier], modifierStart);
  23264. }
  23265. return modifiers;
  23266. }
  23267. function parseClassElement() {
  23268. if (token() === 26 /* SemicolonToken */) {
  23269. var result = createNode(222 /* SemicolonClassElement */);
  23270. nextToken();
  23271. return finishNode(result);
  23272. }
  23273. var node = createNodeWithJSDoc(0 /* Unknown */);
  23274. node.decorators = parseDecorators();
  23275. node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
  23276. if (parseContextualModifier(131 /* GetKeyword */)) {
  23277. return parseAccessorDeclaration(node, 163 /* GetAccessor */);
  23278. }
  23279. if (parseContextualModifier(142 /* SetKeyword */)) {
  23280. return parseAccessorDeclaration(node, 164 /* SetAccessor */);
  23281. }
  23282. if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
  23283. var constructorDeclaration = tryParseConstructorDeclaration(node);
  23284. if (constructorDeclaration) {
  23285. return constructorDeclaration;
  23286. }
  23287. }
  23288. if (isIndexSignature()) {
  23289. return parseIndexSignatureDeclaration(node);
  23290. }
  23291. // It is very important that we check this *after* checking indexers because
  23292. // the [ token can start an index signature or a computed property name
  23293. if (ts.tokenIsIdentifierOrKeyword(token()) ||
  23294. token() === 10 /* StringLiteral */ ||
  23295. token() === 8 /* NumericLiteral */ ||
  23296. token() === 41 /* AsteriskToken */ ||
  23297. token() === 22 /* OpenBracketToken */) {
  23298. var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
  23299. if (isAmbient) {
  23300. for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
  23301. var m = _a[_i];
  23302. m.flags |= 8388608 /* Ambient */;
  23303. }
  23304. return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
  23305. }
  23306. else {
  23307. return parsePropertyOrMethodDeclaration(node);
  23308. }
  23309. }
  23310. if (node.decorators || node.modifiers) {
  23311. // treat this as a property declaration with a missing name.
  23312. node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
  23313. return parsePropertyDeclaration(node);
  23314. }
  23315. // 'isClassMemberStart' should have hinted not to attempt parsing.
  23316. return ts.Debug.fail("Should not have attempted to parse class member declaration.");
  23317. }
  23318. function parseClassExpression() {
  23319. return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
  23320. }
  23321. function parseClassDeclaration(node) {
  23322. return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
  23323. }
  23324. function parseClassDeclarationOrExpression(node, kind) {
  23325. node.kind = kind;
  23326. parseExpected(80 /* ClassKeyword */);
  23327. node.name = parseNameOfClassDeclarationOrExpression();
  23328. node.typeParameters = parseTypeParameters();
  23329. node.heritageClauses = parseHeritageClauses();
  23330. if (parseExpected(18 /* OpenBraceToken */)) {
  23331. // ClassTail[Yield,Await] : (Modified) See 14.5
  23332. // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
  23333. node.members = parseClassMembers();
  23334. parseExpected(19 /* CloseBraceToken */);
  23335. }
  23336. else {
  23337. node.members = createMissingList();
  23338. }
  23339. return finishNode(node);
  23340. }
  23341. function parseNameOfClassDeclarationOrExpression() {
  23342. // implements is a future reserved word so
  23343. // 'class implements' might mean either
  23344. // - class expression with omitted name, 'implements' starts heritage clause
  23345. // - class with name 'implements'
  23346. // 'isImplementsClause' helps to disambiguate between these two cases
  23347. return isIdentifier() && !isImplementsClause()
  23348. ? parseIdentifier()
  23349. : undefined;
  23350. }
  23351. function isImplementsClause() {
  23352. return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
  23353. }
  23354. function parseHeritageClauses() {
  23355. // ClassTail[Yield,Await] : (Modified) See 14.5
  23356. // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
  23357. if (isHeritageClause()) {
  23358. return parseList(22 /* HeritageClauses */, parseHeritageClause);
  23359. }
  23360. return undefined;
  23361. }
  23362. function parseHeritageClause() {
  23363. var tok = token();
  23364. ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
  23365. var node = createNode(279 /* HeritageClause */);
  23366. node.token = tok;
  23367. nextToken();
  23368. node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
  23369. return finishNode(node);
  23370. }
  23371. function parseExpressionWithTypeArguments() {
  23372. var node = createNode(216 /* ExpressionWithTypeArguments */);
  23373. node.expression = parseLeftHandSideExpressionOrHigher();
  23374. node.typeArguments = tryParseTypeArguments();
  23375. return finishNode(node);
  23376. }
  23377. function tryParseTypeArguments() {
  23378. return token() === 29 /* LessThanToken */ ?
  23379. parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
  23380. }
  23381. function isHeritageClause() {
  23382. return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
  23383. }
  23384. function parseClassMembers() {
  23385. return parseList(5 /* ClassMembers */, parseClassElement);
  23386. }
  23387. function parseInterfaceDeclaration(node) {
  23388. node.kind = 246 /* InterfaceDeclaration */;
  23389. parseExpected(114 /* InterfaceKeyword */);
  23390. node.name = parseIdentifier();
  23391. node.typeParameters = parseTypeParameters();
  23392. node.heritageClauses = parseHeritageClauses();
  23393. node.members = parseObjectTypeMembers();
  23394. return finishNode(node);
  23395. }
  23396. function parseTypeAliasDeclaration(node) {
  23397. node.kind = 247 /* TypeAliasDeclaration */;
  23398. parseExpected(145 /* TypeKeyword */);
  23399. node.name = parseIdentifier();
  23400. node.typeParameters = parseTypeParameters();
  23401. parseExpected(62 /* EqualsToken */);
  23402. node.type = parseType();
  23403. parseSemicolon();
  23404. return finishNode(node);
  23405. }
  23406. // In an ambient declaration, the grammar only allows integer literals as initializers.
  23407. // In a non-ambient declaration, the grammar allows uninitialized members only in a
  23408. // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
  23409. // or any time an integer literal initializer is encountered.
  23410. function parseEnumMember() {
  23411. var node = createNodeWithJSDoc(284 /* EnumMember */);
  23412. node.name = parsePropertyName();
  23413. node.initializer = allowInAnd(parseInitializer);
  23414. return finishNode(node);
  23415. }
  23416. function parseEnumDeclaration(node) {
  23417. node.kind = 248 /* EnumDeclaration */;
  23418. parseExpected(88 /* EnumKeyword */);
  23419. node.name = parseIdentifier();
  23420. if (parseExpected(18 /* OpenBraceToken */)) {
  23421. node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
  23422. parseExpected(19 /* CloseBraceToken */);
  23423. }
  23424. else {
  23425. node.members = createMissingList();
  23426. }
  23427. return finishNode(node);
  23428. }
  23429. function parseModuleBlock() {
  23430. var node = createNode(250 /* ModuleBlock */);
  23431. if (parseExpected(18 /* OpenBraceToken */)) {
  23432. node.statements = parseList(1 /* BlockStatements */, parseStatement);
  23433. parseExpected(19 /* CloseBraceToken */);
  23434. }
  23435. else {
  23436. node.statements = createMissingList();
  23437. }
  23438. return finishNode(node);
  23439. }
  23440. function parseModuleOrNamespaceDeclaration(node, flags) {
  23441. node.kind = 249 /* ModuleDeclaration */;
  23442. // If we are parsing a dotted namespace name, we want to
  23443. // propagate the 'Namespace' flag across the names if set.
  23444. var namespaceFlag = flags & 16 /* Namespace */;
  23445. node.flags |= flags;
  23446. node.name = parseIdentifier();
  23447. node.body = parseOptional(24 /* DotToken */)
  23448. ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
  23449. : parseModuleBlock();
  23450. return finishNode(node);
  23451. }
  23452. function parseAmbientExternalModuleDeclaration(node) {
  23453. node.kind = 249 /* ModuleDeclaration */;
  23454. if (token() === 150 /* GlobalKeyword */) {
  23455. // parse 'global' as name of global scope augmentation
  23456. node.name = parseIdentifier();
  23457. node.flags |= 1024 /* GlobalAugmentation */;
  23458. }
  23459. else {
  23460. node.name = parseLiteralNode();
  23461. node.name.text = internIdentifier(node.name.text);
  23462. }
  23463. if (token() === 18 /* OpenBraceToken */) {
  23464. node.body = parseModuleBlock();
  23465. }
  23466. else {
  23467. parseSemicolon();
  23468. }
  23469. return finishNode(node);
  23470. }
  23471. function parseModuleDeclaration(node) {
  23472. var flags = 0;
  23473. if (token() === 150 /* GlobalKeyword */) {
  23474. // global augmentation
  23475. return parseAmbientExternalModuleDeclaration(node);
  23476. }
  23477. else if (parseOptional(136 /* NamespaceKeyword */)) {
  23478. flags |= 16 /* Namespace */;
  23479. }
  23480. else {
  23481. parseExpected(135 /* ModuleKeyword */);
  23482. if (token() === 10 /* StringLiteral */) {
  23483. return parseAmbientExternalModuleDeclaration(node);
  23484. }
  23485. }
  23486. return parseModuleOrNamespaceDeclaration(node, flags);
  23487. }
  23488. function isExternalModuleReference() {
  23489. return token() === 139 /* RequireKeyword */ &&
  23490. lookAhead(nextTokenIsOpenParen);
  23491. }
  23492. function nextTokenIsOpenParen() {
  23493. return nextToken() === 20 /* OpenParenToken */;
  23494. }
  23495. function nextTokenIsSlash() {
  23496. return nextToken() === 43 /* SlashToken */;
  23497. }
  23498. function parseNamespaceExportDeclaration(node) {
  23499. node.kind = 252 /* NamespaceExportDeclaration */;
  23500. parseExpected(123 /* AsKeyword */);
  23501. parseExpected(136 /* NamespaceKeyword */);
  23502. node.name = parseIdentifier();
  23503. parseSemicolon();
  23504. return finishNode(node);
  23505. }
  23506. function parseImportDeclarationOrImportEqualsDeclaration(node) {
  23507. parseExpected(96 /* ImportKeyword */);
  23508. var afterImportPos = scanner.getStartPos();
  23509. var identifier;
  23510. if (isIdentifier()) {
  23511. identifier = parseIdentifier();
  23512. }
  23513. var isTypeOnly = false;
  23514. if (token() !== 149 /* FromKeyword */ &&
  23515. (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
  23516. (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
  23517. isTypeOnly = true;
  23518. identifier = isIdentifier() ? parseIdentifier() : undefined;
  23519. }
  23520. if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
  23521. return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
  23522. }
  23523. // Import statement
  23524. node.kind = 254 /* ImportDeclaration */;
  23525. // ImportDeclaration:
  23526. // import ImportClause from ModuleSpecifier ;
  23527. // import ModuleSpecifier;
  23528. if (identifier || // import id
  23529. token() === 41 /* AsteriskToken */ || // import *
  23530. token() === 18 /* OpenBraceToken */ // import {
  23531. ) {
  23532. node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
  23533. parseExpected(149 /* FromKeyword */);
  23534. }
  23535. node.moduleSpecifier = parseModuleSpecifier();
  23536. parseSemicolon();
  23537. return finishNode(node);
  23538. }
  23539. function tokenAfterImportDefinitelyProducesImportDeclaration() {
  23540. return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
  23541. }
  23542. function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
  23543. // In `import id ___`, the current token decides whether to produce
  23544. // an ImportDeclaration or ImportEqualsDeclaration.
  23545. return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
  23546. }
  23547. function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
  23548. node.kind = 253 /* ImportEqualsDeclaration */;
  23549. node.name = identifier;
  23550. parseExpected(62 /* EqualsToken */);
  23551. node.moduleReference = parseModuleReference();
  23552. parseSemicolon();
  23553. var finished = finishNode(node);
  23554. if (isTypeOnly) {
  23555. parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
  23556. }
  23557. return finished;
  23558. }
  23559. function parseImportClause(identifier, fullStart, isTypeOnly) {
  23560. // ImportClause:
  23561. // ImportedDefaultBinding
  23562. // NameSpaceImport
  23563. // NamedImports
  23564. // ImportedDefaultBinding, NameSpaceImport
  23565. // ImportedDefaultBinding, NamedImports
  23566. var importClause = createNode(255 /* ImportClause */, fullStart);
  23567. importClause.isTypeOnly = isTypeOnly;
  23568. if (identifier) {
  23569. // ImportedDefaultBinding:
  23570. // ImportedBinding
  23571. importClause.name = identifier;
  23572. }
  23573. // If there was no default import or if there is comma token after default import
  23574. // parse namespace or named imports
  23575. if (!importClause.name ||
  23576. parseOptional(27 /* CommaToken */)) {
  23577. importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
  23578. }
  23579. return finishNode(importClause);
  23580. }
  23581. function parseModuleReference() {
  23582. return isExternalModuleReference()
  23583. ? parseExternalModuleReference()
  23584. : parseEntityName(/*allowReservedWords*/ false);
  23585. }
  23586. function parseExternalModuleReference() {
  23587. var node = createNode(265 /* ExternalModuleReference */);
  23588. parseExpected(139 /* RequireKeyword */);
  23589. parseExpected(20 /* OpenParenToken */);
  23590. node.expression = parseModuleSpecifier();
  23591. parseExpected(21 /* CloseParenToken */);
  23592. return finishNode(node);
  23593. }
  23594. function parseModuleSpecifier() {
  23595. if (token() === 10 /* StringLiteral */) {
  23596. var result = parseLiteralNode();
  23597. result.text = internIdentifier(result.text);
  23598. return result;
  23599. }
  23600. else {
  23601. // We allow arbitrary expressions here, even though the grammar only allows string
  23602. // literals. We check to ensure that it is only a string literal later in the grammar
  23603. // check pass.
  23604. return parseExpression();
  23605. }
  23606. }
  23607. function parseNamespaceImport() {
  23608. // NameSpaceImport:
  23609. // * as ImportedBinding
  23610. var namespaceImport = createNode(256 /* NamespaceImport */);
  23611. parseExpected(41 /* AsteriskToken */);
  23612. parseExpected(123 /* AsKeyword */);
  23613. namespaceImport.name = parseIdentifier();
  23614. return finishNode(namespaceImport);
  23615. }
  23616. function parseNamedImportsOrExports(kind) {
  23617. var node = createNode(kind);
  23618. // NamedImports:
  23619. // { }
  23620. // { ImportsList }
  23621. // { ImportsList, }
  23622. // ImportsList:
  23623. // ImportSpecifier
  23624. // ImportsList, ImportSpecifier
  23625. node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
  23626. return finishNode(node);
  23627. }
  23628. function parseExportSpecifier() {
  23629. return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
  23630. }
  23631. function parseImportSpecifier() {
  23632. return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
  23633. }
  23634. function parseImportOrExportSpecifier(kind) {
  23635. var node = createNode(kind);
  23636. // ImportSpecifier:
  23637. // BindingIdentifier
  23638. // IdentifierName as BindingIdentifier
  23639. // ExportSpecifier:
  23640. // IdentifierName
  23641. // IdentifierName as IdentifierName
  23642. var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
  23643. var checkIdentifierStart = scanner.getTokenPos();
  23644. var checkIdentifierEnd = scanner.getTextPos();
  23645. var identifierName = parseIdentifierName();
  23646. if (token() === 123 /* AsKeyword */) {
  23647. node.propertyName = identifierName;
  23648. parseExpected(123 /* AsKeyword */);
  23649. checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
  23650. checkIdentifierStart = scanner.getTokenPos();
  23651. checkIdentifierEnd = scanner.getTextPos();
  23652. node.name = parseIdentifierName();
  23653. }
  23654. else {
  23655. node.name = identifierName;
  23656. }
  23657. if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
  23658. parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
  23659. }
  23660. return finishNode(node);
  23661. }
  23662. function parseNamespaceExport(pos) {
  23663. var node = createNode(262 /* NamespaceExport */, pos);
  23664. node.name = parseIdentifier();
  23665. return finishNode(node);
  23666. }
  23667. function parseExportDeclaration(node) {
  23668. node.kind = 260 /* ExportDeclaration */;
  23669. node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
  23670. var namespaceExportPos = scanner.getStartPos();
  23671. if (parseOptional(41 /* AsteriskToken */)) {
  23672. if (parseOptional(123 /* AsKeyword */)) {
  23673. node.exportClause = parseNamespaceExport(namespaceExportPos);
  23674. }
  23675. parseExpected(149 /* FromKeyword */);
  23676. node.moduleSpecifier = parseModuleSpecifier();
  23677. }
  23678. else {
  23679. node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
  23680. // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
  23681. // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
  23682. // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
  23683. if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
  23684. parseExpected(149 /* FromKeyword */);
  23685. node.moduleSpecifier = parseModuleSpecifier();
  23686. }
  23687. }
  23688. parseSemicolon();
  23689. return finishNode(node);
  23690. }
  23691. function parseExportAssignment(node) {
  23692. node.kind = 259 /* ExportAssignment */;
  23693. if (parseOptional(62 /* EqualsToken */)) {
  23694. node.isExportEquals = true;
  23695. }
  23696. else {
  23697. parseExpected(84 /* DefaultKeyword */);
  23698. }
  23699. node.expression = parseAssignmentExpressionOrHigher();
  23700. parseSemicolon();
  23701. return finishNode(node);
  23702. }
  23703. function setExternalModuleIndicator(sourceFile) {
  23704. // Try to use the first top-level import/export when available, then
  23705. // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
  23706. sourceFile.externalModuleIndicator =
  23707. ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
  23708. getImportMetaIfNecessary(sourceFile);
  23709. }
  23710. function isAnExternalModuleIndicatorNode(node) {
  23711. return hasModifierOfKind(node, 89 /* ExportKeyword */)
  23712. || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
  23713. || node.kind === 254 /* ImportDeclaration */
  23714. || node.kind === 259 /* ExportAssignment */
  23715. || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
  23716. }
  23717. function getImportMetaIfNecessary(sourceFile) {
  23718. return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
  23719. walkTreeForExternalModuleIndicators(sourceFile) :
  23720. undefined;
  23721. }
  23722. function walkTreeForExternalModuleIndicators(node) {
  23723. return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
  23724. }
  23725. /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
  23726. function hasModifierOfKind(node, kind) {
  23727. return ts.some(node.modifiers, function (m) { return m.kind === kind; });
  23728. }
  23729. function isImportMeta(node) {
  23730. return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
  23731. }
  23732. var ParsingContext;
  23733. (function (ParsingContext) {
  23734. ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
  23735. ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
  23736. ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
  23737. ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
  23738. ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
  23739. ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
  23740. ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
  23741. ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
  23742. ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
  23743. ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
  23744. ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
  23745. ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
  23746. ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
  23747. ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
  23748. ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
  23749. ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
  23750. ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
  23751. ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
  23752. ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
  23753. ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
  23754. ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
  23755. ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
  23756. ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
  23757. ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
  23758. ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
  23759. })(ParsingContext || (ParsingContext = {}));
  23760. var Tristate;
  23761. (function (Tristate) {
  23762. Tristate[Tristate["False"] = 0] = "False";
  23763. Tristate[Tristate["True"] = 1] = "True";
  23764. Tristate[Tristate["Unknown"] = 2] = "Unknown";
  23765. })(Tristate || (Tristate = {}));
  23766. var JSDocParser;
  23767. (function (JSDocParser) {
  23768. function parseJSDocTypeExpressionForTests(content, start, length) {
  23769. initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
  23770. sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
  23771. scanner.setText(content, start, length);
  23772. currentToken = scanner.scan();
  23773. var jsDocTypeExpression = parseJSDocTypeExpression();
  23774. var diagnostics = parseDiagnostics;
  23775. clearState();
  23776. return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
  23777. }
  23778. JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
  23779. // Parses out a JSDoc type expression.
  23780. function parseJSDocTypeExpression(mayOmitBraces) {
  23781. var result = createNode(294 /* JSDocTypeExpression */);
  23782. var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
  23783. result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
  23784. if (!mayOmitBraces || hasBrace) {
  23785. parseExpectedJSDoc(19 /* CloseBraceToken */);
  23786. }
  23787. fixupParentReferences(result);
  23788. return finishNode(result);
  23789. }
  23790. JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
  23791. function parseIsolatedJSDocComment(content, start, length) {
  23792. initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
  23793. sourceFile = { languageVariant: 0 /* Standard */, text: content };
  23794. var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
  23795. var diagnostics = parseDiagnostics;
  23796. clearState();
  23797. return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
  23798. }
  23799. JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
  23800. function parseJSDocComment(parent, start, length) {
  23801. var _a;
  23802. var saveToken = currentToken;
  23803. var saveParseDiagnosticsLength = parseDiagnostics.length;
  23804. var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
  23805. var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
  23806. if (comment) {
  23807. comment.parent = parent;
  23808. }
  23809. if (contextFlags & 131072 /* JavaScriptFile */) {
  23810. if (!sourceFile.jsDocDiagnostics) {
  23811. sourceFile.jsDocDiagnostics = [];
  23812. }
  23813. (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
  23814. }
  23815. currentToken = saveToken;
  23816. parseDiagnostics.length = saveParseDiagnosticsLength;
  23817. parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
  23818. return comment;
  23819. }
  23820. JSDocParser.parseJSDocComment = parseJSDocComment;
  23821. var JSDocState;
  23822. (function (JSDocState) {
  23823. JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
  23824. JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
  23825. JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
  23826. JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
  23827. })(JSDocState || (JSDocState = {}));
  23828. var PropertyLikeParse;
  23829. (function (PropertyLikeParse) {
  23830. PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
  23831. PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
  23832. PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
  23833. })(PropertyLikeParse || (PropertyLikeParse = {}));
  23834. function parseJSDocCommentWorker(start, length) {
  23835. if (start === void 0) { start = 0; }
  23836. var content = sourceText;
  23837. var end = length === undefined ? content.length : start + length;
  23838. length = end - start;
  23839. ts.Debug.assert(start >= 0);
  23840. ts.Debug.assert(start <= end);
  23841. ts.Debug.assert(end <= content.length);
  23842. // Check for /** (JSDoc opening part)
  23843. if (!isJSDocLikeText(content, start)) {
  23844. return undefined;
  23845. }
  23846. var tags;
  23847. var tagsPos;
  23848. var tagsEnd;
  23849. var comments = [];
  23850. // + 3 for leading /**, - 5 in total for /** */
  23851. return scanner.scanRange(start + 3, length - 5, function () {
  23852. // Initially we can parse out a tag. We also have seen a starting asterisk.
  23853. // This is so that /** * @type */ doesn't parse.
  23854. var state = 1 /* SawAsterisk */;
  23855. var margin;
  23856. // + 4 for leading '/** '
  23857. var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
  23858. function pushComment(text) {
  23859. if (!margin) {
  23860. margin = indent;
  23861. }
  23862. comments.push(text);
  23863. indent += text.length;
  23864. }
  23865. nextTokenJSDoc();
  23866. while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
  23867. ;
  23868. if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
  23869. state = 0 /* BeginningOfLine */;
  23870. indent = 0;
  23871. }
  23872. loop: while (true) {
  23873. switch (token()) {
  23874. case 59 /* AtToken */:
  23875. if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
  23876. removeTrailingWhitespace(comments);
  23877. addTag(parseTag(indent));
  23878. // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
  23879. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
  23880. // for malformed examples like `/** @param {string} x @returns {number} the length */`
  23881. state = 0 /* BeginningOfLine */;
  23882. margin = undefined;
  23883. }
  23884. else {
  23885. pushComment(scanner.getTokenText());
  23886. }
  23887. break;
  23888. case 4 /* NewLineTrivia */:
  23889. comments.push(scanner.getTokenText());
  23890. state = 0 /* BeginningOfLine */;
  23891. indent = 0;
  23892. break;
  23893. case 41 /* AsteriskToken */:
  23894. var asterisk = scanner.getTokenText();
  23895. if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
  23896. // If we've already seen an asterisk, then we can no longer parse a tag on this line
  23897. state = 2 /* SavingComments */;
  23898. pushComment(asterisk);
  23899. }
  23900. else {
  23901. // Ignore the first asterisk on a line
  23902. state = 1 /* SawAsterisk */;
  23903. indent += asterisk.length;
  23904. }
  23905. break;
  23906. case 5 /* WhitespaceTrivia */:
  23907. // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
  23908. var whitespace = scanner.getTokenText();
  23909. if (state === 2 /* SavingComments */) {
  23910. comments.push(whitespace);
  23911. }
  23912. else if (margin !== undefined && indent + whitespace.length > margin) {
  23913. comments.push(whitespace.slice(margin - indent - 1));
  23914. }
  23915. indent += whitespace.length;
  23916. break;
  23917. case 1 /* EndOfFileToken */:
  23918. break loop;
  23919. default:
  23920. // Anything else is doc comment text. We just save it. Because it
  23921. // wasn't a tag, we can no longer parse a tag on this line until we hit the next
  23922. // line break.
  23923. state = 2 /* SavingComments */;
  23924. pushComment(scanner.getTokenText());
  23925. break;
  23926. }
  23927. nextTokenJSDoc();
  23928. }
  23929. removeLeadingNewlines(comments);
  23930. removeTrailingWhitespace(comments);
  23931. return createJSDocComment();
  23932. });
  23933. function removeLeadingNewlines(comments) {
  23934. while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
  23935. comments.shift();
  23936. }
  23937. }
  23938. function removeTrailingWhitespace(comments) {
  23939. while (comments.length && comments[comments.length - 1].trim() === "") {
  23940. comments.pop();
  23941. }
  23942. }
  23943. function createJSDocComment() {
  23944. var result = createNode(303 /* JSDocComment */, start);
  23945. result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
  23946. result.comment = comments.length ? comments.join("") : undefined;
  23947. return finishNode(result, end);
  23948. }
  23949. function isNextNonwhitespaceTokenEndOfFile() {
  23950. // We must use infinite lookahead, as there could be any number of newlines :(
  23951. while (true) {
  23952. nextTokenJSDoc();
  23953. if (token() === 1 /* EndOfFileToken */) {
  23954. return true;
  23955. }
  23956. if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
  23957. return false;
  23958. }
  23959. }
  23960. }
  23961. function skipWhitespace() {
  23962. if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
  23963. if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
  23964. return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
  23965. }
  23966. }
  23967. while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
  23968. nextTokenJSDoc();
  23969. }
  23970. }
  23971. function skipWhitespaceOrAsterisk() {
  23972. if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
  23973. if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
  23974. return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
  23975. }
  23976. }
  23977. var precedingLineBreak = scanner.hasPrecedingLineBreak();
  23978. var seenLineBreak = false;
  23979. var indentText = "";
  23980. while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
  23981. indentText += scanner.getTokenText();
  23982. if (token() === 4 /* NewLineTrivia */) {
  23983. precedingLineBreak = true;
  23984. seenLineBreak = true;
  23985. indentText = "";
  23986. }
  23987. else if (token() === 41 /* AsteriskToken */) {
  23988. precedingLineBreak = false;
  23989. }
  23990. nextTokenJSDoc();
  23991. }
  23992. return seenLineBreak ? indentText : "";
  23993. }
  23994. function parseTag(margin) {
  23995. ts.Debug.assert(token() === 59 /* AtToken */);
  23996. var start = scanner.getTokenPos();
  23997. nextTokenJSDoc();
  23998. var tagName = parseJSDocIdentifierName(/*message*/ undefined);
  23999. var indentText = skipWhitespaceOrAsterisk();
  24000. var tag;
  24001. switch (tagName.escapedText) {
  24002. case "author":
  24003. tag = parseAuthorTag(start, tagName, margin);
  24004. break;
  24005. case "augments":
  24006. case "extends":
  24007. tag = parseAugmentsTag(start, tagName);
  24008. break;
  24009. case "class":
  24010. case "constructor":
  24011. tag = parseSimpleTag(start, 309 /* JSDocClassTag */, tagName);
  24012. break;
  24013. case "public":
  24014. tag = parseSimpleTag(start, 310 /* JSDocPublicTag */, tagName);
  24015. break;
  24016. case "private":
  24017. tag = parseSimpleTag(start, 311 /* JSDocPrivateTag */, tagName);
  24018. break;
  24019. case "protected":
  24020. tag = parseSimpleTag(start, 312 /* JSDocProtectedTag */, tagName);
  24021. break;
  24022. case "readonly":
  24023. tag = parseSimpleTag(start, 313 /* JSDocReadonlyTag */, tagName);
  24024. break;
  24025. case "this":
  24026. tag = parseThisTag(start, tagName);
  24027. break;
  24028. case "enum":
  24029. tag = parseEnumTag(start, tagName);
  24030. break;
  24031. case "arg":
  24032. case "argument":
  24033. case "param":
  24034. return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
  24035. case "return":
  24036. case "returns":
  24037. tag = parseReturnTag(start, tagName);
  24038. break;
  24039. case "template":
  24040. tag = parseTemplateTag(start, tagName);
  24041. break;
  24042. case "type":
  24043. tag = parseTypeTag(start, tagName);
  24044. break;
  24045. case "typedef":
  24046. tag = parseTypedefTag(start, tagName, margin);
  24047. break;
  24048. case "callback":
  24049. tag = parseCallbackTag(start, tagName, margin);
  24050. break;
  24051. default:
  24052. tag = parseUnknownTag(start, tagName);
  24053. break;
  24054. }
  24055. if (!tag.comment) {
  24056. // some tags, like typedef and callback, have already parsed their comments earlier
  24057. if (!indentText) {
  24058. margin += tag.end - tag.pos;
  24059. }
  24060. tag.comment = parseTagComments(margin, indentText.slice(margin));
  24061. }
  24062. return tag;
  24063. }
  24064. function parseTagComments(indent, initialMargin) {
  24065. var comments = [];
  24066. var state = 0 /* BeginningOfLine */;
  24067. var margin;
  24068. function pushComment(text) {
  24069. if (!margin) {
  24070. margin = indent;
  24071. }
  24072. comments.push(text);
  24073. indent += text.length;
  24074. }
  24075. if (initialMargin) {
  24076. // jump straight to saving comments if there is some initial indentation
  24077. pushComment(initialMargin);
  24078. state = 2 /* SavingComments */;
  24079. }
  24080. var tok = token();
  24081. loop: while (true) {
  24082. switch (tok) {
  24083. case 4 /* NewLineTrivia */:
  24084. if (state >= 1 /* SawAsterisk */) {
  24085. state = 0 /* BeginningOfLine */;
  24086. // don't use pushComment here because we want to keep the margin unchanged
  24087. comments.push(scanner.getTokenText());
  24088. }
  24089. indent = 0;
  24090. break;
  24091. case 59 /* AtToken */:
  24092. if (state === 3 /* SavingBackticks */) {
  24093. comments.push(scanner.getTokenText());
  24094. break;
  24095. }
  24096. scanner.setTextPos(scanner.getTextPos() - 1);
  24097. // falls through
  24098. case 1 /* EndOfFileToken */:
  24099. // Done
  24100. break loop;
  24101. case 5 /* WhitespaceTrivia */:
  24102. if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
  24103. pushComment(scanner.getTokenText());
  24104. }
  24105. else {
  24106. var whitespace = scanner.getTokenText();
  24107. // if the whitespace crosses the margin, take only the whitespace that passes the margin
  24108. if (margin !== undefined && indent + whitespace.length > margin) {
  24109. comments.push(whitespace.slice(margin - indent));
  24110. }
  24111. indent += whitespace.length;
  24112. }
  24113. break;
  24114. case 18 /* OpenBraceToken */:
  24115. state = 2 /* SavingComments */;
  24116. if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
  24117. pushComment(scanner.getTokenText());
  24118. nextTokenJSDoc();
  24119. pushComment(scanner.getTokenText());
  24120. nextTokenJSDoc();
  24121. }
  24122. pushComment(scanner.getTokenText());
  24123. break;
  24124. case 61 /* BacktickToken */:
  24125. if (state === 3 /* SavingBackticks */) {
  24126. state = 2 /* SavingComments */;
  24127. }
  24128. else {
  24129. state = 3 /* SavingBackticks */;
  24130. }
  24131. pushComment(scanner.getTokenText());
  24132. break;
  24133. case 41 /* AsteriskToken */:
  24134. if (state === 0 /* BeginningOfLine */) {
  24135. // leading asterisks start recording on the *next* (non-whitespace) token
  24136. state = 1 /* SawAsterisk */;
  24137. indent += 1;
  24138. break;
  24139. }
  24140. // record the * as a comment
  24141. // falls through
  24142. default:
  24143. if (state !== 3 /* SavingBackticks */) {
  24144. state = 2 /* SavingComments */; // leading identifiers start recording as well
  24145. }
  24146. pushComment(scanner.getTokenText());
  24147. break;
  24148. }
  24149. tok = nextTokenJSDoc();
  24150. }
  24151. removeLeadingNewlines(comments);
  24152. removeTrailingWhitespace(comments);
  24153. return comments.length === 0 ? undefined : comments.join("");
  24154. }
  24155. function parseUnknownTag(start, tagName) {
  24156. var result = createNode(306 /* JSDocTag */, start);
  24157. result.tagName = tagName;
  24158. return finishNode(result);
  24159. }
  24160. function addTag(tag) {
  24161. if (!tag) {
  24162. return;
  24163. }
  24164. if (!tags) {
  24165. tags = [tag];
  24166. tagsPos = tag.pos;
  24167. }
  24168. else {
  24169. tags.push(tag);
  24170. }
  24171. tagsEnd = tag.end;
  24172. }
  24173. function tryParseTypeExpression() {
  24174. skipWhitespaceOrAsterisk();
  24175. return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
  24176. }
  24177. function parseBracketNameInPropertyAndParamTag() {
  24178. // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
  24179. var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
  24180. if (isBracketed) {
  24181. skipWhitespace();
  24182. }
  24183. // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
  24184. var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
  24185. var name = parseJSDocEntityName();
  24186. if (isBackquoted) {
  24187. parseExpectedTokenJSDoc(61 /* BacktickToken */);
  24188. }
  24189. if (isBracketed) {
  24190. skipWhitespace();
  24191. // May have an optional default, e.g. '[foo = 42]'
  24192. if (parseOptionalToken(62 /* EqualsToken */)) {
  24193. parseExpression();
  24194. }
  24195. parseExpected(23 /* CloseBracketToken */);
  24196. }
  24197. return { name: name, isBracketed: isBracketed };
  24198. }
  24199. function isObjectOrObjectArrayTypeReference(node) {
  24200. switch (node.kind) {
  24201. case 141 /* ObjectKeyword */:
  24202. return true;
  24203. case 174 /* ArrayType */:
  24204. return isObjectOrObjectArrayTypeReference(node.elementType);
  24205. default:
  24206. return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
  24207. }
  24208. }
  24209. function parseParameterOrPropertyTag(start, tagName, target, indent) {
  24210. var typeExpression = tryParseTypeExpression();
  24211. var isNameFirst = !typeExpression;
  24212. skipWhitespaceOrAsterisk();
  24213. var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
  24214. skipWhitespace();
  24215. if (isNameFirst) {
  24216. typeExpression = tryParseTypeExpression();
  24217. }
  24218. var result = target === 1 /* Property */ ?
  24219. createNode(322 /* JSDocPropertyTag */, start) :
  24220. createNode(316 /* JSDocParameterTag */, start);
  24221. var comment = parseTagComments(indent + scanner.getStartPos() - start);
  24222. var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
  24223. if (nestedTypeLiteral) {
  24224. typeExpression = nestedTypeLiteral;
  24225. isNameFirst = true;
  24226. }
  24227. result.tagName = tagName;
  24228. result.typeExpression = typeExpression;
  24229. result.name = name;
  24230. result.isNameFirst = isNameFirst;
  24231. result.isBracketed = isBracketed;
  24232. result.comment = comment;
  24233. return finishNode(result);
  24234. }
  24235. function parseNestedTypeLiteral(typeExpression, name, target, indent) {
  24236. if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
  24237. var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
  24238. var child = void 0;
  24239. var jsdocTypeLiteral = void 0;
  24240. var start_3 = scanner.getStartPos();
  24241. var children = void 0;
  24242. while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
  24243. if (child.kind === 316 /* JSDocParameterTag */ || child.kind === 322 /* JSDocPropertyTag */) {
  24244. children = ts.append(children, child);
  24245. }
  24246. }
  24247. if (children) {
  24248. jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
  24249. jsdocTypeLiteral.jsDocPropertyTags = children;
  24250. if (typeExpression.type.kind === 174 /* ArrayType */) {
  24251. jsdocTypeLiteral.isArrayType = true;
  24252. }
  24253. typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
  24254. return finishNode(typeLiteralExpression);
  24255. }
  24256. }
  24257. }
  24258. function parseReturnTag(start, tagName) {
  24259. if (ts.some(tags, ts.isJSDocReturnTag)) {
  24260. parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
  24261. }
  24262. var result = createNode(317 /* JSDocReturnTag */, start);
  24263. result.tagName = tagName;
  24264. result.typeExpression = tryParseTypeExpression();
  24265. return finishNode(result);
  24266. }
  24267. function parseTypeTag(start, tagName) {
  24268. if (ts.some(tags, ts.isJSDocTypeTag)) {
  24269. parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
  24270. }
  24271. var result = createNode(319 /* JSDocTypeTag */, start);
  24272. result.tagName = tagName;
  24273. result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
  24274. return finishNode(result);
  24275. }
  24276. function parseAuthorTag(start, tagName, indent) {
  24277. var result = createNode(308 /* JSDocAuthorTag */, start);
  24278. result.tagName = tagName;
  24279. var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
  24280. if (!authorInfoWithEmail) {
  24281. return finishNode(result);
  24282. }
  24283. result.comment = authorInfoWithEmail;
  24284. if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
  24285. var comment = parseTagComments(indent);
  24286. if (comment) {
  24287. result.comment += comment;
  24288. }
  24289. }
  24290. return finishNode(result);
  24291. }
  24292. function tryParseAuthorNameAndEmail() {
  24293. var comments = [];
  24294. var seenLessThan = false;
  24295. var seenGreaterThan = false;
  24296. var token = scanner.getToken();
  24297. loop: while (true) {
  24298. switch (token) {
  24299. case 75 /* Identifier */:
  24300. case 5 /* WhitespaceTrivia */:
  24301. case 24 /* DotToken */:
  24302. case 59 /* AtToken */:
  24303. comments.push(scanner.getTokenText());
  24304. break;
  24305. case 29 /* LessThanToken */:
  24306. if (seenLessThan || seenGreaterThan) {
  24307. return;
  24308. }
  24309. seenLessThan = true;
  24310. comments.push(scanner.getTokenText());
  24311. break;
  24312. case 31 /* GreaterThanToken */:
  24313. if (!seenLessThan || seenGreaterThan) {
  24314. return;
  24315. }
  24316. seenGreaterThan = true;
  24317. comments.push(scanner.getTokenText());
  24318. scanner.setTextPos(scanner.getTokenPos() + 1);
  24319. break loop;
  24320. case 4 /* NewLineTrivia */:
  24321. case 1 /* EndOfFileToken */:
  24322. break loop;
  24323. }
  24324. token = nextTokenJSDoc();
  24325. }
  24326. if (seenLessThan && seenGreaterThan) {
  24327. return comments.length === 0 ? undefined : comments.join("");
  24328. }
  24329. }
  24330. function parseAugmentsTag(start, tagName) {
  24331. var result = createNode(307 /* JSDocAugmentsTag */, start);
  24332. result.tagName = tagName;
  24333. result.class = parseExpressionWithTypeArgumentsForAugments();
  24334. return finishNode(result);
  24335. }
  24336. function parseExpressionWithTypeArgumentsForAugments() {
  24337. var usedBrace = parseOptional(18 /* OpenBraceToken */);
  24338. var node = createNode(216 /* ExpressionWithTypeArguments */);
  24339. node.expression = parsePropertyAccessEntityNameExpression();
  24340. node.typeArguments = tryParseTypeArguments();
  24341. var res = finishNode(node);
  24342. if (usedBrace) {
  24343. parseExpected(19 /* CloseBraceToken */);
  24344. }
  24345. return res;
  24346. }
  24347. function parsePropertyAccessEntityNameExpression() {
  24348. var node = parseJSDocIdentifierName();
  24349. while (parseOptional(24 /* DotToken */)) {
  24350. var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
  24351. prop.expression = node;
  24352. prop.name = parseJSDocIdentifierName();
  24353. node = finishNode(prop);
  24354. }
  24355. return node;
  24356. }
  24357. function parseSimpleTag(start, kind, tagName) {
  24358. var tag = createNode(kind, start);
  24359. tag.tagName = tagName;
  24360. return finishNode(tag);
  24361. }
  24362. function parseThisTag(start, tagName) {
  24363. var tag = createNode(318 /* JSDocThisTag */, start);
  24364. tag.tagName = tagName;
  24365. tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
  24366. skipWhitespace();
  24367. return finishNode(tag);
  24368. }
  24369. function parseEnumTag(start, tagName) {
  24370. var tag = createNode(315 /* JSDocEnumTag */, start);
  24371. tag.tagName = tagName;
  24372. tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
  24373. skipWhitespace();
  24374. return finishNode(tag);
  24375. }
  24376. function parseTypedefTag(start, tagName, indent) {
  24377. var typeExpression = tryParseTypeExpression();
  24378. skipWhitespaceOrAsterisk();
  24379. var typedefTag = createNode(321 /* JSDocTypedefTag */, start);
  24380. typedefTag.tagName = tagName;
  24381. typedefTag.fullName = parseJSDocTypeNameWithNamespace();
  24382. typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
  24383. skipWhitespace();
  24384. typedefTag.comment = parseTagComments(indent);
  24385. typedefTag.typeExpression = typeExpression;
  24386. var end;
  24387. if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
  24388. var child = void 0;
  24389. var jsdocTypeLiteral = void 0;
  24390. var childTypeTag = void 0;
  24391. while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
  24392. if (!jsdocTypeLiteral) {
  24393. jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
  24394. }
  24395. if (child.kind === 319 /* JSDocTypeTag */) {
  24396. if (childTypeTag) {
  24397. break;
  24398. }
  24399. else {
  24400. childTypeTag = child;
  24401. }
  24402. }
  24403. else {
  24404. jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
  24405. }
  24406. }
  24407. if (jsdocTypeLiteral) {
  24408. if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
  24409. jsdocTypeLiteral.isArrayType = true;
  24410. }
  24411. typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
  24412. childTypeTag.typeExpression :
  24413. finishNode(jsdocTypeLiteral);
  24414. end = typedefTag.typeExpression.end;
  24415. }
  24416. }
  24417. // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
  24418. return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
  24419. }
  24420. function parseJSDocTypeNameWithNamespace(nested) {
  24421. var pos = scanner.getTokenPos();
  24422. if (!ts.tokenIsIdentifierOrKeyword(token())) {
  24423. return undefined;
  24424. }
  24425. var typeNameOrNamespaceName = parseJSDocIdentifierName();
  24426. if (parseOptional(24 /* DotToken */)) {
  24427. var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
  24428. if (nested) {
  24429. jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
  24430. }
  24431. jsDocNamespaceNode.name = typeNameOrNamespaceName;
  24432. jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
  24433. return finishNode(jsDocNamespaceNode);
  24434. }
  24435. if (nested) {
  24436. typeNameOrNamespaceName.isInJSDocNamespace = true;
  24437. }
  24438. return typeNameOrNamespaceName;
  24439. }
  24440. function parseCallbackTag(start, tagName, indent) {
  24441. var callbackTag = createNode(314 /* JSDocCallbackTag */, start);
  24442. callbackTag.tagName = tagName;
  24443. callbackTag.fullName = parseJSDocTypeNameWithNamespace();
  24444. callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
  24445. skipWhitespace();
  24446. callbackTag.comment = parseTagComments(indent);
  24447. var child;
  24448. var jsdocSignature = createNode(305 /* JSDocSignature */, start);
  24449. jsdocSignature.parameters = [];
  24450. while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
  24451. jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
  24452. }
  24453. var returnTag = tryParse(function () {
  24454. if (parseOptionalJsdoc(59 /* AtToken */)) {
  24455. var tag = parseTag(indent);
  24456. if (tag && tag.kind === 317 /* JSDocReturnTag */) {
  24457. return tag;
  24458. }
  24459. }
  24460. });
  24461. if (returnTag) {
  24462. jsdocSignature.type = returnTag;
  24463. }
  24464. callbackTag.typeExpression = finishNode(jsdocSignature);
  24465. return finishNode(callbackTag);
  24466. }
  24467. function getJSDocTypeAliasName(fullName) {
  24468. if (fullName) {
  24469. var rightNode = fullName;
  24470. while (true) {
  24471. if (ts.isIdentifier(rightNode) || !rightNode.body) {
  24472. return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
  24473. }
  24474. rightNode = rightNode.body;
  24475. }
  24476. }
  24477. }
  24478. function escapedTextsEqual(a, b) {
  24479. while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
  24480. if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
  24481. a = a.left;
  24482. b = b.left;
  24483. }
  24484. else {
  24485. return false;
  24486. }
  24487. }
  24488. return a.escapedText === b.escapedText;
  24489. }
  24490. function parseChildPropertyTag(indent) {
  24491. return parseChildParameterOrPropertyTag(1 /* Property */, indent);
  24492. }
  24493. function parseChildParameterOrPropertyTag(target, indent, name) {
  24494. var canParseTag = true;
  24495. var seenAsterisk = false;
  24496. while (true) {
  24497. switch (nextTokenJSDoc()) {
  24498. case 59 /* AtToken */:
  24499. if (canParseTag) {
  24500. var child = tryParseChildTag(target, indent);
  24501. if (child && (child.kind === 316 /* JSDocParameterTag */ || child.kind === 322 /* JSDocPropertyTag */) &&
  24502. target !== 4 /* CallbackParameter */ &&
  24503. name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
  24504. return false;
  24505. }
  24506. return child;
  24507. }
  24508. seenAsterisk = false;
  24509. break;
  24510. case 4 /* NewLineTrivia */:
  24511. canParseTag = true;
  24512. seenAsterisk = false;
  24513. break;
  24514. case 41 /* AsteriskToken */:
  24515. if (seenAsterisk) {
  24516. canParseTag = false;
  24517. }
  24518. seenAsterisk = true;
  24519. break;
  24520. case 75 /* Identifier */:
  24521. canParseTag = false;
  24522. break;
  24523. case 1 /* EndOfFileToken */:
  24524. return false;
  24525. }
  24526. }
  24527. }
  24528. function tryParseChildTag(target, indent) {
  24529. ts.Debug.assert(token() === 59 /* AtToken */);
  24530. var start = scanner.getStartPos();
  24531. nextTokenJSDoc();
  24532. var tagName = parseJSDocIdentifierName();
  24533. skipWhitespace();
  24534. var t;
  24535. switch (tagName.escapedText) {
  24536. case "type":
  24537. return target === 1 /* Property */ && parseTypeTag(start, tagName);
  24538. case "prop":
  24539. case "property":
  24540. t = 1 /* Property */;
  24541. break;
  24542. case "arg":
  24543. case "argument":
  24544. case "param":
  24545. t = 2 /* Parameter */ | 4 /* CallbackParameter */;
  24546. break;
  24547. default:
  24548. return false;
  24549. }
  24550. if (!(target & t)) {
  24551. return false;
  24552. }
  24553. return parseParameterOrPropertyTag(start, tagName, target, indent);
  24554. }
  24555. function parseTemplateTag(start, tagName) {
  24556. // the template tag looks like '@template {Constraint} T,U,V'
  24557. var constraint;
  24558. if (token() === 18 /* OpenBraceToken */) {
  24559. constraint = parseJSDocTypeExpression();
  24560. }
  24561. var typeParameters = [];
  24562. var typeParametersPos = getNodePos();
  24563. do {
  24564. skipWhitespace();
  24565. var typeParameter = createNode(155 /* TypeParameter */);
  24566. typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
  24567. finishNode(typeParameter);
  24568. skipWhitespace();
  24569. typeParameters.push(typeParameter);
  24570. } while (parseOptionalJsdoc(27 /* CommaToken */));
  24571. var result = createNode(320 /* JSDocTemplateTag */, start);
  24572. result.tagName = tagName;
  24573. result.constraint = constraint;
  24574. result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
  24575. finishNode(result);
  24576. return result;
  24577. }
  24578. function parseOptionalJsdoc(t) {
  24579. if (token() === t) {
  24580. nextTokenJSDoc();
  24581. return true;
  24582. }
  24583. return false;
  24584. }
  24585. function parseJSDocEntityName() {
  24586. var entity = parseJSDocIdentifierName();
  24587. if (parseOptional(22 /* OpenBracketToken */)) {
  24588. parseExpected(23 /* CloseBracketToken */);
  24589. // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
  24590. // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
  24591. // but it's not worth it to enforce that restriction.
  24592. }
  24593. while (parseOptional(24 /* DotToken */)) {
  24594. var name = parseJSDocIdentifierName();
  24595. if (parseOptional(22 /* OpenBracketToken */)) {
  24596. parseExpected(23 /* CloseBracketToken */);
  24597. }
  24598. entity = createQualifiedName(entity, name);
  24599. }
  24600. return entity;
  24601. }
  24602. function parseJSDocIdentifierName(message) {
  24603. if (!ts.tokenIsIdentifierOrKeyword(token())) {
  24604. return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
  24605. }
  24606. identifierCount++;
  24607. var pos = scanner.getTokenPos();
  24608. var end = scanner.getTextPos();
  24609. var result = createNode(75 /* Identifier */, pos);
  24610. if (token() !== 75 /* Identifier */) {
  24611. result.originalKeywordKind = token();
  24612. }
  24613. result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
  24614. finishNode(result, end);
  24615. nextTokenJSDoc();
  24616. return result;
  24617. }
  24618. }
  24619. })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
  24620. })(Parser || (Parser = {}));
  24621. var IncrementalParser;
  24622. (function (IncrementalParser) {
  24623. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
  24624. aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
  24625. checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
  24626. if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
  24627. // if the text didn't change, then we can just return our current source file as-is.
  24628. return sourceFile;
  24629. }
  24630. if (sourceFile.statements.length === 0) {
  24631. // If we don't have any statements in the current source file, then there's no real
  24632. // way to incrementally parse. So just do a full parse instead.
  24633. return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
  24634. }
  24635. // Make sure we're not trying to incrementally update a source file more than once. Once
  24636. // we do an update the original source file is considered unusable from that point onwards.
  24637. //
  24638. // This is because we do incremental parsing in-place. i.e. we take nodes from the old
  24639. // tree and give them new positions and parents. From that point on, trusting the old
  24640. // tree at all is not possible as far too much of it may violate invariants.
  24641. var incrementalSourceFile = sourceFile;
  24642. ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
  24643. incrementalSourceFile.hasBeenIncrementallyParsed = true;
  24644. var oldText = sourceFile.text;
  24645. var syntaxCursor = createSyntaxCursor(sourceFile);
  24646. // Make the actual change larger so that we know to reparse anything whose lookahead
  24647. // might have intersected the change.
  24648. var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
  24649. checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
  24650. // Ensure that extending the affected range only moved the start of the change range
  24651. // earlier in the file.
  24652. ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
  24653. ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
  24654. ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
  24655. // The is the amount the nodes after the edit range need to be adjusted. It can be
  24656. // positive (if the edit added characters), negative (if the edit deleted characters)
  24657. // or zero (if this was a pure overwrite with nothing added/removed).
  24658. var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
  24659. // If we added or removed characters during the edit, then we need to go and adjust all
  24660. // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they
  24661. // may move backward (if we deleted chars).
  24662. //
  24663. // Doing this helps us out in two ways. First, it means that any nodes/tokens we want
  24664. // to reuse are already at the appropriate position in the new text. That way when we
  24665. // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes
  24666. // it very easy to determine if we can reuse a node. If the node's position is at where
  24667. // we are in the text, then we can reuse it. Otherwise we can't. If the node's position
  24668. // is ahead of us, then we'll need to rescan tokens. If the node's position is behind
  24669. // us, then we'll need to skip it or crumble it as appropriate
  24670. //
  24671. // We will also adjust the positions of nodes that intersect the change range as well.
  24672. // By doing this, we ensure that all the positions in the old tree are consistent, not
  24673. // just the positions of nodes entirely before/after the change range. By being
  24674. // consistent, we can then easily map from positions to nodes in the old tree easily.
  24675. //
  24676. // Also, mark any syntax elements that intersect the changed span. We know, up front,
  24677. // that we cannot reuse these elements.
  24678. updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
  24679. // Now that we've set up our internal incremental state just proceed and parse the
  24680. // source file in the normal fashion. When possible the parser will retrieve and
  24681. // reuse nodes from the old tree.
  24682. //
  24683. // Note: passing in 'true' for setNodeParents is very important. When incrementally
  24684. // parsing, we will be reusing nodes from the old tree, and placing it into new
  24685. // parents. If we don't set the parents now, we'll end up with an observably
  24686. // inconsistent tree. Setting the parents on the new tree should be very fast. We
  24687. // will immediately bail out of walking any subtrees when we can see that their parents
  24688. // are already correct.
  24689. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
  24690. return result;
  24691. }
  24692. IncrementalParser.updateSourceFile = updateSourceFile;
  24693. function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
  24694. if (isArray) {
  24695. visitArray(element);
  24696. }
  24697. else {
  24698. visitNode(element);
  24699. }
  24700. return;
  24701. function visitNode(node) {
  24702. var text = "";
  24703. if (aggressiveChecks && shouldCheckNode(node)) {
  24704. text = oldText.substring(node.pos, node.end);
  24705. }
  24706. // Ditch any existing LS children we may have created. This way we can avoid
  24707. // moving them forward.
  24708. if (node._children) {
  24709. node._children = undefined;
  24710. }
  24711. node.pos += delta;
  24712. node.end += delta;
  24713. if (aggressiveChecks && shouldCheckNode(node)) {
  24714. ts.Debug.assert(text === newText.substring(node.pos, node.end));
  24715. }
  24716. forEachChild(node, visitNode, visitArray);
  24717. if (ts.hasJSDocNodes(node)) {
  24718. for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
  24719. var jsDocComment = _a[_i];
  24720. visitNode(jsDocComment);
  24721. }
  24722. }
  24723. checkNodePositions(node, aggressiveChecks);
  24724. }
  24725. function visitArray(array) {
  24726. array._children = undefined;
  24727. array.pos += delta;
  24728. array.end += delta;
  24729. for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
  24730. var node = array_8[_i];
  24731. visitNode(node);
  24732. }
  24733. }
  24734. }
  24735. function shouldCheckNode(node) {
  24736. switch (node.kind) {
  24737. case 10 /* StringLiteral */:
  24738. case 8 /* NumericLiteral */:
  24739. case 75 /* Identifier */:
  24740. return true;
  24741. }
  24742. return false;
  24743. }
  24744. function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
  24745. ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
  24746. ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
  24747. ts.Debug.assert(element.pos <= element.end);
  24748. // We have an element that intersects the change range in some way. It may have its
  24749. // start, or its end (or both) in the changed range. We want to adjust any part
  24750. // that intersects such that the final tree is in a consistent state. i.e. all
  24751. // children have spans within the span of their parent, and all siblings are ordered
  24752. // properly.
  24753. // We may need to update both the 'pos' and the 'end' of the element.
  24754. // If the 'pos' is before the start of the change, then we don't need to touch it.
  24755. // If it isn't, then the 'pos' must be inside the change. How we update it will
  24756. // depend if delta is positive or negative. If delta is positive then we have
  24757. // something like:
  24758. //
  24759. // -------------------AAA-----------------
  24760. // -------------------BBBCCCCCCC-----------------
  24761. //
  24762. // In this case, we consider any node that started in the change range to still be
  24763. // starting at the same position.
  24764. //
  24765. // however, if the delta is negative, then we instead have something like this:
  24766. //
  24767. // -------------------XXXYYYYYYY-----------------
  24768. // -------------------ZZZ-----------------
  24769. //
  24770. // In this case, any element that started in the 'X' range will keep its position.
  24771. // However any element that started after that will have their pos adjusted to be
  24772. // at the end of the new range. i.e. any node that started in the 'Y' range will
  24773. // be adjusted to have their start at the end of the 'Z' range.
  24774. //
  24775. // The element will keep its position if possible. Or Move backward to the new-end
  24776. // if it's in the 'Y' range.
  24777. element.pos = Math.min(element.pos, changeRangeNewEnd);
  24778. // If the 'end' is after the change range, then we always adjust it by the delta
  24779. // amount. However, if the end is in the change range, then how we adjust it
  24780. // will depend on if delta is positive or negative. If delta is positive then we
  24781. // have something like:
  24782. //
  24783. // -------------------AAA-----------------
  24784. // -------------------BBBCCCCCCC-----------------
  24785. //
  24786. // In this case, we consider any node that ended inside the change range to keep its
  24787. // end position.
  24788. //
  24789. // however, if the delta is negative, then we instead have something like this:
  24790. //
  24791. // -------------------XXXYYYYYYY-----------------
  24792. // -------------------ZZZ-----------------
  24793. //
  24794. // In this case, any element that ended in the 'X' range will keep its position.
  24795. // However any element that ended after that will have their pos adjusted to be
  24796. // at the end of the new range. i.e. any node that ended in the 'Y' range will
  24797. // be adjusted to have their end at the end of the 'Z' range.
  24798. if (element.end >= changeRangeOldEnd) {
  24799. // Element ends after the change range. Always adjust the end pos.
  24800. element.end += delta;
  24801. }
  24802. else {
  24803. // Element ends in the change range. The element will keep its position if
  24804. // possible. Or Move backward to the new-end if it's in the 'Y' range.
  24805. element.end = Math.min(element.end, changeRangeNewEnd);
  24806. }
  24807. ts.Debug.assert(element.pos <= element.end);
  24808. if (element.parent) {
  24809. ts.Debug.assert(element.pos >= element.parent.pos);
  24810. ts.Debug.assert(element.end <= element.parent.end);
  24811. }
  24812. }
  24813. function checkNodePositions(node, aggressiveChecks) {
  24814. if (aggressiveChecks) {
  24815. var pos_2 = node.pos;
  24816. var visitNode_1 = function (child) {
  24817. ts.Debug.assert(child.pos >= pos_2);
  24818. pos_2 = child.end;
  24819. };
  24820. if (ts.hasJSDocNodes(node)) {
  24821. for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
  24822. var jsDocComment = _a[_i];
  24823. visitNode_1(jsDocComment);
  24824. }
  24825. }
  24826. forEachChild(node, visitNode_1);
  24827. ts.Debug.assert(pos_2 <= node.end);
  24828. }
  24829. }
  24830. function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
  24831. visitNode(sourceFile);
  24832. return;
  24833. function visitNode(child) {
  24834. ts.Debug.assert(child.pos <= child.end);
  24835. if (child.pos > changeRangeOldEnd) {
  24836. // Node is entirely past the change range. We need to move both its pos and
  24837. // end, forward or backward appropriately.
  24838. moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
  24839. return;
  24840. }
  24841. // Check if the element intersects the change range. If it does, then it is not
  24842. // reusable. Also, we'll need to recurse to see what constituent portions we may
  24843. // be able to use.
  24844. var fullEnd = child.end;
  24845. if (fullEnd >= changeStart) {
  24846. child.intersectsChange = true;
  24847. child._children = undefined;
  24848. // Adjust the pos or end (or both) of the intersecting element accordingly.
  24849. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
  24850. forEachChild(child, visitNode, visitArray);
  24851. if (ts.hasJSDocNodes(child)) {
  24852. for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
  24853. var jsDocComment = _a[_i];
  24854. visitNode(jsDocComment);
  24855. }
  24856. }
  24857. checkNodePositions(child, aggressiveChecks);
  24858. return;
  24859. }
  24860. // Otherwise, the node is entirely before the change range. No need to do anything with it.
  24861. ts.Debug.assert(fullEnd < changeStart);
  24862. }
  24863. function visitArray(array) {
  24864. ts.Debug.assert(array.pos <= array.end);
  24865. if (array.pos > changeRangeOldEnd) {
  24866. // Array is entirely after the change range. We need to move it, and move any of
  24867. // its children.
  24868. moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
  24869. return;
  24870. }
  24871. // Check if the element intersects the change range. If it does, then it is not
  24872. // reusable. Also, we'll need to recurse to see what constituent portions we may
  24873. // be able to use.
  24874. var fullEnd = array.end;
  24875. if (fullEnd >= changeStart) {
  24876. array.intersectsChange = true;
  24877. array._children = undefined;
  24878. // Adjust the pos or end (or both) of the intersecting array accordingly.
  24879. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
  24880. for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
  24881. var node = array_9[_i];
  24882. visitNode(node);
  24883. }
  24884. return;
  24885. }
  24886. // Otherwise, the array is entirely before the change range. No need to do anything with it.
  24887. ts.Debug.assert(fullEnd < changeStart);
  24888. }
  24889. }
  24890. function extendToAffectedRange(sourceFile, changeRange) {
  24891. // Consider the following code:
  24892. // void foo() { /; }
  24893. //
  24894. // If the text changes with an insertion of / just before the semicolon then we end up with:
  24895. // void foo() { //; }
  24896. //
  24897. // If we were to just use the changeRange a is, then we would not rescan the { token
  24898. // (as it does not intersect the actual original change range). Because an edit may
  24899. // change the token touching it, we actually need to look back *at least* one token so
  24900. // that the prior token sees that change.
  24901. var maxLookahead = 1;
  24902. var start = changeRange.span.start;
  24903. // the first iteration aligns us with the change start. subsequent iteration move us to
  24904. // the left by maxLookahead tokens. We only need to do this as long as we're not at the
  24905. // start of the tree.
  24906. for (var i = 0; start > 0 && i <= maxLookahead; i++) {
  24907. var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
  24908. ts.Debug.assert(nearestNode.pos <= start);
  24909. var position = nearestNode.pos;
  24910. start = Math.max(0, position - 1);
  24911. }
  24912. var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
  24913. var finalLength = changeRange.newLength + (changeRange.span.start - start);
  24914. return ts.createTextChangeRange(finalSpan, finalLength);
  24915. }
  24916. function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
  24917. var bestResult = sourceFile;
  24918. var lastNodeEntirelyBeforePosition;
  24919. forEachChild(sourceFile, visit);
  24920. if (lastNodeEntirelyBeforePosition) {
  24921. var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
  24922. if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
  24923. bestResult = lastChildOfLastEntireNodeBeforePosition;
  24924. }
  24925. }
  24926. return bestResult;
  24927. function getLastDescendant(node) {
  24928. while (true) {
  24929. var lastChild = ts.getLastChild(node);
  24930. if (lastChild) {
  24931. node = lastChild;
  24932. }
  24933. else {
  24934. return node;
  24935. }
  24936. }
  24937. }
  24938. function visit(child) {
  24939. if (ts.nodeIsMissing(child)) {
  24940. // Missing nodes are effectively invisible to us. We never even consider them
  24941. // When trying to find the nearest node before us.
  24942. return;
  24943. }
  24944. // If the child intersects this position, then this node is currently the nearest
  24945. // node that starts before the position.
  24946. if (child.pos <= position) {
  24947. if (child.pos >= bestResult.pos) {
  24948. // This node starts before the position, and is closer to the position than
  24949. // the previous best node we found. It is now the new best node.
  24950. bestResult = child;
  24951. }
  24952. // Now, the node may overlap the position, or it may end entirely before the
  24953. // position. If it overlaps with the position, then either it, or one of its
  24954. // children must be the nearest node before the position. So we can just
  24955. // recurse into this child to see if we can find something better.
  24956. if (position < child.end) {
  24957. // The nearest node is either this child, or one of the children inside
  24958. // of it. We've already marked this child as the best so far. Recurse
  24959. // in case one of the children is better.
  24960. forEachChild(child, visit);
  24961. // Once we look at the children of this node, then there's no need to
  24962. // continue any further.
  24963. return true;
  24964. }
  24965. else {
  24966. ts.Debug.assert(child.end <= position);
  24967. // The child ends entirely before this position. Say you have the following
  24968. // (where $ is the position)
  24969. //
  24970. // <complex expr 1> ? <complex expr 2> $ : <...> <...>
  24971. //
  24972. // We would want to find the nearest preceding node in "complex expr 2".
  24973. // To support that, we keep track of this node, and once we're done searching
  24974. // for a best node, we recurse down this node to see if we can find a good
  24975. // result in it.
  24976. //
  24977. // This approach allows us to quickly skip over nodes that are entirely
  24978. // before the position, while still allowing us to find any nodes in the
  24979. // last one that might be what we want.
  24980. lastNodeEntirelyBeforePosition = child;
  24981. }
  24982. }
  24983. else {
  24984. ts.Debug.assert(child.pos > position);
  24985. // We're now at a node that is entirely past the position we're searching for.
  24986. // This node (and all following nodes) could never contribute to the result,
  24987. // so just skip them by returning 'true' here.
  24988. return true;
  24989. }
  24990. }
  24991. }
  24992. function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
  24993. var oldText = sourceFile.text;
  24994. if (textChangeRange) {
  24995. ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
  24996. if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
  24997. var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
  24998. var newTextPrefix = newText.substr(0, textChangeRange.span.start);
  24999. ts.Debug.assert(oldTextPrefix === newTextPrefix);
  25000. var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
  25001. var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
  25002. ts.Debug.assert(oldTextSuffix === newTextSuffix);
  25003. }
  25004. }
  25005. }
  25006. function createSyntaxCursor(sourceFile) {
  25007. var currentArray = sourceFile.statements;
  25008. var currentArrayIndex = 0;
  25009. ts.Debug.assert(currentArrayIndex < currentArray.length);
  25010. var current = currentArray[currentArrayIndex];
  25011. var lastQueriedPosition = -1 /* Value */;
  25012. return {
  25013. currentNode: function (position) {
  25014. // Only compute the current node if the position is different than the last time
  25015. // we were asked. The parser commonly asks for the node at the same position
  25016. // twice. Once to know if can read an appropriate list element at a certain point,
  25017. // and then to actually read and consume the node.
  25018. if (position !== lastQueriedPosition) {
  25019. // Much of the time the parser will need the very next node in the array that
  25020. // we just returned a node from.So just simply check for that case and move
  25021. // forward in the array instead of searching for the node again.
  25022. if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
  25023. currentArrayIndex++;
  25024. current = currentArray[currentArrayIndex];
  25025. }
  25026. // If we don't have a node, or the node we have isn't in the right position,
  25027. // then try to find a viable node at the position requested.
  25028. if (!current || current.pos !== position) {
  25029. findHighestListElementThatStartsAtPosition(position);
  25030. }
  25031. }
  25032. // Cache this query so that we don't do any extra work if the parser calls back
  25033. // into us. Note: this is very common as the parser will make pairs of calls like
  25034. // 'isListElement -> parseListElement'. If we were unable to find a node when
  25035. // called with 'isListElement', we don't want to redo the work when parseListElement
  25036. // is called immediately after.
  25037. lastQueriedPosition = position;
  25038. // Either we don'd have a node, or we have a node at the position being asked for.
  25039. ts.Debug.assert(!current || current.pos === position);
  25040. return current;
  25041. }
  25042. };
  25043. // Finds the highest element in the tree we can find that starts at the provided position.
  25044. // The element must be a direct child of some node list in the tree. This way after we
  25045. // return it, we can easily return its next sibling in the list.
  25046. function findHighestListElementThatStartsAtPosition(position) {
  25047. // Clear out any cached state about the last node we found.
  25048. currentArray = undefined;
  25049. currentArrayIndex = -1 /* Value */;
  25050. current = undefined;
  25051. // Recurse into the source file to find the highest node at this position.
  25052. forEachChild(sourceFile, visitNode, visitArray);
  25053. return;
  25054. function visitNode(node) {
  25055. if (position >= node.pos && position < node.end) {
  25056. // Position was within this node. Keep searching deeper to find the node.
  25057. forEachChild(node, visitNode, visitArray);
  25058. // don't proceed any further in the search.
  25059. return true;
  25060. }
  25061. // position wasn't in this node, have to keep searching.
  25062. return false;
  25063. }
  25064. function visitArray(array) {
  25065. if (position >= array.pos && position < array.end) {
  25066. // position was in this array. Search through this array to see if we find a
  25067. // viable element.
  25068. for (var i = 0; i < array.length; i++) {
  25069. var child = array[i];
  25070. if (child) {
  25071. if (child.pos === position) {
  25072. // Found the right node. We're done.
  25073. currentArray = array;
  25074. currentArrayIndex = i;
  25075. current = child;
  25076. return true;
  25077. }
  25078. else {
  25079. if (child.pos < position && position < child.end) {
  25080. // Position in somewhere within this child. Search in it and
  25081. // stop searching in this array.
  25082. forEachChild(child, visitNode, visitArray);
  25083. return true;
  25084. }
  25085. }
  25086. }
  25087. }
  25088. }
  25089. // position wasn't in this array, have to keep searching.
  25090. return false;
  25091. }
  25092. }
  25093. }
  25094. var InvalidPosition;
  25095. (function (InvalidPosition) {
  25096. InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
  25097. })(InvalidPosition || (InvalidPosition = {}));
  25098. })(IncrementalParser || (IncrementalParser = {}));
  25099. /** @internal */
  25100. function isDeclarationFileName(fileName) {
  25101. return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
  25102. }
  25103. ts.isDeclarationFileName = isDeclarationFileName;
  25104. /*@internal*/
  25105. function processCommentPragmas(context, sourceText) {
  25106. var pragmas = [];
  25107. for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
  25108. var range = _a[_i];
  25109. var comment = sourceText.substring(range.pos, range.end);
  25110. extractPragmas(pragmas, range, comment);
  25111. }
  25112. context.pragmas = ts.createMap();
  25113. for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
  25114. var pragma = pragmas_1[_b];
  25115. if (context.pragmas.has(pragma.name)) {
  25116. var currentValue = context.pragmas.get(pragma.name);
  25117. if (currentValue instanceof Array) {
  25118. currentValue.push(pragma.args);
  25119. }
  25120. else {
  25121. context.pragmas.set(pragma.name, [currentValue, pragma.args]);
  25122. }
  25123. continue;
  25124. }
  25125. context.pragmas.set(pragma.name, pragma.args);
  25126. }
  25127. }
  25128. ts.processCommentPragmas = processCommentPragmas;
  25129. /*@internal*/
  25130. function processPragmasIntoFields(context, reportDiagnostic) {
  25131. context.checkJsDirective = undefined;
  25132. context.referencedFiles = [];
  25133. context.typeReferenceDirectives = [];
  25134. context.libReferenceDirectives = [];
  25135. context.amdDependencies = [];
  25136. context.hasNoDefaultLib = false;
  25137. context.pragmas.forEach(function (entryOrList, key) {
  25138. // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
  25139. // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
  25140. switch (key) {
  25141. case "reference": {
  25142. var referencedFiles_1 = context.referencedFiles;
  25143. var typeReferenceDirectives_1 = context.typeReferenceDirectives;
  25144. var libReferenceDirectives_1 = context.libReferenceDirectives;
  25145. ts.forEach(ts.toArray(entryOrList), function (arg) {
  25146. var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
  25147. if (arg.arguments["no-default-lib"]) {
  25148. context.hasNoDefaultLib = true;
  25149. }
  25150. else if (types) {
  25151. typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
  25152. }
  25153. else if (lib) {
  25154. libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
  25155. }
  25156. else if (path) {
  25157. referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
  25158. }
  25159. else {
  25160. reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
  25161. }
  25162. });
  25163. break;
  25164. }
  25165. case "amd-dependency": {
  25166. context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
  25167. break;
  25168. }
  25169. case "amd-module": {
  25170. if (entryOrList instanceof Array) {
  25171. for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
  25172. var entry = entryOrList_1[_i];
  25173. if (context.moduleName) {
  25174. // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
  25175. reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
  25176. }
  25177. context.moduleName = entry.arguments.name;
  25178. }
  25179. }
  25180. else {
  25181. context.moduleName = entryOrList.arguments.name;
  25182. }
  25183. break;
  25184. }
  25185. case "ts-nocheck":
  25186. case "ts-check": {
  25187. // _last_ of either nocheck or check in a file is the "winner"
  25188. ts.forEach(ts.toArray(entryOrList), function (entry) {
  25189. if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
  25190. context.checkJsDirective = {
  25191. enabled: key === "ts-check",
  25192. end: entry.range.end,
  25193. pos: entry.range.pos
  25194. };
  25195. }
  25196. });
  25197. break;
  25198. }
  25199. case "jsx": return; // Accessed directly
  25200. default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
  25201. }
  25202. });
  25203. }
  25204. ts.processPragmasIntoFields = processPragmasIntoFields;
  25205. var namedArgRegExCache = ts.createMap();
  25206. function getNamedArgRegEx(name) {
  25207. if (namedArgRegExCache.has(name)) {
  25208. return namedArgRegExCache.get(name);
  25209. }
  25210. var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
  25211. namedArgRegExCache.set(name, result);
  25212. return result;
  25213. }
  25214. var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
  25215. var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
  25216. function extractPragmas(pragmas, range, text) {
  25217. var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
  25218. if (tripleSlash) {
  25219. var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
  25220. var pragma = ts.commentPragmas[name];
  25221. if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
  25222. return;
  25223. }
  25224. if (pragma.args) {
  25225. var argument = {};
  25226. for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
  25227. var arg = _a[_i];
  25228. var matcher = getNamedArgRegEx(arg.name);
  25229. var matchResult = matcher.exec(text);
  25230. if (!matchResult && !arg.optional) {
  25231. return; // Missing required argument, don't parse
  25232. }
  25233. else if (matchResult) {
  25234. if (arg.captureSpan) {
  25235. var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
  25236. argument[arg.name] = {
  25237. value: matchResult[3],
  25238. pos: startPos,
  25239. end: startPos + matchResult[3].length
  25240. };
  25241. }
  25242. else {
  25243. argument[arg.name] = matchResult[3];
  25244. }
  25245. }
  25246. }
  25247. pragmas.push({ name: name, args: { arguments: argument, range: range } });
  25248. }
  25249. else {
  25250. pragmas.push({ name: name, args: { arguments: {}, range: range } });
  25251. }
  25252. return;
  25253. }
  25254. var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
  25255. if (singleLine) {
  25256. return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
  25257. }
  25258. if (range.kind === 3 /* MultiLineCommentTrivia */) {
  25259. var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
  25260. var multiLineMatch = void 0;
  25261. while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
  25262. addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
  25263. }
  25264. }
  25265. }
  25266. function addPragmaForMatch(pragmas, range, kind, match) {
  25267. if (!match)
  25268. return;
  25269. var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
  25270. var pragma = ts.commentPragmas[name];
  25271. if (!pragma || !(pragma.kind & kind)) {
  25272. return;
  25273. }
  25274. var args = match[2]; // Split on spaces and match up positionally with definition
  25275. var argument = getNamedPragmaArguments(pragma, args);
  25276. if (argument === "fail")
  25277. return; // Missing required argument, fail to parse it
  25278. pragmas.push({ name: name, args: { arguments: argument, range: range } });
  25279. return;
  25280. }
  25281. function getNamedPragmaArguments(pragma, text) {
  25282. if (!text)
  25283. return {};
  25284. if (!pragma.args)
  25285. return {};
  25286. var args = text.split(/\s+/);
  25287. var argMap = {};
  25288. for (var i = 0; i < pragma.args.length; i++) {
  25289. var argument = pragma.args[i];
  25290. if (!args[i] && !argument.optional) {
  25291. return "fail";
  25292. }
  25293. if (argument.captureSpan) {
  25294. return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
  25295. }
  25296. argMap[argument.name] = args[i];
  25297. }
  25298. return argMap;
  25299. }
  25300. /** @internal */
  25301. function tagNamesAreEquivalent(lhs, rhs) {
  25302. if (lhs.kind !== rhs.kind) {
  25303. return false;
  25304. }
  25305. if (lhs.kind === 75 /* Identifier */) {
  25306. return lhs.escapedText === rhs.escapedText;
  25307. }
  25308. if (lhs.kind === 104 /* ThisKeyword */) {
  25309. return true;
  25310. }
  25311. // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
  25312. // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
  25313. // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
  25314. return lhs.name.escapedText === rhs.name.escapedText &&
  25315. tagNamesAreEquivalent(lhs.expression, rhs.expression);
  25316. }
  25317. ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
  25318. })(ts || (ts = {}));
  25319. var ts;
  25320. (function (ts) {
  25321. /* @internal */
  25322. ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
  25323. // NOTE: The order here is important to default lib ordering as entries will have the same
  25324. // order in the generated program (see `getDefaultLibPriority` in program.ts). This
  25325. // order also affects overload resolution when a type declared in one lib is
  25326. // augmented in another lib.
  25327. var libEntries = [
  25328. // JavaScript only
  25329. ["es5", "lib.es5.d.ts"],
  25330. ["es6", "lib.es2015.d.ts"],
  25331. ["es2015", "lib.es2015.d.ts"],
  25332. ["es7", "lib.es2016.d.ts"],
  25333. ["es2016", "lib.es2016.d.ts"],
  25334. ["es2017", "lib.es2017.d.ts"],
  25335. ["es2018", "lib.es2018.d.ts"],
  25336. ["es2019", "lib.es2019.d.ts"],
  25337. ["es2020", "lib.es2020.d.ts"],
  25338. ["esnext", "lib.esnext.d.ts"],
  25339. // Host only
  25340. ["dom", "lib.dom.d.ts"],
  25341. ["dom.iterable", "lib.dom.iterable.d.ts"],
  25342. ["webworker", "lib.webworker.d.ts"],
  25343. ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
  25344. ["scripthost", "lib.scripthost.d.ts"],
  25345. // ES2015 Or ESNext By-feature options
  25346. ["es2015.core", "lib.es2015.core.d.ts"],
  25347. ["es2015.collection", "lib.es2015.collection.d.ts"],
  25348. ["es2015.generator", "lib.es2015.generator.d.ts"],
  25349. ["es2015.iterable", "lib.es2015.iterable.d.ts"],
  25350. ["es2015.promise", "lib.es2015.promise.d.ts"],
  25351. ["es2015.proxy", "lib.es2015.proxy.d.ts"],
  25352. ["es2015.reflect", "lib.es2015.reflect.d.ts"],
  25353. ["es2015.symbol", "lib.es2015.symbol.d.ts"],
  25354. ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
  25355. ["es2016.array.include", "lib.es2016.array.include.d.ts"],
  25356. ["es2017.object", "lib.es2017.object.d.ts"],
  25357. ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
  25358. ["es2017.string", "lib.es2017.string.d.ts"],
  25359. ["es2017.intl", "lib.es2017.intl.d.ts"],
  25360. ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
  25361. ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
  25362. ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
  25363. ["es2018.intl", "lib.es2018.intl.d.ts"],
  25364. ["es2018.promise", "lib.es2018.promise.d.ts"],
  25365. ["es2018.regexp", "lib.es2018.regexp.d.ts"],
  25366. ["es2019.array", "lib.es2019.array.d.ts"],
  25367. ["es2019.object", "lib.es2019.object.d.ts"],
  25368. ["es2019.string", "lib.es2019.string.d.ts"],
  25369. ["es2019.symbol", "lib.es2019.symbol.d.ts"],
  25370. ["es2020.bigint", "lib.es2020.bigint.d.ts"],
  25371. ["es2020.promise", "lib.es2020.promise.d.ts"],
  25372. ["es2020.string", "lib.es2020.string.d.ts"],
  25373. ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
  25374. ["esnext.array", "lib.es2019.array.d.ts"],
  25375. ["esnext.symbol", "lib.es2019.symbol.d.ts"],
  25376. ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
  25377. ["esnext.intl", "lib.esnext.intl.d.ts"],
  25378. ["esnext.bigint", "lib.es2020.bigint.d.ts"]
  25379. ];
  25380. /**
  25381. * An array of supported "lib" reference file names used to determine the order for inclusion
  25382. * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
  25383. * overload resolution when a type declared in one lib is extended by another.
  25384. */
  25385. /* @internal */
  25386. ts.libs = libEntries.map(function (entry) { return entry[0]; });
  25387. /**
  25388. * A map of lib names to lib files. This map is used both for parsing the "lib" command line
  25389. * option as well as for resolving lib reference directives.
  25390. */
  25391. /* @internal */
  25392. ts.libMap = ts.createMapFromEntries(libEntries);
  25393. // Watch related options
  25394. /* @internal */
  25395. ts.optionsForWatch = [
  25396. {
  25397. name: "watchFile",
  25398. type: ts.createMapFromTemplate({
  25399. fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
  25400. prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
  25401. dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
  25402. usefsevents: ts.WatchFileKind.UseFsEvents,
  25403. usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
  25404. }),
  25405. category: ts.Diagnostics.Advanced_Options,
  25406. description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
  25407. },
  25408. {
  25409. name: "watchDirectory",
  25410. type: ts.createMapFromTemplate({
  25411. usefsevents: ts.WatchDirectoryKind.UseFsEvents,
  25412. fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
  25413. dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
  25414. }),
  25415. category: ts.Diagnostics.Advanced_Options,
  25416. description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
  25417. },
  25418. {
  25419. name: "fallbackPolling",
  25420. type: ts.createMapFromTemplate({
  25421. fixedinterval: ts.PollingWatchKind.FixedInterval,
  25422. priorityinterval: ts.PollingWatchKind.PriorityInterval,
  25423. dynamicpriority: ts.PollingWatchKind.DynamicPriority,
  25424. }),
  25425. category: ts.Diagnostics.Advanced_Options,
  25426. description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
  25427. },
  25428. {
  25429. name: "synchronousWatchDirectory",
  25430. type: "boolean",
  25431. category: ts.Diagnostics.Advanced_Options,
  25432. description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
  25433. },
  25434. ];
  25435. /* @internal */
  25436. ts.commonOptionsWithBuild = [
  25437. {
  25438. name: "help",
  25439. shortName: "h",
  25440. type: "boolean",
  25441. showInSimplifiedHelpView: true,
  25442. category: ts.Diagnostics.Command_line_Options,
  25443. description: ts.Diagnostics.Print_this_message,
  25444. },
  25445. {
  25446. name: "help",
  25447. shortName: "?",
  25448. type: "boolean"
  25449. },
  25450. {
  25451. name: "watch",
  25452. shortName: "w",
  25453. type: "boolean",
  25454. showInSimplifiedHelpView: true,
  25455. category: ts.Diagnostics.Command_line_Options,
  25456. description: ts.Diagnostics.Watch_input_files,
  25457. },
  25458. {
  25459. name: "preserveWatchOutput",
  25460. type: "boolean",
  25461. showInSimplifiedHelpView: false,
  25462. category: ts.Diagnostics.Command_line_Options,
  25463. description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
  25464. },
  25465. {
  25466. name: "listFiles",
  25467. type: "boolean",
  25468. category: ts.Diagnostics.Advanced_Options,
  25469. description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
  25470. },
  25471. {
  25472. name: "listEmittedFiles",
  25473. type: "boolean",
  25474. category: ts.Diagnostics.Advanced_Options,
  25475. description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
  25476. },
  25477. {
  25478. name: "pretty",
  25479. type: "boolean",
  25480. showInSimplifiedHelpView: true,
  25481. category: ts.Diagnostics.Command_line_Options,
  25482. description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
  25483. },
  25484. {
  25485. name: "traceResolution",
  25486. type: "boolean",
  25487. category: ts.Diagnostics.Advanced_Options,
  25488. description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
  25489. },
  25490. {
  25491. name: "diagnostics",
  25492. type: "boolean",
  25493. category: ts.Diagnostics.Advanced_Options,
  25494. description: ts.Diagnostics.Show_diagnostic_information
  25495. },
  25496. {
  25497. name: "extendedDiagnostics",
  25498. type: "boolean",
  25499. category: ts.Diagnostics.Advanced_Options,
  25500. description: ts.Diagnostics.Show_verbose_diagnostic_information
  25501. },
  25502. {
  25503. name: "generateCpuProfile",
  25504. type: "string",
  25505. isFilePath: true,
  25506. paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
  25507. category: ts.Diagnostics.Advanced_Options,
  25508. description: ts.Diagnostics.Generates_a_CPU_profile
  25509. },
  25510. {
  25511. name: "incremental",
  25512. shortName: "i",
  25513. type: "boolean",
  25514. category: ts.Diagnostics.Basic_Options,
  25515. description: ts.Diagnostics.Enable_incremental_compilation,
  25516. transpileOptionValue: undefined
  25517. },
  25518. {
  25519. name: "assumeChangesOnlyAffectDirectDependencies",
  25520. type: "boolean",
  25521. affectsSemanticDiagnostics: true,
  25522. affectsEmit: true,
  25523. category: ts.Diagnostics.Advanced_Options,
  25524. description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
  25525. },
  25526. {
  25527. name: "locale",
  25528. type: "string",
  25529. category: ts.Diagnostics.Advanced_Options,
  25530. description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
  25531. },
  25532. ];
  25533. /* @internal */
  25534. ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
  25535. {
  25536. name: "all",
  25537. type: "boolean",
  25538. showInSimplifiedHelpView: true,
  25539. category: ts.Diagnostics.Command_line_Options,
  25540. description: ts.Diagnostics.Show_all_compiler_options,
  25541. },
  25542. {
  25543. name: "version",
  25544. shortName: "v",
  25545. type: "boolean",
  25546. showInSimplifiedHelpView: true,
  25547. category: ts.Diagnostics.Command_line_Options,
  25548. description: ts.Diagnostics.Print_the_compiler_s_version,
  25549. },
  25550. {
  25551. name: "init",
  25552. type: "boolean",
  25553. showInSimplifiedHelpView: true,
  25554. category: ts.Diagnostics.Command_line_Options,
  25555. description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
  25556. },
  25557. {
  25558. name: "project",
  25559. shortName: "p",
  25560. type: "string",
  25561. isFilePath: true,
  25562. showInSimplifiedHelpView: true,
  25563. category: ts.Diagnostics.Command_line_Options,
  25564. paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
  25565. description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
  25566. },
  25567. {
  25568. name: "build",
  25569. type: "boolean",
  25570. shortName: "b",
  25571. showInSimplifiedHelpView: true,
  25572. category: ts.Diagnostics.Command_line_Options,
  25573. description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
  25574. },
  25575. {
  25576. name: "showConfig",
  25577. type: "boolean",
  25578. category: ts.Diagnostics.Command_line_Options,
  25579. isCommandLineOnly: true,
  25580. description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
  25581. },
  25582. {
  25583. name: "listFilesOnly",
  25584. type: "boolean",
  25585. category: ts.Diagnostics.Command_line_Options,
  25586. affectsSemanticDiagnostics: true,
  25587. affectsEmit: true,
  25588. isCommandLineOnly: true,
  25589. description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
  25590. },
  25591. // Basic
  25592. {
  25593. name: "target",
  25594. shortName: "t",
  25595. type: ts.createMapFromTemplate({
  25596. es3: 0 /* ES3 */,
  25597. es5: 1 /* ES5 */,
  25598. es6: 2 /* ES2015 */,
  25599. es2015: 2 /* ES2015 */,
  25600. es2016: 3 /* ES2016 */,
  25601. es2017: 4 /* ES2017 */,
  25602. es2018: 5 /* ES2018 */,
  25603. es2019: 6 /* ES2019 */,
  25604. es2020: 7 /* ES2020 */,
  25605. esnext: 99 /* ESNext */,
  25606. }),
  25607. affectsSourceFile: true,
  25608. affectsModuleResolution: true,
  25609. affectsEmit: true,
  25610. paramType: ts.Diagnostics.VERSION,
  25611. showInSimplifiedHelpView: true,
  25612. category: ts.Diagnostics.Basic_Options,
  25613. description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
  25614. },
  25615. {
  25616. name: "module",
  25617. shortName: "m",
  25618. type: ts.createMapFromTemplate({
  25619. none: ts.ModuleKind.None,
  25620. commonjs: ts.ModuleKind.CommonJS,
  25621. amd: ts.ModuleKind.AMD,
  25622. system: ts.ModuleKind.System,
  25623. umd: ts.ModuleKind.UMD,
  25624. es6: ts.ModuleKind.ES2015,
  25625. es2015: ts.ModuleKind.ES2015,
  25626. es2020: ts.ModuleKind.ES2020,
  25627. esnext: ts.ModuleKind.ESNext
  25628. }),
  25629. affectsModuleResolution: true,
  25630. affectsEmit: true,
  25631. paramType: ts.Diagnostics.KIND,
  25632. showInSimplifiedHelpView: true,
  25633. category: ts.Diagnostics.Basic_Options,
  25634. description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
  25635. },
  25636. {
  25637. name: "lib",
  25638. type: "list",
  25639. element: {
  25640. name: "lib",
  25641. type: ts.libMap
  25642. },
  25643. affectsModuleResolution: true,
  25644. showInSimplifiedHelpView: true,
  25645. category: ts.Diagnostics.Basic_Options,
  25646. description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
  25647. transpileOptionValue: undefined
  25648. },
  25649. {
  25650. name: "allowJs",
  25651. type: "boolean",
  25652. affectsModuleResolution: true,
  25653. showInSimplifiedHelpView: true,
  25654. category: ts.Diagnostics.Basic_Options,
  25655. description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
  25656. },
  25657. {
  25658. name: "checkJs",
  25659. type: "boolean",
  25660. category: ts.Diagnostics.Basic_Options,
  25661. description: ts.Diagnostics.Report_errors_in_js_files
  25662. },
  25663. {
  25664. name: "jsx",
  25665. type: ts.createMapFromTemplate({
  25666. "preserve": 1 /* Preserve */,
  25667. "react-native": 3 /* ReactNative */,
  25668. "react": 2 /* React */
  25669. }),
  25670. affectsSourceFile: true,
  25671. paramType: ts.Diagnostics.KIND,
  25672. showInSimplifiedHelpView: true,
  25673. category: ts.Diagnostics.Basic_Options,
  25674. description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
  25675. },
  25676. {
  25677. name: "declaration",
  25678. shortName: "d",
  25679. type: "boolean",
  25680. affectsEmit: true,
  25681. showInSimplifiedHelpView: true,
  25682. category: ts.Diagnostics.Basic_Options,
  25683. description: ts.Diagnostics.Generates_corresponding_d_ts_file,
  25684. transpileOptionValue: undefined
  25685. },
  25686. {
  25687. name: "declarationMap",
  25688. type: "boolean",
  25689. affectsEmit: true,
  25690. showInSimplifiedHelpView: true,
  25691. category: ts.Diagnostics.Basic_Options,
  25692. description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
  25693. transpileOptionValue: undefined
  25694. },
  25695. {
  25696. name: "emitDeclarationOnly",
  25697. type: "boolean",
  25698. affectsEmit: true,
  25699. category: ts.Diagnostics.Advanced_Options,
  25700. description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
  25701. transpileOptionValue: undefined
  25702. },
  25703. {
  25704. name: "sourceMap",
  25705. type: "boolean",
  25706. affectsEmit: true,
  25707. showInSimplifiedHelpView: true,
  25708. category: ts.Diagnostics.Basic_Options,
  25709. description: ts.Diagnostics.Generates_corresponding_map_file,
  25710. },
  25711. {
  25712. name: "outFile",
  25713. type: "string",
  25714. affectsEmit: true,
  25715. isFilePath: true,
  25716. paramType: ts.Diagnostics.FILE,
  25717. showInSimplifiedHelpView: true,
  25718. category: ts.Diagnostics.Basic_Options,
  25719. description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
  25720. transpileOptionValue: undefined
  25721. },
  25722. {
  25723. name: "outDir",
  25724. type: "string",
  25725. affectsEmit: true,
  25726. isFilePath: true,
  25727. paramType: ts.Diagnostics.DIRECTORY,
  25728. showInSimplifiedHelpView: true,
  25729. category: ts.Diagnostics.Basic_Options,
  25730. description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
  25731. },
  25732. {
  25733. name: "rootDir",
  25734. type: "string",
  25735. affectsEmit: true,
  25736. isFilePath: true,
  25737. paramType: ts.Diagnostics.LOCATION,
  25738. category: ts.Diagnostics.Basic_Options,
  25739. description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
  25740. },
  25741. {
  25742. name: "composite",
  25743. type: "boolean",
  25744. affectsEmit: true,
  25745. isTSConfigOnly: true,
  25746. category: ts.Diagnostics.Basic_Options,
  25747. description: ts.Diagnostics.Enable_project_compilation,
  25748. transpileOptionValue: undefined
  25749. },
  25750. {
  25751. name: "tsBuildInfoFile",
  25752. type: "string",
  25753. affectsEmit: true,
  25754. isFilePath: true,
  25755. paramType: ts.Diagnostics.FILE,
  25756. category: ts.Diagnostics.Basic_Options,
  25757. description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
  25758. transpileOptionValue: undefined
  25759. },
  25760. {
  25761. name: "removeComments",
  25762. type: "boolean",
  25763. affectsEmit: true,
  25764. showInSimplifiedHelpView: true,
  25765. category: ts.Diagnostics.Basic_Options,
  25766. description: ts.Diagnostics.Do_not_emit_comments_to_output,
  25767. },
  25768. {
  25769. name: "noEmit",
  25770. type: "boolean",
  25771. affectsEmit: true,
  25772. showInSimplifiedHelpView: true,
  25773. category: ts.Diagnostics.Basic_Options,
  25774. description: ts.Diagnostics.Do_not_emit_outputs,
  25775. transpileOptionValue: undefined
  25776. },
  25777. {
  25778. name: "importHelpers",
  25779. type: "boolean",
  25780. affectsEmit: true,
  25781. category: ts.Diagnostics.Basic_Options,
  25782. description: ts.Diagnostics.Import_emit_helpers_from_tslib
  25783. },
  25784. {
  25785. name: "importsNotUsedAsValues",
  25786. type: ts.createMapFromTemplate({
  25787. remove: 0 /* Remove */,
  25788. preserve: 1 /* Preserve */,
  25789. error: 2 /* Error */
  25790. }),
  25791. affectsEmit: true,
  25792. affectsSemanticDiagnostics: true,
  25793. category: ts.Diagnostics.Advanced_Options,
  25794. description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
  25795. },
  25796. {
  25797. name: "downlevelIteration",
  25798. type: "boolean",
  25799. affectsEmit: true,
  25800. category: ts.Diagnostics.Basic_Options,
  25801. description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
  25802. },
  25803. {
  25804. name: "isolatedModules",
  25805. type: "boolean",
  25806. category: ts.Diagnostics.Basic_Options,
  25807. description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
  25808. transpileOptionValue: true
  25809. },
  25810. // Strict Type Checks
  25811. {
  25812. name: "strict",
  25813. type: "boolean",
  25814. showInSimplifiedHelpView: true,
  25815. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25816. description: ts.Diagnostics.Enable_all_strict_type_checking_options
  25817. },
  25818. {
  25819. name: "noImplicitAny",
  25820. type: "boolean",
  25821. affectsSemanticDiagnostics: true,
  25822. strictFlag: true,
  25823. showInSimplifiedHelpView: true,
  25824. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25825. description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
  25826. },
  25827. {
  25828. name: "strictNullChecks",
  25829. type: "boolean",
  25830. affectsSemanticDiagnostics: true,
  25831. strictFlag: true,
  25832. showInSimplifiedHelpView: true,
  25833. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25834. description: ts.Diagnostics.Enable_strict_null_checks
  25835. },
  25836. {
  25837. name: "strictFunctionTypes",
  25838. type: "boolean",
  25839. affectsSemanticDiagnostics: true,
  25840. strictFlag: true,
  25841. showInSimplifiedHelpView: true,
  25842. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25843. description: ts.Diagnostics.Enable_strict_checking_of_function_types
  25844. },
  25845. {
  25846. name: "strictBindCallApply",
  25847. type: "boolean",
  25848. strictFlag: true,
  25849. showInSimplifiedHelpView: true,
  25850. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25851. description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
  25852. },
  25853. {
  25854. name: "strictPropertyInitialization",
  25855. type: "boolean",
  25856. affectsSemanticDiagnostics: true,
  25857. strictFlag: true,
  25858. showInSimplifiedHelpView: true,
  25859. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25860. description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
  25861. },
  25862. {
  25863. name: "noImplicitThis",
  25864. type: "boolean",
  25865. affectsSemanticDiagnostics: true,
  25866. strictFlag: true,
  25867. showInSimplifiedHelpView: true,
  25868. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25869. description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
  25870. },
  25871. {
  25872. name: "alwaysStrict",
  25873. type: "boolean",
  25874. affectsSourceFile: true,
  25875. strictFlag: true,
  25876. showInSimplifiedHelpView: true,
  25877. category: ts.Diagnostics.Strict_Type_Checking_Options,
  25878. description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
  25879. },
  25880. // Additional Checks
  25881. {
  25882. name: "noUnusedLocals",
  25883. type: "boolean",
  25884. affectsSemanticDiagnostics: true,
  25885. showInSimplifiedHelpView: true,
  25886. category: ts.Diagnostics.Additional_Checks,
  25887. description: ts.Diagnostics.Report_errors_on_unused_locals,
  25888. },
  25889. {
  25890. name: "noUnusedParameters",
  25891. type: "boolean",
  25892. affectsSemanticDiagnostics: true,
  25893. showInSimplifiedHelpView: true,
  25894. category: ts.Diagnostics.Additional_Checks,
  25895. description: ts.Diagnostics.Report_errors_on_unused_parameters,
  25896. },
  25897. {
  25898. name: "noImplicitReturns",
  25899. type: "boolean",
  25900. affectsSemanticDiagnostics: true,
  25901. showInSimplifiedHelpView: true,
  25902. category: ts.Diagnostics.Additional_Checks,
  25903. description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
  25904. },
  25905. {
  25906. name: "noFallthroughCasesInSwitch",
  25907. type: "boolean",
  25908. affectsBindDiagnostics: true,
  25909. affectsSemanticDiagnostics: true,
  25910. showInSimplifiedHelpView: true,
  25911. category: ts.Diagnostics.Additional_Checks,
  25912. description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
  25913. },
  25914. // Module Resolution
  25915. {
  25916. name: "moduleResolution",
  25917. type: ts.createMapFromTemplate({
  25918. node: ts.ModuleResolutionKind.NodeJs,
  25919. classic: ts.ModuleResolutionKind.Classic,
  25920. }),
  25921. affectsModuleResolution: true,
  25922. paramType: ts.Diagnostics.STRATEGY,
  25923. category: ts.Diagnostics.Module_Resolution_Options,
  25924. description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
  25925. },
  25926. {
  25927. name: "baseUrl",
  25928. type: "string",
  25929. affectsModuleResolution: true,
  25930. isFilePath: true,
  25931. category: ts.Diagnostics.Module_Resolution_Options,
  25932. description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
  25933. },
  25934. {
  25935. // this option can only be specified in tsconfig.json
  25936. // use type = object to copy the value as-is
  25937. name: "paths",
  25938. type: "object",
  25939. affectsModuleResolution: true,
  25940. isTSConfigOnly: true,
  25941. category: ts.Diagnostics.Module_Resolution_Options,
  25942. description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
  25943. transpileOptionValue: undefined
  25944. },
  25945. {
  25946. // this option can only be specified in tsconfig.json
  25947. // use type = object to copy the value as-is
  25948. name: "rootDirs",
  25949. type: "list",
  25950. isTSConfigOnly: true,
  25951. element: {
  25952. name: "rootDirs",
  25953. type: "string",
  25954. isFilePath: true
  25955. },
  25956. affectsModuleResolution: true,
  25957. category: ts.Diagnostics.Module_Resolution_Options,
  25958. description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
  25959. transpileOptionValue: undefined
  25960. },
  25961. {
  25962. name: "typeRoots",
  25963. type: "list",
  25964. element: {
  25965. name: "typeRoots",
  25966. type: "string",
  25967. isFilePath: true
  25968. },
  25969. affectsModuleResolution: true,
  25970. category: ts.Diagnostics.Module_Resolution_Options,
  25971. description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
  25972. },
  25973. {
  25974. name: "types",
  25975. type: "list",
  25976. element: {
  25977. name: "types",
  25978. type: "string"
  25979. },
  25980. affectsModuleResolution: true,
  25981. showInSimplifiedHelpView: true,
  25982. category: ts.Diagnostics.Module_Resolution_Options,
  25983. description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
  25984. transpileOptionValue: undefined
  25985. },
  25986. {
  25987. name: "allowSyntheticDefaultImports",
  25988. type: "boolean",
  25989. affectsSemanticDiagnostics: true,
  25990. category: ts.Diagnostics.Module_Resolution_Options,
  25991. description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
  25992. },
  25993. {
  25994. name: "esModuleInterop",
  25995. type: "boolean",
  25996. affectsSemanticDiagnostics: true,
  25997. affectsEmit: true,
  25998. showInSimplifiedHelpView: true,
  25999. category: ts.Diagnostics.Module_Resolution_Options,
  26000. description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
  26001. },
  26002. {
  26003. name: "preserveSymlinks",
  26004. type: "boolean",
  26005. category: ts.Diagnostics.Module_Resolution_Options,
  26006. description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
  26007. },
  26008. {
  26009. name: "allowUmdGlobalAccess",
  26010. type: "boolean",
  26011. affectsSemanticDiagnostics: true,
  26012. category: ts.Diagnostics.Module_Resolution_Options,
  26013. description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
  26014. },
  26015. // Source Maps
  26016. {
  26017. name: "sourceRoot",
  26018. type: "string",
  26019. affectsEmit: true,
  26020. paramType: ts.Diagnostics.LOCATION,
  26021. category: ts.Diagnostics.Source_Map_Options,
  26022. description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
  26023. },
  26024. {
  26025. name: "mapRoot",
  26026. type: "string",
  26027. affectsEmit: true,
  26028. paramType: ts.Diagnostics.LOCATION,
  26029. category: ts.Diagnostics.Source_Map_Options,
  26030. description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
  26031. },
  26032. {
  26033. name: "inlineSourceMap",
  26034. type: "boolean",
  26035. affectsEmit: true,
  26036. category: ts.Diagnostics.Source_Map_Options,
  26037. description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
  26038. },
  26039. {
  26040. name: "inlineSources",
  26041. type: "boolean",
  26042. affectsEmit: true,
  26043. category: ts.Diagnostics.Source_Map_Options,
  26044. description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
  26045. },
  26046. // Experimental
  26047. {
  26048. name: "experimentalDecorators",
  26049. type: "boolean",
  26050. affectsSemanticDiagnostics: true,
  26051. category: ts.Diagnostics.Experimental_Options,
  26052. description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
  26053. },
  26054. {
  26055. name: "emitDecoratorMetadata",
  26056. type: "boolean",
  26057. affectsSemanticDiagnostics: true,
  26058. affectsEmit: true,
  26059. category: ts.Diagnostics.Experimental_Options,
  26060. description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
  26061. },
  26062. // Advanced
  26063. {
  26064. name: "jsxFactory",
  26065. type: "string",
  26066. category: ts.Diagnostics.Advanced_Options,
  26067. description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
  26068. },
  26069. {
  26070. name: "resolveJsonModule",
  26071. type: "boolean",
  26072. affectsModuleResolution: true,
  26073. category: ts.Diagnostics.Advanced_Options,
  26074. description: ts.Diagnostics.Include_modules_imported_with_json_extension
  26075. },
  26076. {
  26077. name: "out",
  26078. type: "string",
  26079. affectsEmit: true,
  26080. isFilePath: false,
  26081. // for correct behaviour, please use outFile
  26082. category: ts.Diagnostics.Advanced_Options,
  26083. paramType: ts.Diagnostics.FILE,
  26084. description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
  26085. transpileOptionValue: undefined
  26086. },
  26087. {
  26088. name: "reactNamespace",
  26089. type: "string",
  26090. affectsEmit: true,
  26091. category: ts.Diagnostics.Advanced_Options,
  26092. description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
  26093. },
  26094. {
  26095. name: "skipDefaultLibCheck",
  26096. type: "boolean",
  26097. category: ts.Diagnostics.Advanced_Options,
  26098. description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
  26099. },
  26100. {
  26101. name: "charset",
  26102. type: "string",
  26103. category: ts.Diagnostics.Advanced_Options,
  26104. description: ts.Diagnostics.The_character_set_of_the_input_files
  26105. },
  26106. {
  26107. name: "emitBOM",
  26108. type: "boolean",
  26109. affectsEmit: true,
  26110. category: ts.Diagnostics.Advanced_Options,
  26111. description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
  26112. },
  26113. {
  26114. name: "newLine",
  26115. type: ts.createMapFromTemplate({
  26116. crlf: 0 /* CarriageReturnLineFeed */,
  26117. lf: 1 /* LineFeed */
  26118. }),
  26119. affectsEmit: true,
  26120. paramType: ts.Diagnostics.NEWLINE,
  26121. category: ts.Diagnostics.Advanced_Options,
  26122. description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
  26123. },
  26124. {
  26125. name: "noErrorTruncation",
  26126. type: "boolean",
  26127. affectsSemanticDiagnostics: true,
  26128. category: ts.Diagnostics.Advanced_Options,
  26129. description: ts.Diagnostics.Do_not_truncate_error_messages
  26130. },
  26131. {
  26132. name: "noLib",
  26133. type: "boolean",
  26134. affectsModuleResolution: true,
  26135. category: ts.Diagnostics.Advanced_Options,
  26136. description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
  26137. // We are not returning a sourceFile for lib file when asked by the program,
  26138. // so pass --noLib to avoid reporting a file not found error.
  26139. transpileOptionValue: true
  26140. },
  26141. {
  26142. name: "noResolve",
  26143. type: "boolean",
  26144. affectsModuleResolution: true,
  26145. category: ts.Diagnostics.Advanced_Options,
  26146. description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
  26147. // We are not doing a full typecheck, we are not resolving the whole context,
  26148. // so pass --noResolve to avoid reporting missing file errors.
  26149. transpileOptionValue: true
  26150. },
  26151. {
  26152. name: "stripInternal",
  26153. type: "boolean",
  26154. affectsEmit: true,
  26155. category: ts.Diagnostics.Advanced_Options,
  26156. description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
  26157. },
  26158. {
  26159. name: "disableSizeLimit",
  26160. type: "boolean",
  26161. affectsSourceFile: true,
  26162. category: ts.Diagnostics.Advanced_Options,
  26163. description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
  26164. },
  26165. {
  26166. name: "disableSourceOfProjectReferenceRedirect",
  26167. type: "boolean",
  26168. isTSConfigOnly: true,
  26169. category: ts.Diagnostics.Advanced_Options,
  26170. description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
  26171. },
  26172. {
  26173. name: "disableSolutionSearching",
  26174. type: "boolean",
  26175. isTSConfigOnly: true,
  26176. category: ts.Diagnostics.Advanced_Options,
  26177. description: ts.Diagnostics.Disable_solution_searching_for_this_project
  26178. },
  26179. {
  26180. name: "noImplicitUseStrict",
  26181. type: "boolean",
  26182. affectsSemanticDiagnostics: true,
  26183. category: ts.Diagnostics.Advanced_Options,
  26184. description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
  26185. },
  26186. {
  26187. name: "noEmitHelpers",
  26188. type: "boolean",
  26189. affectsEmit: true,
  26190. category: ts.Diagnostics.Advanced_Options,
  26191. description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
  26192. },
  26193. {
  26194. name: "noEmitOnError",
  26195. type: "boolean",
  26196. affectsEmit: true,
  26197. category: ts.Diagnostics.Advanced_Options,
  26198. description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
  26199. transpileOptionValue: undefined
  26200. },
  26201. {
  26202. name: "preserveConstEnums",
  26203. type: "boolean",
  26204. affectsEmit: true,
  26205. category: ts.Diagnostics.Advanced_Options,
  26206. description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
  26207. },
  26208. {
  26209. name: "declarationDir",
  26210. type: "string",
  26211. affectsEmit: true,
  26212. isFilePath: true,
  26213. paramType: ts.Diagnostics.DIRECTORY,
  26214. category: ts.Diagnostics.Advanced_Options,
  26215. description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
  26216. transpileOptionValue: undefined
  26217. },
  26218. {
  26219. name: "skipLibCheck",
  26220. type: "boolean",
  26221. category: ts.Diagnostics.Advanced_Options,
  26222. description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
  26223. },
  26224. {
  26225. name: "allowUnusedLabels",
  26226. type: "boolean",
  26227. affectsBindDiagnostics: true,
  26228. affectsSemanticDiagnostics: true,
  26229. category: ts.Diagnostics.Advanced_Options,
  26230. description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
  26231. },
  26232. {
  26233. name: "allowUnreachableCode",
  26234. type: "boolean",
  26235. affectsBindDiagnostics: true,
  26236. affectsSemanticDiagnostics: true,
  26237. category: ts.Diagnostics.Advanced_Options,
  26238. description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
  26239. },
  26240. {
  26241. name: "suppressExcessPropertyErrors",
  26242. type: "boolean",
  26243. affectsSemanticDiagnostics: true,
  26244. category: ts.Diagnostics.Advanced_Options,
  26245. description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
  26246. },
  26247. {
  26248. name: "suppressImplicitAnyIndexErrors",
  26249. type: "boolean",
  26250. affectsSemanticDiagnostics: true,
  26251. category: ts.Diagnostics.Advanced_Options,
  26252. description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
  26253. },
  26254. {
  26255. name: "forceConsistentCasingInFileNames",
  26256. type: "boolean",
  26257. affectsModuleResolution: true,
  26258. category: ts.Diagnostics.Advanced_Options,
  26259. description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
  26260. },
  26261. {
  26262. name: "maxNodeModuleJsDepth",
  26263. type: "number",
  26264. affectsModuleResolution: true,
  26265. category: ts.Diagnostics.Advanced_Options,
  26266. description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
  26267. },
  26268. {
  26269. name: "noStrictGenericChecks",
  26270. type: "boolean",
  26271. affectsSemanticDiagnostics: true,
  26272. category: ts.Diagnostics.Advanced_Options,
  26273. description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
  26274. },
  26275. {
  26276. name: "useDefineForClassFields",
  26277. type: "boolean",
  26278. affectsSemanticDiagnostics: true,
  26279. affectsEmit: true,
  26280. category: ts.Diagnostics.Advanced_Options,
  26281. description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
  26282. },
  26283. {
  26284. name: "keyofStringsOnly",
  26285. type: "boolean",
  26286. category: ts.Diagnostics.Advanced_Options,
  26287. description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
  26288. },
  26289. {
  26290. // A list of plugins to load in the language service
  26291. name: "plugins",
  26292. type: "list",
  26293. isTSConfigOnly: true,
  26294. element: {
  26295. name: "plugin",
  26296. type: "object"
  26297. },
  26298. description: ts.Diagnostics.List_of_language_service_plugins
  26299. },
  26300. ]);
  26301. /* @internal */
  26302. ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
  26303. /* @internal */
  26304. ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
  26305. /* @internal */
  26306. ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
  26307. /* @internal */
  26308. ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
  26309. return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
  26310. });
  26311. /* @internal */
  26312. ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
  26313. return ts.hasProperty(option, "transpileOptionValue");
  26314. });
  26315. /* @internal */
  26316. ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
  26317. {
  26318. name: "verbose",
  26319. shortName: "v",
  26320. category: ts.Diagnostics.Command_line_Options,
  26321. description: ts.Diagnostics.Enable_verbose_logging,
  26322. type: "boolean"
  26323. },
  26324. {
  26325. name: "dry",
  26326. shortName: "d",
  26327. category: ts.Diagnostics.Command_line_Options,
  26328. description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
  26329. type: "boolean"
  26330. },
  26331. {
  26332. name: "force",
  26333. shortName: "f",
  26334. category: ts.Diagnostics.Command_line_Options,
  26335. description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
  26336. type: "boolean"
  26337. },
  26338. {
  26339. name: "clean",
  26340. category: ts.Diagnostics.Command_line_Options,
  26341. description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
  26342. type: "boolean"
  26343. }
  26344. ]);
  26345. /* @internal */
  26346. ts.typeAcquisitionDeclarations = [
  26347. {
  26348. /* @deprecated typingOptions.enableAutoDiscovery
  26349. * Use typeAcquisition.enable instead.
  26350. */
  26351. name: "enableAutoDiscovery",
  26352. type: "boolean",
  26353. },
  26354. {
  26355. name: "enable",
  26356. type: "boolean",
  26357. },
  26358. {
  26359. name: "include",
  26360. type: "list",
  26361. element: {
  26362. name: "include",
  26363. type: "string"
  26364. }
  26365. },
  26366. {
  26367. name: "exclude",
  26368. type: "list",
  26369. element: {
  26370. name: "exclude",
  26371. type: "string"
  26372. }
  26373. }
  26374. ];
  26375. /*@internal*/
  26376. function createOptionNameMap(optionDeclarations) {
  26377. var optionsNameMap = ts.createMap();
  26378. var shortOptionNames = ts.createMap();
  26379. ts.forEach(optionDeclarations, function (option) {
  26380. optionsNameMap.set(option.name.toLowerCase(), option);
  26381. if (option.shortName) {
  26382. shortOptionNames.set(option.shortName, option.name);
  26383. }
  26384. });
  26385. return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
  26386. }
  26387. ts.createOptionNameMap = createOptionNameMap;
  26388. var optionsNameMapCache;
  26389. /* @internal */
  26390. function getOptionsNameMap() {
  26391. return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
  26392. }
  26393. ts.getOptionsNameMap = getOptionsNameMap;
  26394. /* @internal */
  26395. ts.defaultInitCompilerOptions = {
  26396. module: ts.ModuleKind.CommonJS,
  26397. target: 1 /* ES5 */,
  26398. strict: true,
  26399. esModuleInterop: true,
  26400. forceConsistentCasingInFileNames: true
  26401. };
  26402. /* @internal */
  26403. function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
  26404. // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
  26405. if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
  26406. return {
  26407. enable: typeAcquisition.enableAutoDiscovery,
  26408. include: typeAcquisition.include || [],
  26409. exclude: typeAcquisition.exclude || []
  26410. };
  26411. }
  26412. return typeAcquisition;
  26413. }
  26414. ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
  26415. /* @internal */
  26416. function createCompilerDiagnosticForInvalidCustomType(opt) {
  26417. return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
  26418. }
  26419. ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
  26420. function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
  26421. var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
  26422. return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
  26423. }
  26424. /* @internal */
  26425. function parseCustomTypeOption(opt, value, errors) {
  26426. return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
  26427. }
  26428. ts.parseCustomTypeOption = parseCustomTypeOption;
  26429. /* @internal */
  26430. function parseListTypeOption(opt, value, errors) {
  26431. if (value === void 0) { value = ""; }
  26432. value = trimString(value);
  26433. if (ts.startsWith(value, "-")) {
  26434. return undefined;
  26435. }
  26436. if (value === "") {
  26437. return [];
  26438. }
  26439. var values = value.split(",");
  26440. switch (opt.element.type) {
  26441. case "number":
  26442. return ts.map(values, parseInt);
  26443. case "string":
  26444. return ts.map(values, function (v) { return v || ""; });
  26445. default:
  26446. return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
  26447. }
  26448. }
  26449. ts.parseListTypeOption = parseListTypeOption;
  26450. function getOptionName(option) {
  26451. return option.name;
  26452. }
  26453. function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
  26454. var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
  26455. return possibleOption ?
  26456. createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
  26457. createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
  26458. }
  26459. /*@internal*/
  26460. function parseCommandLineWorker(diagnostics, commandLine, readFile) {
  26461. var options = {};
  26462. var watchOptions;
  26463. var fileNames = [];
  26464. var errors = [];
  26465. parseStrings(commandLine);
  26466. return {
  26467. options: options,
  26468. watchOptions: watchOptions,
  26469. fileNames: fileNames,
  26470. errors: errors
  26471. };
  26472. function parseStrings(args) {
  26473. var i = 0;
  26474. while (i < args.length) {
  26475. var s = args[i];
  26476. i++;
  26477. if (s.charCodeAt(0) === 64 /* at */) {
  26478. parseResponseFile(s.slice(1));
  26479. }
  26480. else if (s.charCodeAt(0) === 45 /* minus */) {
  26481. var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
  26482. var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
  26483. if (opt) {
  26484. i = parseOptionValue(args, i, diagnostics, opt, options, errors);
  26485. }
  26486. else {
  26487. var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
  26488. if (watchOpt) {
  26489. i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
  26490. }
  26491. else {
  26492. errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
  26493. }
  26494. }
  26495. }
  26496. else {
  26497. fileNames.push(s);
  26498. }
  26499. }
  26500. }
  26501. function parseResponseFile(fileName) {
  26502. var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName);
  26503. if (!text) {
  26504. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName));
  26505. return;
  26506. }
  26507. var args = [];
  26508. var pos = 0;
  26509. while (true) {
  26510. while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
  26511. pos++;
  26512. if (pos >= text.length)
  26513. break;
  26514. var start = pos;
  26515. if (text.charCodeAt(start) === 34 /* doubleQuote */) {
  26516. pos++;
  26517. while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
  26518. pos++;
  26519. if (pos < text.length) {
  26520. args.push(text.substring(start + 1, pos));
  26521. pos++;
  26522. }
  26523. else {
  26524. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
  26525. }
  26526. }
  26527. else {
  26528. while (text.charCodeAt(pos) > 32 /* space */)
  26529. pos++;
  26530. args.push(text.substring(start, pos));
  26531. }
  26532. }
  26533. parseStrings(args);
  26534. }
  26535. }
  26536. ts.parseCommandLineWorker = parseCommandLineWorker;
  26537. function parseOptionValue(args, i, diagnostics, opt, options, errors) {
  26538. if (opt.isTSConfigOnly) {
  26539. var optValue = args[i];
  26540. if (optValue === "null") {
  26541. options[opt.name] = undefined;
  26542. i++;
  26543. }
  26544. else if (opt.type === "boolean") {
  26545. if (optValue === "false") {
  26546. options[opt.name] = false;
  26547. i++;
  26548. }
  26549. else {
  26550. if (optValue === "true")
  26551. i++;
  26552. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
  26553. }
  26554. }
  26555. else {
  26556. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
  26557. if (optValue && !ts.startsWith(optValue, "-"))
  26558. i++;
  26559. }
  26560. }
  26561. else {
  26562. // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
  26563. if (!args[i] && opt.type !== "boolean") {
  26564. errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
  26565. }
  26566. if (args[i] !== "null") {
  26567. switch (opt.type) {
  26568. case "number":
  26569. options[opt.name] = parseInt(args[i]);
  26570. i++;
  26571. break;
  26572. case "boolean":
  26573. // boolean flag has optional value true, false, others
  26574. var optValue = args[i];
  26575. options[opt.name] = optValue !== "false";
  26576. // consume next argument as boolean flag value
  26577. if (optValue === "false" || optValue === "true") {
  26578. i++;
  26579. }
  26580. break;
  26581. case "string":
  26582. options[opt.name] = args[i] || "";
  26583. i++;
  26584. break;
  26585. case "list":
  26586. var result = parseListTypeOption(opt, args[i], errors);
  26587. options[opt.name] = result || [];
  26588. if (result) {
  26589. i++;
  26590. }
  26591. break;
  26592. // If not a primitive, the possible types are specified in what is effectively a map of options.
  26593. default:
  26594. options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
  26595. i++;
  26596. break;
  26597. }
  26598. }
  26599. else {
  26600. options[opt.name] = undefined;
  26601. i++;
  26602. }
  26603. }
  26604. return i;
  26605. }
  26606. /*@internal*/
  26607. ts.compilerOptionsDidYouMeanDiagnostics = {
  26608. getOptionsNameMap: getOptionsNameMap,
  26609. optionDeclarations: ts.optionDeclarations,
  26610. unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
  26611. unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
  26612. optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
  26613. };
  26614. function parseCommandLine(commandLine, readFile) {
  26615. return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
  26616. }
  26617. ts.parseCommandLine = parseCommandLine;
  26618. /** @internal */
  26619. function getOptionFromName(optionName, allowShort) {
  26620. return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
  26621. }
  26622. ts.getOptionFromName = getOptionFromName;
  26623. function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
  26624. if (allowShort === void 0) { allowShort = false; }
  26625. optionName = optionName.toLowerCase();
  26626. var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
  26627. // Try to translate short option names to their full equivalents.
  26628. if (allowShort) {
  26629. var short = shortOptionNames.get(optionName);
  26630. if (short !== undefined) {
  26631. optionName = short;
  26632. }
  26633. }
  26634. return optionsNameMap.get(optionName);
  26635. }
  26636. var buildOptionsNameMapCache;
  26637. function getBuildOptionsNameMap() {
  26638. return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
  26639. }
  26640. var buildOptionsDidYouMeanDiagnostics = {
  26641. getOptionsNameMap: getBuildOptionsNameMap,
  26642. optionDeclarations: ts.buildOpts,
  26643. unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
  26644. unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
  26645. optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
  26646. };
  26647. /*@internal*/
  26648. function parseBuildCommand(args) {
  26649. var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
  26650. var buildOptions = options;
  26651. if (projects.length === 0) {
  26652. // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
  26653. projects.push(".");
  26654. }
  26655. // Nonsensical combinations
  26656. if (buildOptions.clean && buildOptions.force) {
  26657. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
  26658. }
  26659. if (buildOptions.clean && buildOptions.verbose) {
  26660. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
  26661. }
  26662. if (buildOptions.clean && buildOptions.watch) {
  26663. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
  26664. }
  26665. if (buildOptions.watch && buildOptions.dry) {
  26666. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
  26667. }
  26668. return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
  26669. }
  26670. ts.parseBuildCommand = parseBuildCommand;
  26671. /* @internal */
  26672. function getDiagnosticText(_message) {
  26673. var _args = [];
  26674. for (var _i = 1; _i < arguments.length; _i++) {
  26675. _args[_i - 1] = arguments[_i];
  26676. }
  26677. var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
  26678. return diagnostic.messageText;
  26679. }
  26680. ts.getDiagnosticText = getDiagnosticText;
  26681. /**
  26682. * Reads the config file, reports errors if any and exits if the config file cannot be found
  26683. */
  26684. function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) {
  26685. var configFileText;
  26686. try {
  26687. configFileText = host.readFile(configFileName);
  26688. }
  26689. catch (e) {
  26690. var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
  26691. host.onUnRecoverableConfigFileDiagnostic(error);
  26692. return undefined;
  26693. }
  26694. if (!configFileText) {
  26695. var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
  26696. host.onUnRecoverableConfigFileDiagnostic(error);
  26697. return undefined;
  26698. }
  26699. var result = ts.parseJsonText(configFileName, configFileText);
  26700. var cwd = host.getCurrentDirectory();
  26701. result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
  26702. result.resolvedPath = result.path;
  26703. result.originalFileName = result.fileName;
  26704. return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd),
  26705. /*resolutionStack*/ undefined,
  26706. /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend);
  26707. }
  26708. ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
  26709. /**
  26710. * Read tsconfig.json file
  26711. * @param fileName The path to the config file
  26712. */
  26713. function readConfigFile(fileName, readFile) {
  26714. var textOrDiagnostic = tryReadFile(fileName, readFile);
  26715. return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
  26716. }
  26717. ts.readConfigFile = readConfigFile;
  26718. /**
  26719. * Parse the text of the tsconfig.json file
  26720. * @param fileName The path to the config file
  26721. * @param jsonText The text of the config file
  26722. */
  26723. function parseConfigFileTextToJson(fileName, jsonText) {
  26724. var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
  26725. return {
  26726. config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
  26727. error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
  26728. };
  26729. }
  26730. ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
  26731. /**
  26732. * Read tsconfig.json file
  26733. * @param fileName The path to the config file
  26734. */
  26735. function readJsonConfigFile(fileName, readFile) {
  26736. var textOrDiagnostic = tryReadFile(fileName, readFile);
  26737. return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
  26738. }
  26739. ts.readJsonConfigFile = readJsonConfigFile;
  26740. function tryReadFile(fileName, readFile) {
  26741. var text;
  26742. try {
  26743. text = readFile(fileName);
  26744. }
  26745. catch (e) {
  26746. return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
  26747. }
  26748. return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text;
  26749. }
  26750. function commandLineOptionsToMap(options) {
  26751. return ts.arrayToMap(options, getOptionName);
  26752. }
  26753. var typeAcquisitionDidYouMeanDiagnostics = {
  26754. optionDeclarations: ts.typeAcquisitionDeclarations,
  26755. unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
  26756. unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
  26757. };
  26758. var watchOptionsNameMapCache;
  26759. function getWatchOptionsNameMap() {
  26760. return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
  26761. }
  26762. var watchOptionsDidYouMeanDiagnostics = {
  26763. getOptionsNameMap: getWatchOptionsNameMap,
  26764. optionDeclarations: ts.optionsForWatch,
  26765. unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
  26766. unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
  26767. optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
  26768. };
  26769. var commandLineCompilerOptionsMapCache;
  26770. function getCommandLineCompilerOptionsMap() {
  26771. return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
  26772. }
  26773. var commandLineWatchOptionsMapCache;
  26774. function getCommandLineWatchOptionsMap() {
  26775. return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
  26776. }
  26777. var commandLineTypeAcquisitionMapCache;
  26778. function getCommandLineTypeAcquisitionMap() {
  26779. return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
  26780. }
  26781. var _tsconfigRootOptions;
  26782. function getTsconfigRootOptionsMap() {
  26783. if (_tsconfigRootOptions === undefined) {
  26784. _tsconfigRootOptions = {
  26785. name: undefined,
  26786. type: "object",
  26787. elementOptions: commandLineOptionsToMap([
  26788. {
  26789. name: "compilerOptions",
  26790. type: "object",
  26791. elementOptions: getCommandLineCompilerOptionsMap(),
  26792. extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
  26793. },
  26794. {
  26795. name: "watchOptions",
  26796. type: "object",
  26797. elementOptions: getCommandLineWatchOptionsMap(),
  26798. extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
  26799. },
  26800. {
  26801. name: "typingOptions",
  26802. type: "object",
  26803. elementOptions: getCommandLineTypeAcquisitionMap(),
  26804. extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
  26805. },
  26806. {
  26807. name: "typeAcquisition",
  26808. type: "object",
  26809. elementOptions: getCommandLineTypeAcquisitionMap(),
  26810. extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
  26811. },
  26812. {
  26813. name: "extends",
  26814. type: "string"
  26815. },
  26816. {
  26817. name: "references",
  26818. type: "list",
  26819. element: {
  26820. name: "references",
  26821. type: "object"
  26822. }
  26823. },
  26824. {
  26825. name: "files",
  26826. type: "list",
  26827. element: {
  26828. name: "files",
  26829. type: "string"
  26830. }
  26831. },
  26832. {
  26833. name: "include",
  26834. type: "list",
  26835. element: {
  26836. name: "include",
  26837. type: "string"
  26838. }
  26839. },
  26840. {
  26841. name: "exclude",
  26842. type: "list",
  26843. element: {
  26844. name: "exclude",
  26845. type: "string"
  26846. }
  26847. },
  26848. ts.compileOnSaveCommandLineOption
  26849. ])
  26850. };
  26851. }
  26852. return _tsconfigRootOptions;
  26853. }
  26854. /**
  26855. * Convert the json syntax tree into the json value
  26856. */
  26857. function convertToObject(sourceFile, errors) {
  26858. return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
  26859. }
  26860. ts.convertToObject = convertToObject;
  26861. /**
  26862. * Convert the json syntax tree into the json value and report errors
  26863. * This returns the json value (apart from checking errors) only if returnValue provided is true.
  26864. * Otherwise it just checks the errors and returns undefined
  26865. */
  26866. /*@internal*/
  26867. function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
  26868. if (!sourceFile.statements.length) {
  26869. return returnValue ? {} : undefined;
  26870. }
  26871. return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
  26872. function isRootOptionMap(knownOptions) {
  26873. return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
  26874. }
  26875. function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
  26876. var result = returnValue ? {} : undefined;
  26877. var _loop_3 = function (element) {
  26878. if (element.kind !== 281 /* PropertyAssignment */) {
  26879. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
  26880. return "continue";
  26881. }
  26882. if (element.questionToken) {
  26883. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
  26884. }
  26885. if (!isDoubleQuotedString(element.name)) {
  26886. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
  26887. }
  26888. var textOfKey = ts.getTextOfPropertyName(element.name);
  26889. var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
  26890. var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
  26891. if (keyText && extraKeyDiagnostics && !option) {
  26892. if (knownOptions) {
  26893. errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
  26894. }
  26895. else {
  26896. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
  26897. }
  26898. }
  26899. var value = convertPropertyValueToJson(element.initializer, option);
  26900. if (typeof keyText !== "undefined") {
  26901. if (returnValue) {
  26902. result[keyText] = value;
  26903. }
  26904. // Notify key value set, if user asked for it
  26905. if (jsonConversionNotifier &&
  26906. // Current callbacks are only on known parent option or if we are setting values in the root
  26907. (parentOption || isRootOptionMap(knownOptions))) {
  26908. var isValidOptionValue = isCompilerOptionsValue(option, value);
  26909. if (parentOption) {
  26910. if (isValidOptionValue) {
  26911. // Notify option set in the parent if its a valid option value
  26912. jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
  26913. }
  26914. }
  26915. else if (isRootOptionMap(knownOptions)) {
  26916. if (isValidOptionValue) {
  26917. // Notify about the valid root key value being set
  26918. jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
  26919. }
  26920. else if (!option) {
  26921. // Notify about the unknown root key value being set
  26922. jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
  26923. }
  26924. }
  26925. }
  26926. }
  26927. };
  26928. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  26929. var element = _a[_i];
  26930. _loop_3(element);
  26931. }
  26932. return result;
  26933. }
  26934. function convertArrayLiteralExpressionToJson(elements, elementOption) {
  26935. if (!returnValue) {
  26936. return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
  26937. }
  26938. // Filter out invalid values
  26939. return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
  26940. }
  26941. function convertPropertyValueToJson(valueExpression, option) {
  26942. switch (valueExpression.kind) {
  26943. case 106 /* TrueKeyword */:
  26944. reportInvalidOptionValue(option && option.type !== "boolean");
  26945. return true;
  26946. case 91 /* FalseKeyword */:
  26947. reportInvalidOptionValue(option && option.type !== "boolean");
  26948. return false;
  26949. case 100 /* NullKeyword */:
  26950. reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
  26951. return null; // eslint-disable-line no-null/no-null
  26952. case 10 /* StringLiteral */:
  26953. if (!isDoubleQuotedString(valueExpression)) {
  26954. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
  26955. }
  26956. reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
  26957. var text = valueExpression.text;
  26958. if (option && !ts.isString(option.type)) {
  26959. var customOption = option;
  26960. // Validate custom option type
  26961. if (!customOption.type.has(text.toLowerCase())) {
  26962. errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
  26963. }
  26964. }
  26965. return text;
  26966. case 8 /* NumericLiteral */:
  26967. reportInvalidOptionValue(option && option.type !== "number");
  26968. return Number(valueExpression.text);
  26969. case 207 /* PrefixUnaryExpression */:
  26970. if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
  26971. break; // not valid JSON syntax
  26972. }
  26973. reportInvalidOptionValue(option && option.type !== "number");
  26974. return -Number(valueExpression.operand.text);
  26975. case 193 /* ObjectLiteralExpression */:
  26976. reportInvalidOptionValue(option && option.type !== "object");
  26977. var objectLiteralExpression = valueExpression;
  26978. // Currently having element option declaration in the tsconfig with type "object"
  26979. // determines if it needs onSetValidOptionKeyValueInParent callback or not
  26980. // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
  26981. // that satifies it and need it to modify options set in them (for normalizing file paths)
  26982. // vs what we set in the json
  26983. // If need arises, we can modify this interface and callbacks as needed
  26984. if (option) {
  26985. var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
  26986. return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
  26987. }
  26988. else {
  26989. return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined,
  26990. /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
  26991. }
  26992. case 192 /* ArrayLiteralExpression */:
  26993. reportInvalidOptionValue(option && option.type !== "list");
  26994. return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
  26995. }
  26996. // Not in expected format
  26997. if (option) {
  26998. reportInvalidOptionValue(/*isError*/ true);
  26999. }
  27000. else {
  27001. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal));
  27002. }
  27003. return undefined;
  27004. function reportInvalidOptionValue(isError) {
  27005. if (isError) {
  27006. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
  27007. }
  27008. }
  27009. }
  27010. function isDoubleQuotedString(node) {
  27011. return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
  27012. }
  27013. }
  27014. ts.convertToObjectWorker = convertToObjectWorker;
  27015. function getCompilerOptionValueTypeString(option) {
  27016. return option.type === "list" ?
  27017. "Array" :
  27018. ts.isString(option.type) ? option.type : "string";
  27019. }
  27020. function isCompilerOptionsValue(option, value) {
  27021. if (option) {
  27022. if (isNullOrUndefined(value))
  27023. return true; // All options are undefinable/nullable
  27024. if (option.type === "list") {
  27025. return ts.isArray(value);
  27026. }
  27027. var expectedType = ts.isString(option.type) ? option.type : "string";
  27028. return typeof value === expectedType;
  27029. }
  27030. return false;
  27031. }
  27032. /**
  27033. * Generate an uncommented, complete tsconfig for use with "--showConfig"
  27034. * @param configParseResult options to be generated into tsconfig.json
  27035. * @param configFileName name of the parsed config file - output paths will be generated relative to this
  27036. * @param host provides current directory and case sensitivity services
  27037. */
  27038. /** @internal */
  27039. function convertToTSConfig(configParseResult, configFileName, host) {
  27040. var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  27041. var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
  27042. var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
  27043. var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
  27044. var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? {
  27045. include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
  27046. exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
  27047. } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
  27048. return config;
  27049. }
  27050. ts.convertToTSConfig = convertToTSConfig;
  27051. function optionMapToObject(optionMap) {
  27052. return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
  27053. var _a;
  27054. return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
  27055. }, {}));
  27056. }
  27057. function filterSameAsDefaultInclude(specs) {
  27058. if (!ts.length(specs))
  27059. return undefined;
  27060. if (ts.length(specs) !== 1)
  27061. return specs;
  27062. if (specs[0] === "**/*")
  27063. return undefined;
  27064. return specs;
  27065. }
  27066. function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
  27067. if (!includeSpecs)
  27068. return function (_) { return true; };
  27069. var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
  27070. var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
  27071. var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
  27072. if (includeRe) {
  27073. if (excludeRe) {
  27074. return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
  27075. }
  27076. return function (path) { return !includeRe.test(path); };
  27077. }
  27078. if (excludeRe) {
  27079. return function (path) { return excludeRe.test(path); };
  27080. }
  27081. return function (_) { return true; };
  27082. }
  27083. function getCustomTypeMapOfCommandLineOption(optionDefinition) {
  27084. if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
  27085. // this is of a type CommandLineOptionOfPrimitiveType
  27086. return undefined;
  27087. }
  27088. else if (optionDefinition.type === "list") {
  27089. return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
  27090. }
  27091. else {
  27092. return optionDefinition.type;
  27093. }
  27094. }
  27095. function getNameOfCompilerOptionValue(value, customTypeMap) {
  27096. // There is a typeMap associated with this command-line option so use it to map value back to its name
  27097. return ts.forEachEntry(customTypeMap, function (mapValue, key) {
  27098. if (mapValue === value) {
  27099. return key;
  27100. }
  27101. });
  27102. }
  27103. function serializeCompilerOptions(options, pathOptions) {
  27104. return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
  27105. }
  27106. function serializeWatchOptions(options) {
  27107. return serializeOptionBaseObject(options, getWatchOptionsNameMap());
  27108. }
  27109. function serializeOptionBaseObject(options, _a, pathOptions) {
  27110. var optionsNameMap = _a.optionsNameMap;
  27111. var result = ts.createMap();
  27112. var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
  27113. var _loop_4 = function (name) {
  27114. if (ts.hasProperty(options, name)) {
  27115. // tsconfig only options cannot be specified via command line,
  27116. // so we can assume that only types that can appear here string | number | boolean
  27117. if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
  27118. return "continue";
  27119. }
  27120. var value = options[name];
  27121. var optionDefinition = optionsNameMap.get(name.toLowerCase());
  27122. if (optionDefinition) {
  27123. var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
  27124. if (!customTypeMap_1) {
  27125. // There is no map associated with this compiler option then use the value as-is
  27126. // This is the case if the value is expect to be string, number, boolean or list of string
  27127. if (pathOptions && optionDefinition.isFilePath) {
  27128. result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
  27129. }
  27130. else {
  27131. result.set(name, value);
  27132. }
  27133. }
  27134. else {
  27135. if (optionDefinition.type === "list") {
  27136. result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
  27137. }
  27138. else {
  27139. // There is a typeMap associated with this command-line option so use it to map value back to its name
  27140. result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
  27141. }
  27142. }
  27143. }
  27144. }
  27145. };
  27146. for (var name in options) {
  27147. _loop_4(name);
  27148. }
  27149. return result;
  27150. }
  27151. /**
  27152. * Generate tsconfig configuration when running command line "--init"
  27153. * @param options commandlineOptions to be generated into tsconfig.json
  27154. * @param fileNames array of filenames to be generated into tsconfig.json
  27155. */
  27156. /* @internal */
  27157. function generateTSConfig(options, fileNames, newLine) {
  27158. var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
  27159. var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
  27160. return writeConfigurations();
  27161. function getDefaultValueForOption(option) {
  27162. switch (option.type) {
  27163. case "number":
  27164. return 1;
  27165. case "boolean":
  27166. return true;
  27167. case "string":
  27168. return option.isFilePath ? "./" : "";
  27169. case "list":
  27170. return [];
  27171. case "object":
  27172. return {};
  27173. default:
  27174. var iterResult = option.type.keys().next();
  27175. if (!iterResult.done)
  27176. return iterResult.value;
  27177. return ts.Debug.fail("Expected 'option.type' to have entries.");
  27178. }
  27179. }
  27180. function makePadding(paddingLength) {
  27181. return Array(paddingLength + 1).join(" ");
  27182. }
  27183. function isAllowedOption(_a) {
  27184. var category = _a.category, name = _a.name;
  27185. // Skip options which do not have a category or have category `Command_line_Options`
  27186. // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
  27187. return category !== undefined
  27188. && category !== ts.Diagnostics.Command_line_Options
  27189. && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
  27190. }
  27191. function writeConfigurations() {
  27192. // Filter applicable options to place in the file
  27193. var categorizedOptions = ts.createMultiMap();
  27194. for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
  27195. var option = optionDeclarations_1[_i];
  27196. var category = option.category;
  27197. if (isAllowedOption(option)) {
  27198. categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
  27199. }
  27200. }
  27201. // Serialize all options and their descriptions
  27202. var marginLength = 0;
  27203. var seenKnownKeys = 0;
  27204. var nameColumn = [];
  27205. var descriptionColumn = [];
  27206. categorizedOptions.forEach(function (options, category) {
  27207. if (nameColumn.length !== 0) {
  27208. nameColumn.push("");
  27209. descriptionColumn.push("");
  27210. }
  27211. nameColumn.push("/* " + category + " */");
  27212. descriptionColumn.push("");
  27213. for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
  27214. var option = options_1[_i];
  27215. var optionName = void 0;
  27216. if (compilerOptionsMap.has(option.name)) {
  27217. optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
  27218. }
  27219. else {
  27220. optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
  27221. }
  27222. nameColumn.push(optionName);
  27223. descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */");
  27224. marginLength = Math.max(optionName.length, marginLength);
  27225. }
  27226. });
  27227. // Write the output
  27228. var tab = makePadding(2);
  27229. var result = [];
  27230. result.push("{");
  27231. result.push(tab + "\"compilerOptions\": {");
  27232. // Print out each row, aligning all the descriptions on the same column.
  27233. for (var i = 0; i < nameColumn.length; i++) {
  27234. var optionName = nameColumn[i];
  27235. var description = descriptionColumn[i];
  27236. result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description)));
  27237. }
  27238. if (fileNames.length) {
  27239. result.push(tab + "},");
  27240. result.push(tab + "\"files\": [");
  27241. for (var i = 0; i < fileNames.length; i++) {
  27242. result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
  27243. }
  27244. result.push(tab + "]");
  27245. }
  27246. else {
  27247. result.push(tab + "}");
  27248. }
  27249. result.push("}");
  27250. return result.join(newLine) + newLine;
  27251. }
  27252. }
  27253. ts.generateTSConfig = generateTSConfig;
  27254. /* @internal */
  27255. function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
  27256. var result = {};
  27257. var optionsNameMap = getOptionsNameMap().optionsNameMap;
  27258. for (var name in options) {
  27259. if (ts.hasProperty(options, name)) {
  27260. result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
  27261. }
  27262. }
  27263. if (result.configFilePath) {
  27264. result.configFilePath = toAbsolutePath(result.configFilePath);
  27265. }
  27266. return result;
  27267. }
  27268. ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
  27269. function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
  27270. if (option && !isNullOrUndefined(value)) {
  27271. if (option.type === "list") {
  27272. var values = value;
  27273. if (option.element.isFilePath && values.length) {
  27274. return values.map(toAbsolutePath);
  27275. }
  27276. }
  27277. else if (option.isFilePath) {
  27278. return toAbsolutePath(value);
  27279. }
  27280. }
  27281. return value;
  27282. }
  27283. /**
  27284. * Parse the contents of a config file (tsconfig.json).
  27285. * @param json The contents of the config file to parse
  27286. * @param host Instance of ParseConfigHost used to enumerate files in folder.
  27287. * @param basePath A root directory to resolve relative path entries in the config
  27288. * file to. e.g. outDir
  27289. */
  27290. function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
  27291. return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
  27292. }
  27293. ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
  27294. /**
  27295. * Parse the contents of a config file (tsconfig.json).
  27296. * @param jsonNode The contents of the config file to parse
  27297. * @param host Instance of ParseConfigHost used to enumerate files in folder.
  27298. * @param basePath A root directory to resolve relative path entries in the config
  27299. * file to. e.g. outDir
  27300. */
  27301. function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
  27302. return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
  27303. }
  27304. ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
  27305. /*@internal*/
  27306. function setConfigFileInOptions(options, configFile) {
  27307. if (configFile) {
  27308. Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
  27309. }
  27310. }
  27311. ts.setConfigFileInOptions = setConfigFileInOptions;
  27312. function isNullOrUndefined(x) {
  27313. return x === undefined || x === null; // eslint-disable-line no-null/no-null
  27314. }
  27315. function directoryOfCombinedPath(fileName, basePath) {
  27316. // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
  27317. // until consistent casing errors are reported
  27318. return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
  27319. }
  27320. /**
  27321. * Parse the contents of a config file from json or json source file (tsconfig.json).
  27322. * @param json The contents of the config file to parse
  27323. * @param sourceFile sourceFile corresponding to the Json
  27324. * @param host Instance of ParseConfigHost used to enumerate files in folder.
  27325. * @param basePath A root directory to resolve relative path entries in the config
  27326. * file to. e.g. outDir
  27327. * @param resolutionStack Only present for backwards-compatibility. Should be empty.
  27328. */
  27329. function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
  27330. if (existingOptions === void 0) { existingOptions = {}; }
  27331. if (resolutionStack === void 0) { resolutionStack = []; }
  27332. if (extraFileExtensions === void 0) { extraFileExtensions = []; }
  27333. ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
  27334. var errors = [];
  27335. var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
  27336. var raw = parsedConfig.raw;
  27337. var options = ts.extend(existingOptions, parsedConfig.options || {});
  27338. var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
  27339. ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
  27340. parsedConfig.watchOptions || existingWatchOptions;
  27341. options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
  27342. setConfigFileInOptions(options, sourceFile);
  27343. var projectReferences;
  27344. var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
  27345. return {
  27346. options: options,
  27347. watchOptions: watchOptions,
  27348. fileNames: fileNames,
  27349. projectReferences: projectReferences,
  27350. typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
  27351. raw: raw,
  27352. errors: errors,
  27353. wildcardDirectories: wildcardDirectories,
  27354. compileOnSave: !!raw.compileOnSave,
  27355. configFileSpecs: spec
  27356. };
  27357. function getFileNames() {
  27358. var filesSpecs;
  27359. if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
  27360. if (ts.isArray(raw.files)) {
  27361. filesSpecs = raw.files;
  27362. var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
  27363. var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
  27364. var hasExtends = ts.hasProperty(raw, "extends");
  27365. if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
  27366. if (sourceFile) {
  27367. var fileName = configFileName || "tsconfig.json";
  27368. var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
  27369. var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
  27370. var error = nodeValue
  27371. ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
  27372. : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
  27373. errors.push(error);
  27374. }
  27375. else {
  27376. createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
  27377. }
  27378. }
  27379. }
  27380. else {
  27381. createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
  27382. }
  27383. }
  27384. var includeSpecs;
  27385. if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
  27386. if (ts.isArray(raw.include)) {
  27387. includeSpecs = raw.include;
  27388. }
  27389. else {
  27390. createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
  27391. }
  27392. }
  27393. var excludeSpecs;
  27394. if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
  27395. if (ts.isArray(raw.exclude)) {
  27396. excludeSpecs = raw.exclude;
  27397. }
  27398. else {
  27399. createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
  27400. }
  27401. }
  27402. else if (raw.compilerOptions) {
  27403. var outDir = raw.compilerOptions.outDir;
  27404. var declarationDir = raw.compilerOptions.declarationDir;
  27405. if (outDir || declarationDir) {
  27406. excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
  27407. }
  27408. }
  27409. if (filesSpecs === undefined && includeSpecs === undefined) {
  27410. includeSpecs = ["**/*"];
  27411. }
  27412. var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
  27413. if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
  27414. errors.push(getErrorForNoInputFiles(result.spec, configFileName));
  27415. }
  27416. if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
  27417. if (ts.isArray(raw.references)) {
  27418. for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
  27419. var ref = _a[_i];
  27420. if (typeof ref.path !== "string") {
  27421. createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
  27422. }
  27423. else {
  27424. (projectReferences || (projectReferences = [])).push({
  27425. path: ts.getNormalizedAbsolutePath(ref.path, basePath),
  27426. originalPath: ref.path,
  27427. prepend: ref.prepend,
  27428. circular: ref.circular
  27429. });
  27430. }
  27431. }
  27432. }
  27433. else {
  27434. createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
  27435. }
  27436. }
  27437. return result;
  27438. }
  27439. function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
  27440. if (!sourceFile) {
  27441. errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
  27442. }
  27443. }
  27444. }
  27445. function isErrorNoInputFiles(error) {
  27446. return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
  27447. }
  27448. function getErrorForNoInputFiles(_a, configFileName) {
  27449. var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
  27450. return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []));
  27451. }
  27452. function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
  27453. return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
  27454. }
  27455. /*@internal*/
  27456. function canJsonReportNoInutFiles(raw) {
  27457. return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
  27458. }
  27459. ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
  27460. /*@internal*/
  27461. function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
  27462. var existingErrors = configParseDiagnostics.length;
  27463. if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
  27464. configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
  27465. }
  27466. else {
  27467. ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
  27468. }
  27469. return existingErrors !== configParseDiagnostics.length;
  27470. }
  27471. ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
  27472. function isSuccessfulParsedTsconfig(value) {
  27473. return !!value.options;
  27474. }
  27475. /**
  27476. * This *just* extracts options/include/exclude/files out of a config file.
  27477. * It does *not* resolve the included files.
  27478. */
  27479. function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
  27480. basePath = ts.normalizeSlashes(basePath);
  27481. var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
  27482. if (resolutionStack.indexOf(resolvedPath) >= 0) {
  27483. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
  27484. return { raw: json || convertToObject(sourceFile, errors) };
  27485. }
  27486. var ownConfig = json ?
  27487. parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
  27488. parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
  27489. if (ownConfig.extendedConfigPath) {
  27490. // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
  27491. resolutionStack = resolutionStack.concat([resolvedPath]);
  27492. var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
  27493. if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
  27494. var baseRaw_1 = extendedConfig.raw;
  27495. var raw_1 = ownConfig.raw;
  27496. var setPropertyInRawIfNotUndefined = function (propertyName) {
  27497. var value = raw_1[propertyName] || baseRaw_1[propertyName];
  27498. if (value) {
  27499. raw_1[propertyName] = value;
  27500. }
  27501. };
  27502. setPropertyInRawIfNotUndefined("include");
  27503. setPropertyInRawIfNotUndefined("exclude");
  27504. setPropertyInRawIfNotUndefined("files");
  27505. if (raw_1.compileOnSave === undefined) {
  27506. raw_1.compileOnSave = baseRaw_1.compileOnSave;
  27507. }
  27508. ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
  27509. ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
  27510. ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
  27511. ownConfig.watchOptions || extendedConfig.watchOptions;
  27512. // TODO extend type typeAcquisition
  27513. }
  27514. }
  27515. return ownConfig;
  27516. }
  27517. function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
  27518. if (ts.hasProperty(json, "excludes")) {
  27519. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
  27520. }
  27521. var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
  27522. // typingOptions has been deprecated and is only supported for backward compatibility purposes.
  27523. // It should be removed in future releases - use typeAcquisition instead.
  27524. var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
  27525. var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
  27526. json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
  27527. var extendedConfigPath;
  27528. if (json.extends) {
  27529. if (!ts.isString(json.extends)) {
  27530. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
  27531. }
  27532. else {
  27533. var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
  27534. extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
  27535. }
  27536. }
  27537. return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
  27538. }
  27539. function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
  27540. var options = getDefaultCompilerOptions(configFileName);
  27541. var typeAcquisition, typingOptionstypeAcquisition;
  27542. var watchOptions;
  27543. var extendedConfigPath;
  27544. var optionsIterator = {
  27545. onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
  27546. var currentOption;
  27547. switch (parentOption) {
  27548. case "compilerOptions":
  27549. currentOption = options;
  27550. break;
  27551. case "watchOptions":
  27552. currentOption = (watchOptions || (watchOptions = {}));
  27553. break;
  27554. case "typeAcquisition":
  27555. currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
  27556. break;
  27557. case "typingOptions":
  27558. currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
  27559. break;
  27560. default:
  27561. ts.Debug.fail("Unknown option");
  27562. }
  27563. currentOption[option.name] = normalizeOptionValue(option, basePath, value);
  27564. },
  27565. onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
  27566. switch (key) {
  27567. case "extends":
  27568. var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
  27569. extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
  27570. return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
  27571. });
  27572. return;
  27573. }
  27574. },
  27575. onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
  27576. if (key === "excludes") {
  27577. errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
  27578. }
  27579. }
  27580. };
  27581. var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
  27582. if (!typeAcquisition) {
  27583. if (typingOptionstypeAcquisition) {
  27584. typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
  27585. {
  27586. enable: typingOptionstypeAcquisition.enableAutoDiscovery,
  27587. include: typingOptionstypeAcquisition.include,
  27588. exclude: typingOptionstypeAcquisition.exclude
  27589. } :
  27590. typingOptionstypeAcquisition;
  27591. }
  27592. else {
  27593. typeAcquisition = getDefaultTypeAcquisition(configFileName);
  27594. }
  27595. }
  27596. return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
  27597. }
  27598. function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
  27599. extendedConfig = ts.normalizeSlashes(extendedConfig);
  27600. if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
  27601. var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
  27602. if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
  27603. extendedConfigPath = extendedConfigPath + ".json";
  27604. if (!host.fileExists(extendedConfigPath)) {
  27605. errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
  27606. return undefined;
  27607. }
  27608. }
  27609. return extendedConfigPath;
  27610. }
  27611. // If the path isn't a rooted or relative path, resolve like a module
  27612. var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
  27613. if (resolved.resolvedModule) {
  27614. return resolved.resolvedModule.resolvedFileName;
  27615. }
  27616. errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
  27617. return undefined;
  27618. }
  27619. function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
  27620. var _a;
  27621. var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
  27622. var value;
  27623. var extendedResult;
  27624. var extendedConfig;
  27625. if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
  27626. (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
  27627. }
  27628. else {
  27629. extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
  27630. if (!extendedResult.parseDiagnostics.length) {
  27631. var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
  27632. extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
  27633. if (isSuccessfulParsedTsconfig(extendedConfig)) {
  27634. // Update the paths to reflect base path
  27635. var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
  27636. var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
  27637. var mapPropertiesInRawIfNotUndefined = function (propertyName) {
  27638. if (raw_2[propertyName]) {
  27639. raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
  27640. }
  27641. };
  27642. var raw_2 = extendedConfig.raw;
  27643. mapPropertiesInRawIfNotUndefined("include");
  27644. mapPropertiesInRawIfNotUndefined("exclude");
  27645. mapPropertiesInRawIfNotUndefined("files");
  27646. }
  27647. }
  27648. if (extendedConfigCache) {
  27649. extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
  27650. }
  27651. }
  27652. if (sourceFile) {
  27653. sourceFile.extendedSourceFiles = [extendedResult.fileName];
  27654. if (extendedResult.extendedSourceFiles) {
  27655. (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
  27656. }
  27657. }
  27658. if (extendedResult.parseDiagnostics.length) {
  27659. errors.push.apply(errors, extendedResult.parseDiagnostics);
  27660. return undefined;
  27661. }
  27662. return extendedConfig;
  27663. }
  27664. function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
  27665. if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
  27666. return false;
  27667. }
  27668. var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
  27669. return typeof result === "boolean" && result;
  27670. }
  27671. function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
  27672. var errors = [];
  27673. var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
  27674. return { options: options, errors: errors };
  27675. }
  27676. ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
  27677. function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
  27678. var errors = [];
  27679. var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
  27680. return { options: options, errors: errors };
  27681. }
  27682. ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
  27683. function getDefaultCompilerOptions(configFileName) {
  27684. var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
  27685. ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
  27686. : {};
  27687. return options;
  27688. }
  27689. function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
  27690. var options = getDefaultCompilerOptions(configFileName);
  27691. convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
  27692. if (configFileName) {
  27693. options.configFilePath = ts.normalizeSlashes(configFileName);
  27694. }
  27695. return options;
  27696. }
  27697. function getDefaultTypeAcquisition(configFileName) {
  27698. return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
  27699. }
  27700. function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
  27701. var options = getDefaultTypeAcquisition(configFileName);
  27702. var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
  27703. convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
  27704. return options;
  27705. }
  27706. function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
  27707. return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
  27708. }
  27709. function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
  27710. if (!jsonOptions) {
  27711. return;
  27712. }
  27713. for (var id in jsonOptions) {
  27714. var opt = optionsNameMap.get(id);
  27715. if (opt) {
  27716. (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
  27717. }
  27718. else {
  27719. errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
  27720. }
  27721. }
  27722. return defaultOptions;
  27723. }
  27724. function convertJsonOption(opt, value, basePath, errors) {
  27725. if (isCompilerOptionsValue(opt, value)) {
  27726. var optType = opt.type;
  27727. if (optType === "list" && ts.isArray(value)) {
  27728. return convertJsonOptionOfListType(opt, value, basePath, errors);
  27729. }
  27730. else if (!ts.isString(optType)) {
  27731. return convertJsonOptionOfCustomType(opt, value, errors);
  27732. }
  27733. return normalizeNonListOptionValue(opt, basePath, value);
  27734. }
  27735. else {
  27736. errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
  27737. }
  27738. }
  27739. function normalizeOptionValue(option, basePath, value) {
  27740. if (isNullOrUndefined(value))
  27741. return undefined;
  27742. if (option.type === "list") {
  27743. var listOption_1 = option;
  27744. if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
  27745. return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
  27746. }
  27747. return value;
  27748. }
  27749. else if (!ts.isString(option.type)) {
  27750. return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
  27751. }
  27752. return normalizeNonListOptionValue(option, basePath, value);
  27753. }
  27754. function normalizeNonListOptionValue(option, basePath, value) {
  27755. if (option.isFilePath) {
  27756. value = ts.getNormalizedAbsolutePath(value, basePath);
  27757. if (value === "") {
  27758. value = ".";
  27759. }
  27760. }
  27761. return value;
  27762. }
  27763. function convertJsonOptionOfCustomType(opt, value, errors) {
  27764. if (isNullOrUndefined(value))
  27765. return undefined;
  27766. var key = value.toLowerCase();
  27767. var val = opt.type.get(key);
  27768. if (val !== undefined) {
  27769. return val;
  27770. }
  27771. else {
  27772. errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
  27773. }
  27774. }
  27775. function convertJsonOptionOfListType(option, values, basePath, errors) {
  27776. return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
  27777. }
  27778. function trimString(s) {
  27779. return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
  27780. }
  27781. /**
  27782. * Tests for a path that ends in a recursive directory wildcard.
  27783. * Matches **, \**, **\, and \**\, but not a**b.
  27784. *
  27785. * NOTE: used \ in place of / above to avoid issues with multiline comments.
  27786. *
  27787. * Breakdown:
  27788. * (^|\/) # matches either the beginning of the string or a directory separator.
  27789. * \*\* # matches the recursive directory wildcard "**".
  27790. * \/?$ # matches an optional trailing directory separator at the end of the string.
  27791. */
  27792. var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
  27793. /**
  27794. * Tests for a path where .. appears after a recursive directory wildcard.
  27795. * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
  27796. *
  27797. * NOTE: used \ in place of / above to avoid issues with multiline comments.
  27798. *
  27799. * Breakdown:
  27800. * (^|\/) # matches either the beginning of the string or a directory separator.
  27801. * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator.
  27802. * (.*\/)? # optionally matches any number of characters followed by a directory separator.
  27803. * \.\. # matches a parent directory path component ".."
  27804. * ($|\/) # matches either the end of the string or a directory separator.
  27805. */
  27806. var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
  27807. /**
  27808. * Tests for a path containing a wildcard character in a directory component of the path.
  27809. * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
  27810. *
  27811. * NOTE: used \ in place of / above to avoid issues with multiline comments.
  27812. *
  27813. * Breakdown:
  27814. * \/ # matches a directory separator.
  27815. * [^/]*? # matches any number of characters excluding directory separators (non-greedy).
  27816. * [*?] # matches either a wildcard character (* or ?)
  27817. * [^/]* # matches any number of characters excluding directory separators (greedy).
  27818. * \/ # matches a directory separator.
  27819. */
  27820. var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
  27821. /**
  27822. * Matches the portion of a wildcard path that does not contain wildcards.
  27823. * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
  27824. *
  27825. * NOTE: used \ in place of / above to avoid issues with multiline comments.
  27826. *
  27827. * Breakdown:
  27828. * ^ # matches the beginning of the string
  27829. * [^*?]* # matches any number of non-wildcard characters
  27830. * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by
  27831. * # a path component that contains at least one wildcard character (* or ?).
  27832. */
  27833. var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
  27834. /**
  27835. * Expands an array of file specifications.
  27836. *
  27837. * @param filesSpecs The literal file names to include.
  27838. * @param includeSpecs The wildcard file specifications to include.
  27839. * @param excludeSpecs The wildcard file specifications to exclude.
  27840. * @param basePath The base path for any relative file specifications.
  27841. * @param options Compiler options.
  27842. * @param host The host used to resolve files and directories.
  27843. * @param errors An array for diagnostic reporting.
  27844. */
  27845. function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
  27846. basePath = ts.normalizePath(basePath);
  27847. var validatedIncludeSpecs, validatedExcludeSpecs;
  27848. // The exclude spec list is converted into a regular expression, which allows us to quickly
  27849. // test whether a file or directory should be excluded before recursively traversing the
  27850. // file system.
  27851. if (includeSpecs) {
  27852. validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
  27853. }
  27854. if (excludeSpecs) {
  27855. validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
  27856. }
  27857. // Wildcard directories (provided as part of a wildcard path) are stored in a
  27858. // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
  27859. // or a recursive directory. This information is used by filesystem watchers to monitor for
  27860. // new entries in these paths.
  27861. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
  27862. var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
  27863. return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
  27864. }
  27865. /**
  27866. * Gets the file names from the provided config file specs that contain, files, include, exclude and
  27867. * other properties needed to resolve the file names
  27868. * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
  27869. * @param basePath The base path for any relative file specifications.
  27870. * @param options Compiler options.
  27871. * @param host The host used to resolve files and directories.
  27872. * @param extraFileExtensions optionaly file extra file extension information from host
  27873. */
  27874. /* @internal */
  27875. function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
  27876. if (extraFileExtensions === void 0) { extraFileExtensions = []; }
  27877. basePath = ts.normalizePath(basePath);
  27878. var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  27879. // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
  27880. // file map with a possibly case insensitive key. We use this map later when when including
  27881. // wildcard paths.
  27882. var literalFileMap = ts.createMap();
  27883. // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
  27884. // file map with a possibly case insensitive key. We use this map to store paths matched
  27885. // via wildcard, and to handle extension priority.
  27886. var wildcardFileMap = ts.createMap();
  27887. // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
  27888. // file map with a possibly case insensitive key. We use this map to store paths matched
  27889. // via wildcard of *.json kind
  27890. var wildCardJsonFileMap = ts.createMap();
  27891. var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
  27892. // Rather than requery this for each file and filespec, we query the supported extensions
  27893. // once and store it on the expansion context.
  27894. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
  27895. var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
  27896. // Literal files are always included verbatim. An "include" or "exclude" specification cannot
  27897. // remove a literal file.
  27898. if (filesSpecs) {
  27899. for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
  27900. var fileName = filesSpecs_1[_i];
  27901. var file = ts.getNormalizedAbsolutePath(fileName, basePath);
  27902. literalFileMap.set(keyMapper(file), file);
  27903. }
  27904. }
  27905. var jsonOnlyIncludeRegexes;
  27906. if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
  27907. var _loop_5 = function (file) {
  27908. if (ts.fileExtensionIs(file, ".json" /* Json */)) {
  27909. // Valid only if *.json specified
  27910. if (!jsonOnlyIncludeRegexes) {
  27911. var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
  27912. var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
  27913. jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
  27914. }
  27915. var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
  27916. if (includeIndex !== -1) {
  27917. var key_1 = keyMapper(file);
  27918. if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
  27919. wildCardJsonFileMap.set(key_1, file);
  27920. }
  27921. }
  27922. return "continue";
  27923. }
  27924. // If we have already included a literal or wildcard path with a
  27925. // higher priority extension, we should skip this file.
  27926. //
  27927. // This handles cases where we may encounter both <file>.ts and
  27928. // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
  27929. // directory when they are compilation outputs.
  27930. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
  27931. return "continue";
  27932. }
  27933. // We may have included a wildcard path with a lower priority
  27934. // extension due to the user-defined order of entries in the
  27935. // "include" array. If there is a lower priority extension in the
  27936. // same directory, we should remove it.
  27937. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
  27938. var key = keyMapper(file);
  27939. if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
  27940. wildcardFileMap.set(key, file);
  27941. }
  27942. };
  27943. for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
  27944. var file = _b[_a];
  27945. _loop_5(file);
  27946. }
  27947. }
  27948. var literalFiles = ts.arrayFrom(literalFileMap.values());
  27949. var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
  27950. return {
  27951. fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
  27952. wildcardDirectories: wildcardDirectories,
  27953. spec: spec
  27954. };
  27955. }
  27956. ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
  27957. function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
  27958. return specs.filter(function (spec) {
  27959. var diag = specToDiagnostic(spec, allowTrailingRecursion);
  27960. if (diag !== undefined) {
  27961. errors.push(createDiagnostic(diag, spec));
  27962. }
  27963. return diag === undefined;
  27964. });
  27965. function createDiagnostic(message, spec) {
  27966. var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
  27967. return element ?
  27968. ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
  27969. ts.createCompilerDiagnostic(message, spec);
  27970. }
  27971. }
  27972. function specToDiagnostic(spec, allowTrailingRecursion) {
  27973. if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
  27974. return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
  27975. }
  27976. else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
  27977. return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
  27978. }
  27979. }
  27980. /**
  27981. * Gets directories in a set of include patterns that should be watched for changes.
  27982. */
  27983. function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
  27984. // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
  27985. // of the pattern:
  27986. //
  27987. // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively
  27988. // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
  27989. // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler
  27990. //
  27991. // We watch a directory without recursion if it contains a wildcard in the file segment of
  27992. // the pattern:
  27993. //
  27994. // /a/b/* - Watch /a/b directly to catch any new file
  27995. // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
  27996. var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
  27997. var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
  27998. var wildcardDirectories = {};
  27999. if (include !== undefined) {
  28000. var recursiveKeys = [];
  28001. for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
  28002. var file = include_1[_i];
  28003. var spec = ts.normalizePath(ts.combinePaths(path, file));
  28004. if (excludeRegex && excludeRegex.test(spec)) {
  28005. continue;
  28006. }
  28007. var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
  28008. if (match) {
  28009. var key = match.key, flags = match.flags;
  28010. var existingFlags = wildcardDirectories[key];
  28011. if (existingFlags === undefined || existingFlags < flags) {
  28012. wildcardDirectories[key] = flags;
  28013. if (flags === 1 /* Recursive */) {
  28014. recursiveKeys.push(key);
  28015. }
  28016. }
  28017. }
  28018. }
  28019. // Remove any subpaths under an existing recursively watched directory.
  28020. for (var key in wildcardDirectories) {
  28021. if (ts.hasProperty(wildcardDirectories, key)) {
  28022. for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
  28023. var recursiveKey = recursiveKeys_1[_a];
  28024. if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
  28025. delete wildcardDirectories[key];
  28026. }
  28027. }
  28028. }
  28029. }
  28030. }
  28031. return wildcardDirectories;
  28032. }
  28033. function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
  28034. var match = wildcardDirectoryPattern.exec(spec);
  28035. if (match) {
  28036. return {
  28037. key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
  28038. flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
  28039. };
  28040. }
  28041. if (ts.isImplicitGlob(spec)) {
  28042. return { key: spec, flags: 1 /* Recursive */ };
  28043. }
  28044. return undefined;
  28045. }
  28046. /**
  28047. * Determines whether a literal or wildcard file has already been included that has a higher
  28048. * extension priority.
  28049. *
  28050. * @param file The path to the file.
  28051. * @param extensionPriority The priority of the extension.
  28052. * @param context The expansion context.
  28053. */
  28054. function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
  28055. var extensionPriority = ts.getExtensionPriority(file, extensions);
  28056. var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
  28057. for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
  28058. var higherPriorityExtension = extensions[i];
  28059. var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
  28060. if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
  28061. return true;
  28062. }
  28063. }
  28064. return false;
  28065. }
  28066. /**
  28067. * Removes files included via wildcard expansion with a lower extension priority that have
  28068. * already been included.
  28069. *
  28070. * @param file The path to the file.
  28071. * @param extensionPriority The priority of the extension.
  28072. * @param context The expansion context.
  28073. */
  28074. function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
  28075. var extensionPriority = ts.getExtensionPriority(file, extensions);
  28076. var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
  28077. for (var i = nextExtensionPriority; i < extensions.length; i++) {
  28078. var lowerPriorityExtension = extensions[i];
  28079. var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
  28080. wildcardFiles.delete(lowerPriorityPath);
  28081. }
  28082. }
  28083. /**
  28084. * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
  28085. * Also converts enum values back to strings.
  28086. */
  28087. /* @internal */
  28088. function convertCompilerOptionsForTelemetry(opts) {
  28089. var out = {};
  28090. for (var key in opts) {
  28091. if (opts.hasOwnProperty(key)) {
  28092. var type = getOptionFromName(key);
  28093. if (type !== undefined) { // Ignore unknown options
  28094. out[key] = getOptionValueWithEmptyStrings(opts[key], type);
  28095. }
  28096. }
  28097. }
  28098. return out;
  28099. }
  28100. ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
  28101. function getOptionValueWithEmptyStrings(value, option) {
  28102. switch (option.type) {
  28103. case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
  28104. return "";
  28105. case "string": // Could be any arbitrary string -- use empty string instead.
  28106. return "";
  28107. case "number": // Allow numbers, but be sure to check it's actually a number.
  28108. return typeof value === "number" ? value : "";
  28109. case "boolean":
  28110. return typeof value === "boolean" ? value : "";
  28111. case "list":
  28112. var elementType_1 = option.element;
  28113. return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
  28114. default:
  28115. return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
  28116. if (optionEnumValue === value) {
  28117. return optionStringValue;
  28118. }
  28119. }); // TODO: GH#18217
  28120. }
  28121. }
  28122. })(ts || (ts = {}));
  28123. var ts;
  28124. (function (ts) {
  28125. function trace(host) {
  28126. host.trace(ts.formatMessage.apply(undefined, arguments));
  28127. }
  28128. ts.trace = trace;
  28129. /* @internal */
  28130. function isTraceEnabled(compilerOptions, host) {
  28131. return !!compilerOptions.traceResolution && host.trace !== undefined;
  28132. }
  28133. ts.isTraceEnabled = isTraceEnabled;
  28134. function withPackageId(packageInfo, r) {
  28135. var packageId;
  28136. if (r && packageInfo) {
  28137. var packageJsonContent = packageInfo.packageJsonContent;
  28138. if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
  28139. packageId = {
  28140. name: packageJsonContent.name,
  28141. subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
  28142. version: packageJsonContent.version
  28143. };
  28144. }
  28145. }
  28146. return r && { path: r.path, extension: r.ext, packageId: packageId };
  28147. }
  28148. function noPackageId(r) {
  28149. return withPackageId(/*packageInfo*/ undefined, r);
  28150. }
  28151. function removeIgnoredPackageId(r) {
  28152. if (r) {
  28153. ts.Debug.assert(r.packageId === undefined);
  28154. return { path: r.path, ext: r.extension };
  28155. }
  28156. }
  28157. /**
  28158. * Kinds of file that we are currently looking for.
  28159. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
  28160. */
  28161. var Extensions;
  28162. (function (Extensions) {
  28163. Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
  28164. Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
  28165. Extensions[Extensions["Json"] = 2] = "Json";
  28166. Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
  28167. Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
  28168. })(Extensions || (Extensions = {}));
  28169. /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
  28170. function resolvedTypeScriptOnly(resolved) {
  28171. if (!resolved) {
  28172. return undefined;
  28173. }
  28174. ts.Debug.assert(ts.extensionIsTS(resolved.extension));
  28175. return { fileName: resolved.path, packageId: resolved.packageId };
  28176. }
  28177. function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) {
  28178. return {
  28179. resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
  28180. failedLookupLocations: failedLookupLocations
  28181. };
  28182. }
  28183. function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
  28184. if (!ts.hasProperty(jsonContent, fieldName)) {
  28185. if (state.traceEnabled) {
  28186. trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
  28187. }
  28188. return;
  28189. }
  28190. var value = jsonContent[fieldName];
  28191. if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
  28192. if (state.traceEnabled) {
  28193. // eslint-disable-next-line no-null/no-null
  28194. trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
  28195. }
  28196. return;
  28197. }
  28198. return value;
  28199. }
  28200. function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
  28201. var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
  28202. if (fileName === undefined) {
  28203. return;
  28204. }
  28205. if (!fileName) {
  28206. if (state.traceEnabled) {
  28207. trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
  28208. }
  28209. return;
  28210. }
  28211. var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
  28212. if (state.traceEnabled) {
  28213. trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
  28214. }
  28215. return path;
  28216. }
  28217. function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
  28218. return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
  28219. || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
  28220. }
  28221. function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
  28222. return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
  28223. }
  28224. function readPackageJsonMainField(jsonContent, baseDirectory, state) {
  28225. return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
  28226. }
  28227. function readPackageJsonTypesVersionsField(jsonContent, state) {
  28228. var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
  28229. if (typesVersions === undefined)
  28230. return;
  28231. if (state.traceEnabled) {
  28232. trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
  28233. }
  28234. return typesVersions;
  28235. }
  28236. function readPackageJsonTypesVersionPaths(jsonContent, state) {
  28237. var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
  28238. if (typesVersions === undefined)
  28239. return;
  28240. if (state.traceEnabled) {
  28241. for (var key in typesVersions) {
  28242. if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
  28243. trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
  28244. }
  28245. }
  28246. }
  28247. var result = getPackageJsonTypesVersionsPaths(typesVersions);
  28248. if (!result) {
  28249. if (state.traceEnabled) {
  28250. trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
  28251. }
  28252. return;
  28253. }
  28254. var bestVersionKey = result.version, bestVersionPaths = result.paths;
  28255. if (typeof bestVersionPaths !== "object") {
  28256. if (state.traceEnabled) {
  28257. trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
  28258. }
  28259. return;
  28260. }
  28261. return result;
  28262. }
  28263. var typeScriptVersion;
  28264. /* @internal */
  28265. function getPackageJsonTypesVersionsPaths(typesVersions) {
  28266. if (!typeScriptVersion)
  28267. typeScriptVersion = new ts.Version(ts.version);
  28268. for (var key in typesVersions) {
  28269. if (!ts.hasProperty(typesVersions, key))
  28270. continue;
  28271. var keyRange = ts.VersionRange.tryParse(key);
  28272. if (keyRange === undefined) {
  28273. continue;
  28274. }
  28275. // return the first entry whose range matches the current compiler version.
  28276. if (keyRange.test(typeScriptVersion)) {
  28277. return { version: key, paths: typesVersions[key] };
  28278. }
  28279. }
  28280. }
  28281. ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
  28282. function getEffectiveTypeRoots(options, host) {
  28283. if (options.typeRoots) {
  28284. return options.typeRoots;
  28285. }
  28286. var currentDirectory;
  28287. if (options.configFilePath) {
  28288. currentDirectory = ts.getDirectoryPath(options.configFilePath);
  28289. }
  28290. else if (host.getCurrentDirectory) {
  28291. currentDirectory = host.getCurrentDirectory();
  28292. }
  28293. if (currentDirectory !== undefined) {
  28294. return getDefaultTypeRoots(currentDirectory, host);
  28295. }
  28296. }
  28297. ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
  28298. /**
  28299. * Returns the path to every node_modules/@types directory from some ancestor directory.
  28300. * Returns undefined if there are none.
  28301. */
  28302. function getDefaultTypeRoots(currentDirectory, host) {
  28303. if (!host.directoryExists) {
  28304. return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
  28305. // And if it doesn't exist, tough.
  28306. }
  28307. var typeRoots;
  28308. ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
  28309. var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
  28310. if (host.directoryExists(atTypes)) {
  28311. (typeRoots || (typeRoots = [])).push(atTypes);
  28312. }
  28313. return undefined;
  28314. });
  28315. return typeRoots;
  28316. }
  28317. var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
  28318. /**
  28319. * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
  28320. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
  28321. * is assumed to be the same as root directory of the project.
  28322. */
  28323. function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
  28324. var traceEnabled = isTraceEnabled(options, host);
  28325. if (redirectedReference) {
  28326. options = redirectedReference.commandLine.options;
  28327. }
  28328. var failedLookupLocations = [];
  28329. var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
  28330. var typeRoots = getEffectiveTypeRoots(options, host);
  28331. if (traceEnabled) {
  28332. if (containingFile === undefined) {
  28333. if (typeRoots === undefined) {
  28334. trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
  28335. }
  28336. else {
  28337. trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
  28338. }
  28339. }
  28340. else {
  28341. if (typeRoots === undefined) {
  28342. trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
  28343. }
  28344. else {
  28345. trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
  28346. }
  28347. }
  28348. if (redirectedReference) {
  28349. trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
  28350. }
  28351. }
  28352. var resolved = primaryLookup();
  28353. var primary = true;
  28354. if (!resolved) {
  28355. resolved = secondaryLookup();
  28356. primary = false;
  28357. }
  28358. var resolvedTypeReferenceDirective;
  28359. if (resolved) {
  28360. var fileName = resolved.fileName, packageId = resolved.packageId;
  28361. var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
  28362. if (traceEnabled) {
  28363. if (packageId) {
  28364. trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary);
  28365. }
  28366. else {
  28367. trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
  28368. }
  28369. }
  28370. resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
  28371. }
  28372. return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
  28373. function primaryLookup() {
  28374. // Check primary library paths
  28375. if (typeRoots && typeRoots.length) {
  28376. if (traceEnabled) {
  28377. trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
  28378. }
  28379. return ts.firstDefined(typeRoots, function (typeRoot) {
  28380. var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
  28381. var candidateDirectory = ts.getDirectoryPath(candidate);
  28382. var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
  28383. if (!directoryExists && traceEnabled) {
  28384. trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
  28385. }
  28386. return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
  28387. });
  28388. }
  28389. else {
  28390. if (traceEnabled) {
  28391. trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
  28392. }
  28393. }
  28394. }
  28395. function secondaryLookup() {
  28396. var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
  28397. if (initialLocationForSecondaryLookup !== undefined) {
  28398. // check secondary locations
  28399. if (traceEnabled) {
  28400. trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
  28401. }
  28402. var result = void 0;
  28403. if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
  28404. var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
  28405. result = searchResult && searchResult.value;
  28406. }
  28407. else {
  28408. var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
  28409. result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
  28410. }
  28411. var resolvedFile = resolvedTypeScriptOnly(result);
  28412. if (!resolvedFile && traceEnabled) {
  28413. trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
  28414. }
  28415. return resolvedFile;
  28416. }
  28417. else {
  28418. if (traceEnabled) {
  28419. trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
  28420. }
  28421. }
  28422. }
  28423. }
  28424. ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
  28425. /**
  28426. * Given a set of options, returns the set of type directive names
  28427. * that should be included for this program automatically.
  28428. * This list could either come from the config file,
  28429. * or from enumerating the types root + initial secondary types lookup location.
  28430. * More type directives might appear in the program later as a result of loading actual source files;
  28431. * this list is only the set of defaults that are implicitly included.
  28432. */
  28433. function getAutomaticTypeDirectiveNames(options, host) {
  28434. // Use explicit type list from tsconfig.json
  28435. if (options.types) {
  28436. return options.types;
  28437. }
  28438. // Walk the primary type lookup locations
  28439. var result = [];
  28440. if (host.directoryExists && host.getDirectories) {
  28441. var typeRoots = getEffectiveTypeRoots(options, host);
  28442. if (typeRoots) {
  28443. for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
  28444. var root = typeRoots_1[_i];
  28445. if (host.directoryExists(root)) {
  28446. for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
  28447. var typeDirectivePath = _b[_a];
  28448. var normalized = ts.normalizePath(typeDirectivePath);
  28449. var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
  28450. // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
  28451. // See `createNotNeededPackageJSON` in the types-publisher` repo.
  28452. // eslint-disable-next-line no-null/no-null
  28453. var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
  28454. if (!isNotNeededPackage) {
  28455. var baseFileName = ts.getBaseFileName(normalized);
  28456. // At this stage, skip results with leading dot.
  28457. if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
  28458. // Return just the type directive names
  28459. result.push(baseFileName);
  28460. }
  28461. }
  28462. }
  28463. }
  28464. }
  28465. }
  28466. }
  28467. return result;
  28468. }
  28469. ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
  28470. function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
  28471. return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
  28472. }
  28473. ts.createModuleResolutionCache = createModuleResolutionCache;
  28474. /*@internal*/
  28475. function createCacheWithRedirects(options) {
  28476. var ownMap = ts.createMap();
  28477. var redirectsMap = ts.createMap();
  28478. return {
  28479. ownMap: ownMap,
  28480. redirectsMap: redirectsMap,
  28481. getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
  28482. clear: clear,
  28483. setOwnOptions: setOwnOptions,
  28484. setOwnMap: setOwnMap
  28485. };
  28486. function setOwnOptions(newOptions) {
  28487. options = newOptions;
  28488. }
  28489. function setOwnMap(newOwnMap) {
  28490. ownMap = newOwnMap;
  28491. }
  28492. function getOrCreateMapOfCacheRedirects(redirectedReference) {
  28493. if (!redirectedReference) {
  28494. return ownMap;
  28495. }
  28496. var path = redirectedReference.sourceFile.path;
  28497. var redirects = redirectsMap.get(path);
  28498. if (!redirects) {
  28499. // Reuse map if redirected reference map uses same resolution
  28500. redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
  28501. redirectsMap.set(path, redirects);
  28502. }
  28503. return redirects;
  28504. }
  28505. function clear() {
  28506. ownMap.clear();
  28507. redirectsMap.clear();
  28508. }
  28509. }
  28510. ts.createCacheWithRedirects = createCacheWithRedirects;
  28511. /*@internal*/
  28512. function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
  28513. return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
  28514. function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
  28515. var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
  28516. return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
  28517. }
  28518. function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
  28519. ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
  28520. return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
  28521. }
  28522. function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
  28523. var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
  28524. var result = cache.get(key);
  28525. if (!result) {
  28526. result = create();
  28527. cache.set(key, result);
  28528. }
  28529. return result;
  28530. }
  28531. function createPerModuleNameCache() {
  28532. var directoryPathMap = ts.createMap();
  28533. return { get: get, set: set };
  28534. function get(directory) {
  28535. return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
  28536. }
  28537. /**
  28538. * At first this function add entry directory -> module resolution result to the table.
  28539. * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
  28540. * and for every parent folder in set it adds entry: parent -> module resolution. .
  28541. * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
  28542. * Set of parent folders that should have the same result will be:
  28543. * [
  28544. * /a/b/c/d, /a/b/c, /a/b
  28545. * ]
  28546. * this means that request for module resolution from file in any of these folder will be immediately found in cache.
  28547. */
  28548. function set(directory, result) {
  28549. var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
  28550. // if entry is already in cache do nothing
  28551. if (directoryPathMap.has(path)) {
  28552. return;
  28553. }
  28554. directoryPathMap.set(path, result);
  28555. var resolvedFileName = result.resolvedModule &&
  28556. (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
  28557. // find common prefix between directory and resolved file name
  28558. // this common prefix should be the shortest path that has the same resolution
  28559. // directory: /a/b/c/d/e
  28560. // resolvedFileName: /a/b/foo.d.ts
  28561. // commonPrefix: /a/b
  28562. // for failed lookups cache the result for every directory up to root
  28563. var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
  28564. var current = path;
  28565. while (current !== commonPrefix) {
  28566. var parent = ts.getDirectoryPath(current);
  28567. if (parent === current || directoryPathMap.has(parent)) {
  28568. break;
  28569. }
  28570. directoryPathMap.set(parent, result);
  28571. current = parent;
  28572. }
  28573. }
  28574. function getCommonPrefix(directory, resolution) {
  28575. var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
  28576. // find first position where directory and resolution differs
  28577. var i = 0;
  28578. var limit = Math.min(directory.length, resolutionDirectory.length);
  28579. while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
  28580. i++;
  28581. }
  28582. if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
  28583. return directory;
  28584. }
  28585. var rootLength = ts.getRootLength(directory);
  28586. if (i < rootLength) {
  28587. return undefined;
  28588. }
  28589. var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
  28590. if (sep === -1) {
  28591. return undefined;
  28592. }
  28593. return directory.substr(0, Math.max(sep, rootLength));
  28594. }
  28595. }
  28596. }
  28597. ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
  28598. function resolveModuleNameFromCache(moduleName, containingFile, cache) {
  28599. var containingDirectory = ts.getDirectoryPath(containingFile);
  28600. var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
  28601. return perFolderCache && perFolderCache.get(moduleName);
  28602. }
  28603. ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
  28604. function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
  28605. var traceEnabled = isTraceEnabled(compilerOptions, host);
  28606. if (redirectedReference) {
  28607. compilerOptions = redirectedReference.commandLine.options;
  28608. }
  28609. if (traceEnabled) {
  28610. trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
  28611. if (redirectedReference) {
  28612. trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
  28613. }
  28614. }
  28615. var containingDirectory = ts.getDirectoryPath(containingFile);
  28616. var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
  28617. var result = perFolderCache && perFolderCache.get(moduleName);
  28618. if (result) {
  28619. if (traceEnabled) {
  28620. trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
  28621. }
  28622. }
  28623. else {
  28624. var moduleResolution = compilerOptions.moduleResolution;
  28625. if (moduleResolution === undefined) {
  28626. moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
  28627. if (traceEnabled) {
  28628. trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
  28629. }
  28630. }
  28631. else {
  28632. if (traceEnabled) {
  28633. trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
  28634. }
  28635. }
  28636. ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
  28637. switch (moduleResolution) {
  28638. case ts.ModuleResolutionKind.NodeJs:
  28639. result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
  28640. break;
  28641. case ts.ModuleResolutionKind.Classic:
  28642. result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
  28643. break;
  28644. default:
  28645. return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
  28646. }
  28647. if (result && result.resolvedModule)
  28648. ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
  28649. ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
  28650. if (perFolderCache) {
  28651. perFolderCache.set(moduleName, result);
  28652. if (!ts.isExternalModuleNameRelative(moduleName)) {
  28653. // put result in per-module name cache
  28654. cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
  28655. }
  28656. }
  28657. }
  28658. if (traceEnabled) {
  28659. if (result.resolvedModule) {
  28660. if (result.resolvedModule.packageId) {
  28661. trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, ts.packageIdToString(result.resolvedModule.packageId));
  28662. }
  28663. else {
  28664. trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
  28665. }
  28666. }
  28667. else {
  28668. trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
  28669. }
  28670. }
  28671. return result;
  28672. }
  28673. ts.resolveModuleName = resolveModuleName;
  28674. /**
  28675. * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
  28676. * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
  28677. * can be resolved successfully by TypeScript compiler and runtime module loader.
  28678. * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
  28679. * fallback to standard resolution routine.
  28680. *
  28681. * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
  28682. * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
  28683. * be '/a/b/c/d'
  28684. * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
  28685. * will be resolved based on the content of the module name.
  28686. * Structure of 'paths' compiler options
  28687. * 'paths': {
  28688. * pattern-1: [...substitutions],
  28689. * pattern-2: [...substitutions],
  28690. * ...
  28691. * pattern-n: [...substitutions]
  28692. * }
  28693. * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
  28694. * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
  28695. * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
  28696. * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
  28697. * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
  28698. * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
  28699. * from the candidate location.
  28700. * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
  28701. * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
  28702. * will be converted to absolute using baseUrl.
  28703. * For example:
  28704. * baseUrl: /a/b/c
  28705. * "paths": {
  28706. * // match all module names
  28707. * "*": [
  28708. * "*", // use matched name as is,
  28709. * // <matched name> will be looked as /a/b/c/<matched name>
  28710. *
  28711. * "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
  28712. * // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
  28713. * ],
  28714. * // match module names that start with 'components/'
  28715. * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
  28716. * // it is rooted so it will be final candidate location
  28717. * }
  28718. *
  28719. * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
  28720. * they were in the same location. For example lets say there are two files
  28721. * '/local/src/content/file1.ts'
  28722. * '/shared/components/contracts/src/content/protocols/file2.ts'
  28723. * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
  28724. * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
  28725. * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
  28726. * root dirs were merged together.
  28727. * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
  28728. * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
  28729. * '/local/src/content/protocols/file2' and try to load it - failure.
  28730. * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
  28731. * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
  28732. * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
  28733. */
  28734. function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
  28735. var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
  28736. if (resolved)
  28737. return resolved.value;
  28738. if (!ts.isExternalModuleNameRelative(moduleName)) {
  28739. return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
  28740. }
  28741. else {
  28742. return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
  28743. }
  28744. }
  28745. function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
  28746. var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
  28747. if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
  28748. if (state.traceEnabled) {
  28749. trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
  28750. trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
  28751. }
  28752. return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
  28753. }
  28754. }
  28755. function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
  28756. if (!state.compilerOptions.rootDirs) {
  28757. return undefined;
  28758. }
  28759. if (state.traceEnabled) {
  28760. trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
  28761. }
  28762. var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
  28763. var matchedRootDir;
  28764. var matchedNormalizedPrefix;
  28765. for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
  28766. var rootDir = _a[_i];
  28767. // rootDirs are expected to be absolute
  28768. // in case of tsconfig.json this will happen automatically - compiler will expand relative names
  28769. // using location of tsconfig.json as base location
  28770. var normalizedRoot = ts.normalizePath(rootDir);
  28771. if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
  28772. normalizedRoot += ts.directorySeparator;
  28773. }
  28774. var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
  28775. (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
  28776. if (state.traceEnabled) {
  28777. trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
  28778. }
  28779. if (isLongestMatchingPrefix) {
  28780. matchedNormalizedPrefix = normalizedRoot;
  28781. matchedRootDir = rootDir;
  28782. }
  28783. }
  28784. if (matchedNormalizedPrefix) {
  28785. if (state.traceEnabled) {
  28786. trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
  28787. }
  28788. var suffix = candidate.substr(matchedNormalizedPrefix.length);
  28789. // first - try to load from a initial location
  28790. if (state.traceEnabled) {
  28791. trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
  28792. }
  28793. var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
  28794. if (resolvedFileName) {
  28795. return resolvedFileName;
  28796. }
  28797. if (state.traceEnabled) {
  28798. trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
  28799. }
  28800. // then try to resolve using remaining entries in rootDirs
  28801. for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
  28802. var rootDir = _c[_b];
  28803. if (rootDir === matchedRootDir) {
  28804. // skip the initially matched entry
  28805. continue;
  28806. }
  28807. var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
  28808. if (state.traceEnabled) {
  28809. trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
  28810. }
  28811. var baseDirectory = ts.getDirectoryPath(candidate_1);
  28812. var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
  28813. if (resolvedFileName_1) {
  28814. return resolvedFileName_1;
  28815. }
  28816. }
  28817. if (state.traceEnabled) {
  28818. trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
  28819. }
  28820. }
  28821. return undefined;
  28822. }
  28823. function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
  28824. var baseUrl = state.compilerOptions.baseUrl;
  28825. if (!baseUrl) {
  28826. return undefined;
  28827. }
  28828. if (state.traceEnabled) {
  28829. trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
  28830. }
  28831. var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
  28832. if (state.traceEnabled) {
  28833. trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
  28834. }
  28835. return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
  28836. }
  28837. /**
  28838. * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
  28839. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
  28840. * Throws an error if the module can't be resolved.
  28841. */
  28842. /* @internal */
  28843. function resolveJSModule(moduleName, initialDir, host) {
  28844. var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
  28845. if (!resolvedModule) {
  28846. throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
  28847. }
  28848. return resolvedModule.resolvedFileName;
  28849. }
  28850. ts.resolveJSModule = resolveJSModule;
  28851. /* @internal */
  28852. function tryResolveJSModule(moduleName, initialDir, host) {
  28853. var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
  28854. return resolvedModule && resolvedModule.resolvedFileName;
  28855. }
  28856. ts.tryResolveJSModule = tryResolveJSModule;
  28857. var jsOnlyExtensions = [Extensions.JavaScript];
  28858. var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
  28859. var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
  28860. var tsconfigExtensions = [Extensions.TSConfig];
  28861. function tryResolveJSModuleWorker(moduleName, initialDir, host) {
  28862. return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
  28863. }
  28864. function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
  28865. return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
  28866. }
  28867. ts.nodeModuleNameResolver = nodeModuleNameResolver;
  28868. function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
  28869. var traceEnabled = isTraceEnabled(compilerOptions, host);
  28870. var failedLookupLocations = [];
  28871. var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
  28872. var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
  28873. if (result && result.value) {
  28874. var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport;
  28875. return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations);
  28876. }
  28877. return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
  28878. function tryResolve(extensions) {
  28879. var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
  28880. var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
  28881. if (resolved) {
  28882. return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
  28883. }
  28884. if (!ts.isExternalModuleNameRelative(moduleName)) {
  28885. if (traceEnabled) {
  28886. trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
  28887. }
  28888. var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
  28889. if (!resolved_1)
  28890. return undefined;
  28891. var resolvedValue = resolved_1.value;
  28892. if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
  28893. var path = realPath(resolvedValue.path, host, traceEnabled);
  28894. var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
  28895. resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
  28896. }
  28897. // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
  28898. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
  28899. }
  28900. else {
  28901. var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
  28902. var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
  28903. // Treat explicit "node_modules" import as an external library import.
  28904. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
  28905. }
  28906. }
  28907. }
  28908. function realPath(path, host, traceEnabled) {
  28909. if (!host.realpath) {
  28910. return path;
  28911. }
  28912. var real = ts.normalizePath(host.realpath(path));
  28913. if (traceEnabled) {
  28914. trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
  28915. }
  28916. ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
  28917. return real;
  28918. }
  28919. function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
  28920. if (state.traceEnabled) {
  28921. trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
  28922. }
  28923. if (!ts.hasTrailingDirectorySeparator(candidate)) {
  28924. if (!onlyRecordFailures) {
  28925. var parentOfCandidate = ts.getDirectoryPath(candidate);
  28926. if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
  28927. if (state.traceEnabled) {
  28928. trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
  28929. }
  28930. onlyRecordFailures = true;
  28931. }
  28932. }
  28933. var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
  28934. if (resolvedFromFile) {
  28935. var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
  28936. var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
  28937. return withPackageId(packageInfo, resolvedFromFile);
  28938. }
  28939. }
  28940. if (!onlyRecordFailures) {
  28941. var candidateExists = ts.directoryProbablyExists(candidate, state.host);
  28942. if (!candidateExists) {
  28943. if (state.traceEnabled) {
  28944. trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
  28945. }
  28946. onlyRecordFailures = true;
  28947. }
  28948. }
  28949. return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
  28950. }
  28951. /*@internal*/
  28952. ts.nodeModulesPathPart = "/node_modules/";
  28953. /*@internal*/
  28954. function pathContainsNodeModules(path) {
  28955. return ts.stringContains(path, ts.nodeModulesPathPart);
  28956. }
  28957. ts.pathContainsNodeModules = pathContainsNodeModules;
  28958. /**
  28959. * This will be called on the successfully resolved path from `loadModuleFromFile`.
  28960. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
  28961. *
  28962. * packageDirectory is the directory of the package itself.
  28963. * For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
  28964. * For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
  28965. * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
  28966. * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
  28967. */
  28968. function parseNodeModuleFromPath(resolved) {
  28969. var path = ts.normalizePath(resolved.path);
  28970. var idx = path.lastIndexOf(ts.nodeModulesPathPart);
  28971. if (idx === -1) {
  28972. return undefined;
  28973. }
  28974. var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
  28975. var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
  28976. if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
  28977. indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
  28978. }
  28979. return path.slice(0, indexAfterPackageName);
  28980. }
  28981. function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
  28982. var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
  28983. return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
  28984. }
  28985. function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
  28986. return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
  28987. }
  28988. /**
  28989. * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
  28990. * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
  28991. */
  28992. function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
  28993. if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
  28994. var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
  28995. return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
  28996. }
  28997. // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
  28998. var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
  28999. if (resolvedByAddingExtension) {
  29000. return resolvedByAddingExtension;
  29001. }
  29002. // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
  29003. // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
  29004. if (ts.hasJSFileExtension(candidate)) {
  29005. var extensionless = ts.removeFileExtension(candidate);
  29006. if (state.traceEnabled) {
  29007. var extension = candidate.substring(extensionless.length);
  29008. trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
  29009. }
  29010. return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
  29011. }
  29012. }
  29013. /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
  29014. function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
  29015. if (!onlyRecordFailures) {
  29016. // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
  29017. var directory = ts.getDirectoryPath(candidate);
  29018. if (directory) {
  29019. onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
  29020. }
  29021. }
  29022. switch (extensions) {
  29023. case Extensions.DtsOnly:
  29024. return tryExtension(".d.ts" /* Dts */);
  29025. case Extensions.TypeScript:
  29026. return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
  29027. case Extensions.JavaScript:
  29028. return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
  29029. case Extensions.TSConfig:
  29030. case Extensions.Json:
  29031. return tryExtension(".json" /* Json */);
  29032. }
  29033. function tryExtension(ext) {
  29034. var path = tryFile(candidate + ext, onlyRecordFailures, state);
  29035. return path === undefined ? undefined : { path: path, ext: ext };
  29036. }
  29037. }
  29038. /** Return the file if it exists. */
  29039. function tryFile(fileName, onlyRecordFailures, state) {
  29040. if (!onlyRecordFailures) {
  29041. if (state.host.fileExists(fileName)) {
  29042. if (state.traceEnabled) {
  29043. trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
  29044. }
  29045. return fileName;
  29046. }
  29047. else {
  29048. if (state.traceEnabled) {
  29049. trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
  29050. }
  29051. }
  29052. }
  29053. state.failedLookupLocations.push(fileName);
  29054. return undefined;
  29055. }
  29056. function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
  29057. if (considerPackageJson === void 0) { considerPackageJson = true; }
  29058. var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
  29059. var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
  29060. var versionPaths = packageInfo && packageInfo.versionPaths;
  29061. return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
  29062. }
  29063. function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
  29064. var host = state.host, traceEnabled = state.traceEnabled;
  29065. var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
  29066. var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
  29067. if (directoryExists && host.fileExists(packageJsonPath)) {
  29068. var packageJsonContent = ts.readJson(packageJsonPath, host);
  29069. if (traceEnabled) {
  29070. trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
  29071. }
  29072. var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
  29073. return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
  29074. }
  29075. else {
  29076. if (directoryExists && traceEnabled) {
  29077. trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
  29078. }
  29079. // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
  29080. state.failedLookupLocations.push(packageJsonPath);
  29081. }
  29082. }
  29083. function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
  29084. var packageFile;
  29085. if (jsonContent) {
  29086. switch (extensions) {
  29087. case Extensions.JavaScript:
  29088. case Extensions.Json:
  29089. packageFile = readPackageJsonMainField(jsonContent, candidate, state);
  29090. break;
  29091. case Extensions.TypeScript:
  29092. // When resolving typescript modules, try resolving using main field as well
  29093. packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
  29094. break;
  29095. case Extensions.DtsOnly:
  29096. packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
  29097. break;
  29098. case Extensions.TSConfig:
  29099. packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
  29100. break;
  29101. default:
  29102. return ts.Debug.assertNever(extensions);
  29103. }
  29104. }
  29105. var loader = function (extensions, candidate, onlyRecordFailures, state) {
  29106. var fromFile = tryFile(candidate, onlyRecordFailures, state);
  29107. if (fromFile) {
  29108. var resolved = resolvedIfExtensionMatches(extensions, fromFile);
  29109. if (resolved) {
  29110. return noPackageId(resolved);
  29111. }
  29112. if (state.traceEnabled) {
  29113. trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
  29114. }
  29115. }
  29116. // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
  29117. var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
  29118. // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
  29119. return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
  29120. };
  29121. var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
  29122. var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
  29123. var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
  29124. if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
  29125. var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
  29126. if (state.traceEnabled) {
  29127. trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName);
  29128. }
  29129. var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
  29130. if (result) {
  29131. return removeIgnoredPackageId(result.value);
  29132. }
  29133. }
  29134. // It won't have a `packageId` set, because we disabled `considerPackageJson`.
  29135. var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
  29136. if (packageFileResult)
  29137. return packageFileResult;
  29138. return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
  29139. }
  29140. /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
  29141. function resolvedIfExtensionMatches(extensions, path) {
  29142. var ext = ts.tryGetExtensionFromPath(path);
  29143. return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
  29144. }
  29145. /** True if `extension` is one of the supported `extensions`. */
  29146. function extensionIsOk(extensions, extension) {
  29147. switch (extensions) {
  29148. case Extensions.JavaScript:
  29149. return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
  29150. case Extensions.TSConfig:
  29151. case Extensions.Json:
  29152. return extension === ".json" /* Json */;
  29153. case Extensions.TypeScript:
  29154. return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
  29155. case Extensions.DtsOnly:
  29156. return extension === ".d.ts" /* Dts */;
  29157. }
  29158. }
  29159. /* @internal */
  29160. function parsePackageName(moduleName) {
  29161. var idx = moduleName.indexOf(ts.directorySeparator);
  29162. if (moduleName[0] === "@") {
  29163. idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
  29164. }
  29165. return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
  29166. }
  29167. ts.parsePackageName = parsePackageName;
  29168. function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
  29169. return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
  29170. }
  29171. function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
  29172. // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
  29173. return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
  29174. }
  29175. function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
  29176. var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
  29177. return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
  29178. if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
  29179. var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
  29180. if (resolutionFromCache) {
  29181. return resolutionFromCache;
  29182. }
  29183. return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
  29184. }
  29185. });
  29186. }
  29187. function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
  29188. var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
  29189. var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
  29190. if (!nodeModulesFolderExists && state.traceEnabled) {
  29191. trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
  29192. }
  29193. var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
  29194. if (packageResult) {
  29195. return packageResult;
  29196. }
  29197. if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
  29198. var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
  29199. var nodeModulesAtTypesExists = nodeModulesFolderExists;
  29200. if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
  29201. if (state.traceEnabled) {
  29202. trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
  29203. }
  29204. nodeModulesAtTypesExists = false;
  29205. }
  29206. return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
  29207. }
  29208. }
  29209. function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
  29210. var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
  29211. // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
  29212. var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
  29213. if (packageInfo) {
  29214. var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
  29215. if (fromFile) {
  29216. return noPackageId(fromFile);
  29217. }
  29218. var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
  29219. return withPackageId(packageInfo, fromDirectory);
  29220. }
  29221. var loader = function (extensions, candidate, onlyRecordFailures, state) {
  29222. var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
  29223. loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
  29224. return withPackageId(packageInfo, pathAndExtension);
  29225. };
  29226. var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
  29227. if (rest !== "") { // If "rest" is empty, we just did this search above.
  29228. var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
  29229. // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
  29230. packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
  29231. if (packageInfo && packageInfo.versionPaths) {
  29232. if (state.traceEnabled) {
  29233. trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
  29234. }
  29235. var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
  29236. var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
  29237. if (fromPaths) {
  29238. return fromPaths.value;
  29239. }
  29240. }
  29241. }
  29242. return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
  29243. }
  29244. function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
  29245. var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
  29246. if (matchedPattern) {
  29247. var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
  29248. var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
  29249. if (state.traceEnabled) {
  29250. trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
  29251. }
  29252. var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
  29253. var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
  29254. var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
  29255. if (state.traceEnabled) {
  29256. trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
  29257. }
  29258. // A path mapping may have an extension, in contrast to an import, which should omit it.
  29259. var extension = ts.tryGetExtensionFromPath(candidate);
  29260. if (extension !== undefined) {
  29261. var path_1 = tryFile(candidate, onlyRecordFailures, state);
  29262. if (path_1 !== undefined) {
  29263. return noPackageId({ path: path_1, ext: extension });
  29264. }
  29265. }
  29266. return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
  29267. });
  29268. return { value: resolved };
  29269. }
  29270. }
  29271. /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
  29272. var mangledScopedPackageSeparator = "__";
  29273. /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
  29274. function mangleScopedPackageNameWithTrace(packageName, state) {
  29275. var mangled = mangleScopedPackageName(packageName);
  29276. if (state.traceEnabled && mangled !== packageName) {
  29277. trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
  29278. }
  29279. return mangled;
  29280. }
  29281. /* @internal */
  29282. function getTypesPackageName(packageName) {
  29283. return "@types/" + mangleScopedPackageName(packageName);
  29284. }
  29285. ts.getTypesPackageName = getTypesPackageName;
  29286. /* @internal */
  29287. function mangleScopedPackageName(packageName) {
  29288. if (ts.startsWith(packageName, "@")) {
  29289. var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
  29290. if (replaceSlash !== packageName) {
  29291. return replaceSlash.slice(1); // Take off the "@"
  29292. }
  29293. }
  29294. return packageName;
  29295. }
  29296. ts.mangleScopedPackageName = mangleScopedPackageName;
  29297. /* @internal */
  29298. function getPackageNameFromTypesPackageName(mangledName) {
  29299. var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
  29300. if (withoutAtTypePrefix !== mangledName) {
  29301. return unmangleScopedPackageName(withoutAtTypePrefix);
  29302. }
  29303. return mangledName;
  29304. }
  29305. ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
  29306. /* @internal */
  29307. function unmangleScopedPackageName(typesPackageName) {
  29308. return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
  29309. "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
  29310. typesPackageName;
  29311. }
  29312. ts.unmangleScopedPackageName = unmangleScopedPackageName;
  29313. function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
  29314. var _a;
  29315. var result = cache && cache.get(containingDirectory);
  29316. if (result) {
  29317. if (state.traceEnabled) {
  29318. trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
  29319. }
  29320. (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations);
  29321. return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
  29322. }
  29323. }
  29324. function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
  29325. var traceEnabled = isTraceEnabled(compilerOptions, host);
  29326. var failedLookupLocations = [];
  29327. var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
  29328. var containingDirectory = ts.getDirectoryPath(containingFile);
  29329. var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
  29330. // No originalPath because classic resolution doesn't resolve realPath
  29331. return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations);
  29332. function tryResolve(extensions) {
  29333. var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
  29334. if (resolvedUsingSettings) {
  29335. return { value: resolvedUsingSettings };
  29336. }
  29337. if (!ts.isExternalModuleNameRelative(moduleName)) {
  29338. var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
  29339. // Climb up parent directories looking for a module.
  29340. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
  29341. var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
  29342. if (resolutionFromCache) {
  29343. return resolutionFromCache;
  29344. }
  29345. var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
  29346. return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
  29347. });
  29348. if (resolved_3) {
  29349. return resolved_3;
  29350. }
  29351. if (extensions === Extensions.TypeScript) {
  29352. // If we didn't find the file normally, look it up in @types.
  29353. return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
  29354. }
  29355. }
  29356. else {
  29357. var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
  29358. return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
  29359. }
  29360. }
  29361. }
  29362. ts.classicNameResolver = classicNameResolver;
  29363. /**
  29364. * A host may load a module from a global cache of typings.
  29365. * This is the minumum code needed to expose that functionality; the rest is in the host.
  29366. */
  29367. /* @internal */
  29368. function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
  29369. var traceEnabled = isTraceEnabled(compilerOptions, host);
  29370. if (traceEnabled) {
  29371. trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
  29372. }
  29373. var failedLookupLocations = [];
  29374. var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
  29375. var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
  29376. return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
  29377. }
  29378. ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
  29379. /**
  29380. * Wraps value to SearchResult.
  29381. * @returns undefined if value is undefined or { value } otherwise
  29382. */
  29383. function toSearchResult(value) {
  29384. return value !== undefined ? { value: value } : undefined;
  29385. }
  29386. })(ts || (ts = {}));
  29387. /* @internal */
  29388. var ts;
  29389. (function (ts) {
  29390. var ModuleInstanceState;
  29391. (function (ModuleInstanceState) {
  29392. ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
  29393. ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
  29394. ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
  29395. })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
  29396. function getModuleInstanceState(node, visited) {
  29397. if (node.body && !node.body.parent) {
  29398. // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
  29399. setParentPointers(node, node.body);
  29400. }
  29401. return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
  29402. }
  29403. ts.getModuleInstanceState = getModuleInstanceState;
  29404. function getModuleInstanceStateCached(node, visited) {
  29405. if (visited === void 0) { visited = ts.createMap(); }
  29406. var nodeId = "" + ts.getNodeId(node);
  29407. if (visited.has(nodeId)) {
  29408. return visited.get(nodeId) || 0 /* NonInstantiated */;
  29409. }
  29410. visited.set(nodeId, undefined);
  29411. var result = getModuleInstanceStateWorker(node, visited);
  29412. visited.set(nodeId, result);
  29413. return result;
  29414. }
  29415. function getModuleInstanceStateWorker(node, visited) {
  29416. // A module is uninstantiated if it contains only
  29417. switch (node.kind) {
  29418. // 1. interface declarations, type alias declarations
  29419. case 246 /* InterfaceDeclaration */:
  29420. case 247 /* TypeAliasDeclaration */:
  29421. return 0 /* NonInstantiated */;
  29422. // 2. const enum declarations
  29423. case 248 /* EnumDeclaration */:
  29424. if (ts.isEnumConst(node)) {
  29425. return 2 /* ConstEnumOnly */;
  29426. }
  29427. break;
  29428. // 3. non-exported import declarations
  29429. case 254 /* ImportDeclaration */:
  29430. case 253 /* ImportEqualsDeclaration */:
  29431. if (!(ts.hasModifier(node, 1 /* Export */))) {
  29432. return 0 /* NonInstantiated */;
  29433. }
  29434. break;
  29435. // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
  29436. case 260 /* ExportDeclaration */:
  29437. var exportDeclaration = node;
  29438. if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
  29439. var state = 0 /* NonInstantiated */;
  29440. for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
  29441. var specifier = _a[_i];
  29442. var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
  29443. if (specifierState > state) {
  29444. state = specifierState;
  29445. }
  29446. if (state === 1 /* Instantiated */) {
  29447. return state;
  29448. }
  29449. }
  29450. return state;
  29451. }
  29452. break;
  29453. // 5. other uninstantiated module declarations.
  29454. case 250 /* ModuleBlock */: {
  29455. var state_1 = 0 /* NonInstantiated */;
  29456. ts.forEachChild(node, function (n) {
  29457. var childState = getModuleInstanceStateCached(n, visited);
  29458. switch (childState) {
  29459. case 0 /* NonInstantiated */:
  29460. // child is non-instantiated - continue searching
  29461. return;
  29462. case 2 /* ConstEnumOnly */:
  29463. // child is const enum only - record state and continue searching
  29464. state_1 = 2 /* ConstEnumOnly */;
  29465. return;
  29466. case 1 /* Instantiated */:
  29467. // child is instantiated - record state and stop
  29468. state_1 = 1 /* Instantiated */;
  29469. return true;
  29470. default:
  29471. ts.Debug.assertNever(childState);
  29472. }
  29473. });
  29474. return state_1;
  29475. }
  29476. case 249 /* ModuleDeclaration */:
  29477. return getModuleInstanceState(node, visited);
  29478. case 75 /* Identifier */:
  29479. // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
  29480. // be considered the same as type alias
  29481. if (node.isInJSDocNamespace) {
  29482. return 0 /* NonInstantiated */;
  29483. }
  29484. }
  29485. return 1 /* Instantiated */;
  29486. }
  29487. function getModuleInstanceStateForAliasTarget(specifier, visited) {
  29488. var name = specifier.propertyName || specifier.name;
  29489. var p = specifier.parent;
  29490. while (p) {
  29491. if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
  29492. var statements = p.statements;
  29493. var found = void 0;
  29494. for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
  29495. var statement = statements_1[_i];
  29496. if (ts.nodeHasName(statement, name)) {
  29497. if (!statement.parent) {
  29498. setParentPointers(p, statement);
  29499. }
  29500. var state = getModuleInstanceStateCached(statement, visited);
  29501. if (found === undefined || state > found) {
  29502. found = state;
  29503. }
  29504. if (found === 1 /* Instantiated */) {
  29505. return found;
  29506. }
  29507. }
  29508. }
  29509. if (found !== undefined) {
  29510. return found;
  29511. }
  29512. }
  29513. p = p.parent;
  29514. }
  29515. return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
  29516. }
  29517. var ContainerFlags;
  29518. (function (ContainerFlags) {
  29519. // The current node is not a container, and no container manipulation should happen before
  29520. // recursing into it.
  29521. ContainerFlags[ContainerFlags["None"] = 0] = "None";
  29522. // The current node is a container. It should be set as the current container (and block-
  29523. // container) before recursing into it. The current node does not have locals. Examples:
  29524. //
  29525. // Classes, ObjectLiterals, TypeLiterals, Interfaces...
  29526. ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
  29527. // The current node is a block-scoped-container. It should be set as the current block-
  29528. // container before recursing into it. Examples:
  29529. //
  29530. // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
  29531. ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
  29532. // The current node is the container of a control flow path. The current control flow should
  29533. // be saved and restored, and a new control flow initialized within the container.
  29534. ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
  29535. ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
  29536. ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
  29537. ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
  29538. ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
  29539. ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
  29540. })(ContainerFlags || (ContainerFlags = {}));
  29541. function initFlowNode(node) {
  29542. ts.Debug.attachFlowNodeDebugInfo(node);
  29543. return node;
  29544. }
  29545. var binder = createBinder();
  29546. function bindSourceFile(file, options) {
  29547. ts.performance.mark("beforeBind");
  29548. ts.perfLogger.logStartBindFile("" + file.fileName);
  29549. binder(file, options);
  29550. ts.perfLogger.logStopBindFile();
  29551. ts.performance.mark("afterBind");
  29552. ts.performance.measure("Bind", "beforeBind", "afterBind");
  29553. }
  29554. ts.bindSourceFile = bindSourceFile;
  29555. function createBinder() {
  29556. var file;
  29557. var options;
  29558. var languageVersion;
  29559. var parent;
  29560. var container;
  29561. var thisParentContainer; // Container one level up
  29562. var blockScopeContainer;
  29563. var lastContainer;
  29564. var delayedTypeAliases;
  29565. var seenThisKeyword;
  29566. // state used by control flow analysis
  29567. var currentFlow;
  29568. var currentBreakTarget;
  29569. var currentContinueTarget;
  29570. var currentReturnTarget;
  29571. var currentTrueTarget;
  29572. var currentFalseTarget;
  29573. var currentExceptionTarget;
  29574. var preSwitchCaseFlow;
  29575. var activeLabelList;
  29576. var hasExplicitReturn;
  29577. // state used for emit helpers
  29578. var emitFlags;
  29579. // If this file is an external module, then it is automatically in strict-mode according to
  29580. // ES6. If it is not an external module, then we'll determine if it is in strict mode or
  29581. // not depending on if we see "use strict" in certain places or if we hit a class/namespace
  29582. // or if compiler options contain alwaysStrict.
  29583. var inStrictMode;
  29584. var symbolCount = 0;
  29585. var Symbol;
  29586. var classifiableNames;
  29587. var unreachableFlow = { flags: 1 /* Unreachable */ };
  29588. var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
  29589. // state used to aggregate transform flags during bind.
  29590. var subtreeTransformFlags = 0 /* None */;
  29591. var skipTransformFlagAggregation;
  29592. /**
  29593. * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
  29594. * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
  29595. * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
  29596. */
  29597. function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
  29598. return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
  29599. }
  29600. function bindSourceFile(f, opts) {
  29601. file = f;
  29602. options = opts;
  29603. languageVersion = ts.getEmitScriptTarget(options);
  29604. inStrictMode = bindInStrictMode(file, opts);
  29605. classifiableNames = ts.createUnderscoreEscapedMap();
  29606. symbolCount = 0;
  29607. skipTransformFlagAggregation = file.isDeclarationFile;
  29608. Symbol = ts.objectAllocator.getSymbolConstructor();
  29609. // Attach debugging information if necessary
  29610. ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
  29611. ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
  29612. if (!file.locals) {
  29613. bind(file);
  29614. file.symbolCount = symbolCount;
  29615. file.classifiableNames = classifiableNames;
  29616. delayedBindJSDocTypedefTag();
  29617. }
  29618. file = undefined;
  29619. options = undefined;
  29620. languageVersion = undefined;
  29621. parent = undefined;
  29622. container = undefined;
  29623. thisParentContainer = undefined;
  29624. blockScopeContainer = undefined;
  29625. lastContainer = undefined;
  29626. delayedTypeAliases = undefined;
  29627. seenThisKeyword = false;
  29628. currentFlow = undefined;
  29629. currentBreakTarget = undefined;
  29630. currentContinueTarget = undefined;
  29631. currentReturnTarget = undefined;
  29632. currentTrueTarget = undefined;
  29633. currentFalseTarget = undefined;
  29634. currentExceptionTarget = undefined;
  29635. activeLabelList = undefined;
  29636. hasExplicitReturn = false;
  29637. emitFlags = 0 /* None */;
  29638. subtreeTransformFlags = 0 /* None */;
  29639. }
  29640. return bindSourceFile;
  29641. function bindInStrictMode(file, opts) {
  29642. if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
  29643. // bind in strict mode source files with alwaysStrict option
  29644. return true;
  29645. }
  29646. else {
  29647. return !!file.externalModuleIndicator;
  29648. }
  29649. }
  29650. function createSymbol(flags, name) {
  29651. symbolCount++;
  29652. return new Symbol(flags, name);
  29653. }
  29654. function addDeclarationToSymbol(symbol, node, symbolFlags) {
  29655. symbol.flags |= symbolFlags;
  29656. node.symbol = symbol;
  29657. symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
  29658. if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
  29659. symbol.exports = ts.createSymbolTable();
  29660. }
  29661. if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
  29662. symbol.members = ts.createSymbolTable();
  29663. }
  29664. // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
  29665. if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
  29666. symbol.constEnumOnlyModule = false;
  29667. }
  29668. if (symbolFlags & 111551 /* Value */) {
  29669. setValueDeclaration(symbol, node);
  29670. }
  29671. }
  29672. function setValueDeclaration(symbol, node) {
  29673. var valueDeclaration = symbol.valueDeclaration;
  29674. if (!valueDeclaration ||
  29675. (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) ||
  29676. (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) {
  29677. // other kinds of value declarations take precedence over modules and assignment declarations
  29678. symbol.valueDeclaration = node;
  29679. }
  29680. }
  29681. // Should not be called on a declaration with a computed property name,
  29682. // unless it is a well known Symbol.
  29683. function getDeclarationName(node) {
  29684. if (node.kind === 259 /* ExportAssignment */) {
  29685. return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
  29686. }
  29687. var name = ts.getNameOfDeclaration(node);
  29688. if (name) {
  29689. if (ts.isAmbientModule(node)) {
  29690. var moduleName = ts.getTextOfIdentifierOrLiteral(name);
  29691. return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
  29692. }
  29693. if (name.kind === 154 /* ComputedPropertyName */) {
  29694. var nameExpression = name.expression;
  29695. // treat computed property names where expression is string/numeric literal as just string/numeric literal
  29696. if (ts.isStringOrNumericLiteralLike(nameExpression)) {
  29697. return ts.escapeLeadingUnderscores(nameExpression.text);
  29698. }
  29699. if (ts.isSignedNumericLiteral(nameExpression)) {
  29700. return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
  29701. }
  29702. ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
  29703. return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
  29704. }
  29705. if (ts.isWellKnownSymbolSyntactically(name)) {
  29706. return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
  29707. }
  29708. if (ts.isPrivateIdentifier(name)) {
  29709. // containingClass exists because private names only allowed inside classes
  29710. var containingClass = ts.getContainingClass(node);
  29711. if (!containingClass) {
  29712. // we can get here in cases where there is already a parse error.
  29713. return undefined;
  29714. }
  29715. var containingClassSymbol = containingClass.symbol;
  29716. return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
  29717. }
  29718. return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
  29719. }
  29720. switch (node.kind) {
  29721. case 162 /* Constructor */:
  29722. return "__constructor" /* Constructor */;
  29723. case 170 /* FunctionType */:
  29724. case 165 /* CallSignature */:
  29725. case 305 /* JSDocSignature */:
  29726. return "__call" /* Call */;
  29727. case 171 /* ConstructorType */:
  29728. case 166 /* ConstructSignature */:
  29729. return "__new" /* New */;
  29730. case 167 /* IndexSignature */:
  29731. return "__index" /* Index */;
  29732. case 260 /* ExportDeclaration */:
  29733. return "__export" /* ExportStar */;
  29734. case 290 /* SourceFile */:
  29735. // json file should behave as
  29736. // module.exports = ...
  29737. return "export=" /* ExportEquals */;
  29738. case 209 /* BinaryExpression */:
  29739. if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
  29740. // module.exports = ...
  29741. return "export=" /* ExportEquals */;
  29742. }
  29743. ts.Debug.fail("Unknown binary declaration kind");
  29744. break;
  29745. case 300 /* JSDocFunctionType */:
  29746. return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
  29747. case 156 /* Parameter */:
  29748. // Parameters with names are handled at the top of this function. Parameters
  29749. // without names can only come from JSDocFunctionTypes.
  29750. ts.Debug.assert(node.parent.kind === 300 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
  29751. var functionType = node.parent;
  29752. var index = functionType.parameters.indexOf(node);
  29753. return "arg" + index;
  29754. }
  29755. }
  29756. function getDisplayName(node) {
  29757. return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node)));
  29758. }
  29759. /**
  29760. * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
  29761. * @param symbolTable - The symbol table which node will be added to.
  29762. * @param parent - node's parent declaration.
  29763. * @param node - The declaration to be added to the symbol table
  29764. * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
  29765. * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
  29766. */
  29767. function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
  29768. ts.Debug.assert(!ts.hasDynamicName(node));
  29769. var isDefaultExport = ts.hasModifier(node, 512 /* Default */);
  29770. // The exported symbol for an export default function/class node is always named "default"
  29771. var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
  29772. var symbol;
  29773. if (name === undefined) {
  29774. symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
  29775. }
  29776. else {
  29777. // Check and see if the symbol table already has a symbol with this name. If not,
  29778. // create a new symbol with this name and add it to the table. Note that we don't
  29779. // give the new symbol any flags *yet*. This ensures that it will not conflict
  29780. // with the 'excludes' flags we pass in.
  29781. //
  29782. // If we do get an existing symbol, see if it conflicts with the new symbol we're
  29783. // creating. For example, a 'var' symbol and a 'class' symbol will conflict within
  29784. // the same symbol table. If we have a conflict, report the issue on each
  29785. // declaration we have for this symbol, and then create a new symbol for this
  29786. // declaration.
  29787. //
  29788. // Note that when properties declared in Javascript constructors
  29789. // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
  29790. // Always. This allows the common Javascript pattern of overwriting a prototype method
  29791. // with an bound instance method of the same type: `this.method = this.method.bind(this)`
  29792. //
  29793. // If we created a new symbol, either because we didn't have a symbol with this name
  29794. // in the symbol table, or we conflicted with an existing symbol, then just add this
  29795. // node as the sole declaration of the new symbol.
  29796. //
  29797. // Otherwise, we'll be merging into a compatible existing symbol (for example when
  29798. // you have multiple 'vars' with the same name in the same container). In this case
  29799. // just add this node into the declarations list of the symbol.
  29800. symbol = symbolTable.get(name);
  29801. if (includes & 2885600 /* Classifiable */) {
  29802. classifiableNames.set(name, true);
  29803. }
  29804. if (!symbol) {
  29805. symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
  29806. if (isReplaceableByMethod)
  29807. symbol.isReplaceableByMethod = true;
  29808. }
  29809. else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
  29810. // A symbol already exists, so don't add this as a declaration.
  29811. return symbol;
  29812. }
  29813. else if (symbol.flags & excludes) {
  29814. if (symbol.isReplaceableByMethod) {
  29815. // Javascript constructor-declared symbols can be discarded in favor of
  29816. // prototype symbols like methods.
  29817. symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
  29818. }
  29819. else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
  29820. // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
  29821. if (ts.isNamedDeclaration(node)) {
  29822. node.name.parent = node;
  29823. }
  29824. // Report errors every position with duplicate declaration
  29825. // Report errors on previous encountered declarations
  29826. var message_1 = symbol.flags & 2 /* BlockScopedVariable */
  29827. ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
  29828. : ts.Diagnostics.Duplicate_identifier_0;
  29829. var messageNeedsName_1 = true;
  29830. if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
  29831. message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
  29832. messageNeedsName_1 = false;
  29833. }
  29834. var multipleDefaultExports_1 = false;
  29835. if (ts.length(symbol.declarations)) {
  29836. // If the current node is a default export of some sort, then check if
  29837. // there are any other default exports that we need to error on.
  29838. // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
  29839. if (isDefaultExport) {
  29840. message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
  29841. messageNeedsName_1 = false;
  29842. multipleDefaultExports_1 = true;
  29843. }
  29844. else {
  29845. // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
  29846. // Error on multiple export default in the following case:
  29847. // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
  29848. // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
  29849. if (symbol.declarations && symbol.declarations.length &&
  29850. (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
  29851. message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
  29852. messageNeedsName_1 = false;
  29853. multipleDefaultExports_1 = true;
  29854. }
  29855. }
  29856. }
  29857. var relatedInformation_1 = [];
  29858. if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
  29859. // export type T; - may have meant export type { T }?
  29860. relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
  29861. }
  29862. var declarationName_1 = ts.getNameOfDeclaration(node) || node;
  29863. ts.forEach(symbol.declarations, function (declaration, index) {
  29864. var decl = ts.getNameOfDeclaration(declaration) || declaration;
  29865. var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
  29866. file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
  29867. if (multipleDefaultExports_1) {
  29868. relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
  29869. }
  29870. });
  29871. var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
  29872. file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
  29873. symbol = createSymbol(0 /* None */, name);
  29874. }
  29875. }
  29876. }
  29877. addDeclarationToSymbol(symbol, node, includes);
  29878. if (symbol.parent) {
  29879. ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
  29880. }
  29881. else {
  29882. symbol.parent = parent;
  29883. }
  29884. return symbol;
  29885. }
  29886. function declareModuleMember(node, symbolFlags, symbolExcludes) {
  29887. var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
  29888. if (symbolFlags & 2097152 /* Alias */) {
  29889. if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
  29890. return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
  29891. }
  29892. else {
  29893. return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
  29894. }
  29895. }
  29896. else {
  29897. // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
  29898. // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
  29899. //
  29900. // 1. We treat locals and exports of the same name as mutually exclusive within a container.
  29901. // That means the binder will issue a Duplicate Identifier error if you mix locals and exports
  29902. // with the same name in the same container.
  29903. // TODO: Make this a more specific error and decouple it from the exclusion logic.
  29904. // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
  29905. // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
  29906. // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
  29907. // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
  29908. // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
  29909. // and this case is specially handled. Module augmentations should only be merged with original module definition
  29910. // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
  29911. if (ts.isJSDocTypeAlias(node))
  29912. ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
  29913. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
  29914. if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
  29915. return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
  29916. }
  29917. var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
  29918. var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
  29919. local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
  29920. node.localSymbol = local;
  29921. return local;
  29922. }
  29923. else {
  29924. return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
  29925. }
  29926. }
  29927. }
  29928. // All container nodes are kept on a linked list in declaration order. This list is used by
  29929. // the getLocalNameOfContainer function in the type checker to validate that the local name
  29930. // used for a container is unique.
  29931. function bindContainer(node, containerFlags) {
  29932. // Before we recurse into a node's children, we first save the existing parent, container
  29933. // and block-container. Then after we pop out of processing the children, we restore
  29934. // these saved values.
  29935. var saveContainer = container;
  29936. var saveThisParentContainer = thisParentContainer;
  29937. var savedBlockScopeContainer = blockScopeContainer;
  29938. // Depending on what kind of node this is, we may have to adjust the current container
  29939. // and block-container. If the current node is a container, then it is automatically
  29940. // considered the current block-container as well. Also, for containers that we know
  29941. // may contain locals, we eagerly initialize the .locals field. We do this because
  29942. // it's highly likely that the .locals will be needed to place some child in (for example,
  29943. // a parameter, or variable declaration).
  29944. //
  29945. // However, we do not proactively create the .locals for block-containers because it's
  29946. // totally normal and common for block-containers to never actually have a block-scoped
  29947. // variable in them. We don't want to end up allocating an object for every 'block' we
  29948. // run into when most of them won't be necessary.
  29949. //
  29950. // Finally, if this is a block-container, then we clear out any existing .locals object
  29951. // it may contain within it. This happens in incremental scenarios. Because we can be
  29952. // reusing a node from a previous compilation, that node may have had 'locals' created
  29953. // for it. We must clear this so we don't accidentally move any stale data forward from
  29954. // a previous compilation.
  29955. if (containerFlags & 1 /* IsContainer */) {
  29956. if (node.kind !== 202 /* ArrowFunction */) {
  29957. thisParentContainer = container;
  29958. }
  29959. container = blockScopeContainer = node;
  29960. if (containerFlags & 32 /* HasLocals */) {
  29961. container.locals = ts.createSymbolTable();
  29962. }
  29963. addToContainerChain(container);
  29964. }
  29965. else if (containerFlags & 2 /* IsBlockScopedContainer */) {
  29966. blockScopeContainer = node;
  29967. blockScopeContainer.locals = undefined;
  29968. }
  29969. if (containerFlags & 4 /* IsControlFlowContainer */) {
  29970. var saveCurrentFlow = currentFlow;
  29971. var saveBreakTarget = currentBreakTarget;
  29972. var saveContinueTarget = currentContinueTarget;
  29973. var saveReturnTarget = currentReturnTarget;
  29974. var saveExceptionTarget = currentExceptionTarget;
  29975. var saveActiveLabelList = activeLabelList;
  29976. var saveHasExplicitReturn = hasExplicitReturn;
  29977. var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
  29978. !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
  29979. // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
  29980. // similarly to break statements that exit to a label just past the statement body.
  29981. if (!isIIFE) {
  29982. currentFlow = initFlowNode({ flags: 2 /* Start */ });
  29983. if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
  29984. currentFlow.node = node;
  29985. }
  29986. }
  29987. // We create a return control flow graph for IIFEs and constructors. For constructors
  29988. // we use the return control flow graph in strict property initialization checks.
  29989. currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
  29990. currentExceptionTarget = undefined;
  29991. currentBreakTarget = undefined;
  29992. currentContinueTarget = undefined;
  29993. activeLabelList = undefined;
  29994. hasExplicitReturn = false;
  29995. bindChildren(node);
  29996. // Reset all reachability check related flags on node (for incremental scenarios)
  29997. node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
  29998. if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
  29999. node.flags |= 256 /* HasImplicitReturn */;
  30000. if (hasExplicitReturn)
  30001. node.flags |= 512 /* HasExplicitReturn */;
  30002. node.endFlowNode = currentFlow;
  30003. }
  30004. if (node.kind === 290 /* SourceFile */) {
  30005. node.flags |= emitFlags;
  30006. }
  30007. if (currentReturnTarget) {
  30008. addAntecedent(currentReturnTarget, currentFlow);
  30009. currentFlow = finishFlowLabel(currentReturnTarget);
  30010. if (node.kind === 162 /* Constructor */) {
  30011. node.returnFlowNode = currentFlow;
  30012. }
  30013. }
  30014. if (!isIIFE) {
  30015. currentFlow = saveCurrentFlow;
  30016. }
  30017. currentBreakTarget = saveBreakTarget;
  30018. currentContinueTarget = saveContinueTarget;
  30019. currentReturnTarget = saveReturnTarget;
  30020. currentExceptionTarget = saveExceptionTarget;
  30021. activeLabelList = saveActiveLabelList;
  30022. hasExplicitReturn = saveHasExplicitReturn;
  30023. }
  30024. else if (containerFlags & 64 /* IsInterface */) {
  30025. seenThisKeyword = false;
  30026. bindChildren(node);
  30027. node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
  30028. }
  30029. else {
  30030. bindChildren(node);
  30031. }
  30032. container = saveContainer;
  30033. thisParentContainer = saveThisParentContainer;
  30034. blockScopeContainer = savedBlockScopeContainer;
  30035. }
  30036. function bindChildren(node) {
  30037. if (skipTransformFlagAggregation) {
  30038. bindChildrenWorker(node);
  30039. }
  30040. else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
  30041. skipTransformFlagAggregation = true;
  30042. bindChildrenWorker(node);
  30043. skipTransformFlagAggregation = false;
  30044. subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
  30045. }
  30046. else {
  30047. var savedSubtreeTransformFlags = subtreeTransformFlags;
  30048. subtreeTransformFlags = 0;
  30049. bindChildrenWorker(node);
  30050. subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
  30051. }
  30052. }
  30053. function bindEachFunctionsFirst(nodes) {
  30054. bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
  30055. bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
  30056. }
  30057. function bindEach(nodes, bindFunction) {
  30058. if (bindFunction === void 0) { bindFunction = bind; }
  30059. if (nodes === undefined) {
  30060. return;
  30061. }
  30062. if (skipTransformFlagAggregation) {
  30063. ts.forEach(nodes, bindFunction);
  30064. }
  30065. else {
  30066. var savedSubtreeTransformFlags = subtreeTransformFlags;
  30067. subtreeTransformFlags = 0 /* None */;
  30068. var nodeArrayFlags = 0 /* None */;
  30069. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  30070. var node = nodes_2[_i];
  30071. bindFunction(node);
  30072. nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
  30073. }
  30074. nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
  30075. subtreeTransformFlags |= savedSubtreeTransformFlags;
  30076. }
  30077. }
  30078. function bindEachChild(node) {
  30079. ts.forEachChild(node, bind, bindEach);
  30080. }
  30081. function bindChildrenWorker(node) {
  30082. if (checkUnreachable(node)) {
  30083. bindEachChild(node);
  30084. bindJSDoc(node);
  30085. return;
  30086. }
  30087. if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
  30088. node.flowNode = currentFlow;
  30089. }
  30090. switch (node.kind) {
  30091. case 229 /* WhileStatement */:
  30092. bindWhileStatement(node);
  30093. break;
  30094. case 228 /* DoStatement */:
  30095. bindDoStatement(node);
  30096. break;
  30097. case 230 /* ForStatement */:
  30098. bindForStatement(node);
  30099. break;
  30100. case 231 /* ForInStatement */:
  30101. case 232 /* ForOfStatement */:
  30102. bindForInOrForOfStatement(node);
  30103. break;
  30104. case 227 /* IfStatement */:
  30105. bindIfStatement(node);
  30106. break;
  30107. case 235 /* ReturnStatement */:
  30108. case 239 /* ThrowStatement */:
  30109. bindReturnOrThrow(node);
  30110. break;
  30111. case 234 /* BreakStatement */:
  30112. case 233 /* ContinueStatement */:
  30113. bindBreakOrContinueStatement(node);
  30114. break;
  30115. case 240 /* TryStatement */:
  30116. bindTryStatement(node);
  30117. break;
  30118. case 237 /* SwitchStatement */:
  30119. bindSwitchStatement(node);
  30120. break;
  30121. case 251 /* CaseBlock */:
  30122. bindCaseBlock(node);
  30123. break;
  30124. case 277 /* CaseClause */:
  30125. bindCaseClause(node);
  30126. break;
  30127. case 226 /* ExpressionStatement */:
  30128. bindExpressionStatement(node);
  30129. break;
  30130. case 238 /* LabeledStatement */:
  30131. bindLabeledStatement(node);
  30132. break;
  30133. case 207 /* PrefixUnaryExpression */:
  30134. bindPrefixUnaryExpressionFlow(node);
  30135. break;
  30136. case 208 /* PostfixUnaryExpression */:
  30137. bindPostfixUnaryExpressionFlow(node);
  30138. break;
  30139. case 209 /* BinaryExpression */:
  30140. bindBinaryExpressionFlow(node);
  30141. break;
  30142. case 203 /* DeleteExpression */:
  30143. bindDeleteExpressionFlow(node);
  30144. break;
  30145. case 210 /* ConditionalExpression */:
  30146. bindConditionalExpressionFlow(node);
  30147. break;
  30148. case 242 /* VariableDeclaration */:
  30149. bindVariableDeclarationFlow(node);
  30150. break;
  30151. case 194 /* PropertyAccessExpression */:
  30152. case 195 /* ElementAccessExpression */:
  30153. bindAccessExpressionFlow(node);
  30154. break;
  30155. case 196 /* CallExpression */:
  30156. bindCallExpressionFlow(node);
  30157. break;
  30158. case 321 /* JSDocTypedefTag */:
  30159. case 314 /* JSDocCallbackTag */:
  30160. case 315 /* JSDocEnumTag */:
  30161. bindJSDocTypeAlias(node);
  30162. break;
  30163. // In source files and blocks, bind functions first to match hoisting that occurs at runtime
  30164. case 290 /* SourceFile */: {
  30165. bindEachFunctionsFirst(node.statements);
  30166. bind(node.endOfFileToken);
  30167. break;
  30168. }
  30169. case 223 /* Block */:
  30170. case 250 /* ModuleBlock */:
  30171. bindEachFunctionsFirst(node.statements);
  30172. break;
  30173. default:
  30174. bindEachChild(node);
  30175. break;
  30176. }
  30177. bindJSDoc(node);
  30178. }
  30179. function isNarrowingExpression(expr) {
  30180. switch (expr.kind) {
  30181. case 75 /* Identifier */:
  30182. case 104 /* ThisKeyword */:
  30183. case 194 /* PropertyAccessExpression */:
  30184. case 195 /* ElementAccessExpression */:
  30185. return containsNarrowableReference(expr);
  30186. case 196 /* CallExpression */:
  30187. return hasNarrowableArgument(expr);
  30188. case 200 /* ParenthesizedExpression */:
  30189. return isNarrowingExpression(expr.expression);
  30190. case 209 /* BinaryExpression */:
  30191. return isNarrowingBinaryExpression(expr);
  30192. case 207 /* PrefixUnaryExpression */:
  30193. return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
  30194. case 204 /* TypeOfExpression */:
  30195. return isNarrowingExpression(expr.expression);
  30196. }
  30197. return false;
  30198. }
  30199. function isNarrowableReference(expr) {
  30200. return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
  30201. (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
  30202. ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
  30203. }
  30204. function containsNarrowableReference(expr) {
  30205. return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
  30206. }
  30207. function hasNarrowableArgument(expr) {
  30208. if (expr.arguments) {
  30209. for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
  30210. var argument = _a[_i];
  30211. if (containsNarrowableReference(argument)) {
  30212. return true;
  30213. }
  30214. }
  30215. }
  30216. if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
  30217. containsNarrowableReference(expr.expression.expression)) {
  30218. return true;
  30219. }
  30220. return false;
  30221. }
  30222. function isNarrowingTypeofOperands(expr1, expr2) {
  30223. return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
  30224. }
  30225. function isNarrowableInOperands(left, right) {
  30226. return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
  30227. }
  30228. function isNarrowingBinaryExpression(expr) {
  30229. switch (expr.operatorToken.kind) {
  30230. case 62 /* EqualsToken */:
  30231. return containsNarrowableReference(expr.left);
  30232. case 34 /* EqualsEqualsToken */:
  30233. case 35 /* ExclamationEqualsToken */:
  30234. case 36 /* EqualsEqualsEqualsToken */:
  30235. case 37 /* ExclamationEqualsEqualsToken */:
  30236. return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
  30237. isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
  30238. case 98 /* InstanceOfKeyword */:
  30239. return isNarrowableOperand(expr.left);
  30240. case 97 /* InKeyword */:
  30241. return isNarrowableInOperands(expr.left, expr.right);
  30242. case 27 /* CommaToken */:
  30243. return isNarrowingExpression(expr.right);
  30244. }
  30245. return false;
  30246. }
  30247. function isNarrowableOperand(expr) {
  30248. switch (expr.kind) {
  30249. case 200 /* ParenthesizedExpression */:
  30250. return isNarrowableOperand(expr.expression);
  30251. case 209 /* BinaryExpression */:
  30252. switch (expr.operatorToken.kind) {
  30253. case 62 /* EqualsToken */:
  30254. return isNarrowableOperand(expr.left);
  30255. case 27 /* CommaToken */:
  30256. return isNarrowableOperand(expr.right);
  30257. }
  30258. }
  30259. return containsNarrowableReference(expr);
  30260. }
  30261. function createBranchLabel() {
  30262. return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
  30263. }
  30264. function createLoopLabel() {
  30265. return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
  30266. }
  30267. function setFlowNodeReferenced(flow) {
  30268. // On first reference we set the Referenced flag, thereafter we set the Shared flag
  30269. flow.flags |= flow.flags & 1024 /* Referenced */ ? 2048 /* Shared */ : 1024 /* Referenced */;
  30270. }
  30271. function addAntecedent(label, antecedent) {
  30272. if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
  30273. (label.antecedents || (label.antecedents = [])).push(antecedent);
  30274. setFlowNodeReferenced(antecedent);
  30275. }
  30276. }
  30277. function createFlowCondition(flags, antecedent, expression) {
  30278. if (antecedent.flags & 1 /* Unreachable */) {
  30279. return antecedent;
  30280. }
  30281. if (!expression) {
  30282. return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
  30283. }
  30284. if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
  30285. expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
  30286. !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
  30287. return unreachableFlow;
  30288. }
  30289. if (!isNarrowingExpression(expression)) {
  30290. return antecedent;
  30291. }
  30292. setFlowNodeReferenced(antecedent);
  30293. return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
  30294. }
  30295. function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
  30296. setFlowNodeReferenced(antecedent);
  30297. return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
  30298. }
  30299. function createFlowMutation(flags, antecedent, node) {
  30300. setFlowNodeReferenced(antecedent);
  30301. var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
  30302. if (currentExceptionTarget) {
  30303. addAntecedent(currentExceptionTarget, result);
  30304. }
  30305. return result;
  30306. }
  30307. function createFlowCall(antecedent, node) {
  30308. setFlowNodeReferenced(antecedent);
  30309. return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
  30310. }
  30311. function finishFlowLabel(flow) {
  30312. var antecedents = flow.antecedents;
  30313. if (!antecedents) {
  30314. return unreachableFlow;
  30315. }
  30316. if (antecedents.length === 1) {
  30317. return antecedents[0];
  30318. }
  30319. return flow;
  30320. }
  30321. function isStatementCondition(node) {
  30322. var parent = node.parent;
  30323. switch (parent.kind) {
  30324. case 227 /* IfStatement */:
  30325. case 229 /* WhileStatement */:
  30326. case 228 /* DoStatement */:
  30327. return parent.expression === node;
  30328. case 230 /* ForStatement */:
  30329. case 210 /* ConditionalExpression */:
  30330. return parent.condition === node;
  30331. }
  30332. return false;
  30333. }
  30334. function isLogicalExpression(node) {
  30335. while (true) {
  30336. if (node.kind === 200 /* ParenthesizedExpression */) {
  30337. node = node.expression;
  30338. }
  30339. else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
  30340. node = node.operand;
  30341. }
  30342. else {
  30343. return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
  30344. node.operatorToken.kind === 56 /* BarBarToken */ ||
  30345. node.operatorToken.kind === 60 /* QuestionQuestionToken */);
  30346. }
  30347. }
  30348. }
  30349. function isTopLevelLogicalExpression(node) {
  30350. while (ts.isParenthesizedExpression(node.parent) ||
  30351. ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
  30352. node = node.parent;
  30353. }
  30354. return !isStatementCondition(node) &&
  30355. !isLogicalExpression(node.parent) &&
  30356. !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
  30357. }
  30358. function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
  30359. var savedTrueTarget = currentTrueTarget;
  30360. var savedFalseTarget = currentFalseTarget;
  30361. currentTrueTarget = trueTarget;
  30362. currentFalseTarget = falseTarget;
  30363. action(value);
  30364. currentTrueTarget = savedTrueTarget;
  30365. currentFalseTarget = savedFalseTarget;
  30366. }
  30367. function bindCondition(node, trueTarget, falseTarget) {
  30368. doWithConditionalBranches(bind, node, trueTarget, falseTarget);
  30369. if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
  30370. addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
  30371. addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
  30372. }
  30373. }
  30374. function bindIterativeStatement(node, breakTarget, continueTarget) {
  30375. var saveBreakTarget = currentBreakTarget;
  30376. var saveContinueTarget = currentContinueTarget;
  30377. currentBreakTarget = breakTarget;
  30378. currentContinueTarget = continueTarget;
  30379. bind(node);
  30380. currentBreakTarget = saveBreakTarget;
  30381. currentContinueTarget = saveContinueTarget;
  30382. }
  30383. function setContinueTarget(node, target) {
  30384. var label = activeLabelList;
  30385. while (label && node.parent.kind === 238 /* LabeledStatement */) {
  30386. label.continueTarget = target;
  30387. label = label.next;
  30388. node = node.parent;
  30389. }
  30390. return target;
  30391. }
  30392. function bindWhileStatement(node) {
  30393. var preWhileLabel = setContinueTarget(node, createLoopLabel());
  30394. var preBodyLabel = createBranchLabel();
  30395. var postWhileLabel = createBranchLabel();
  30396. addAntecedent(preWhileLabel, currentFlow);
  30397. currentFlow = preWhileLabel;
  30398. bindCondition(node.expression, preBodyLabel, postWhileLabel);
  30399. currentFlow = finishFlowLabel(preBodyLabel);
  30400. bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
  30401. addAntecedent(preWhileLabel, currentFlow);
  30402. currentFlow = finishFlowLabel(postWhileLabel);
  30403. }
  30404. function bindDoStatement(node) {
  30405. var preDoLabel = createLoopLabel();
  30406. var preConditionLabel = setContinueTarget(node, createBranchLabel());
  30407. var postDoLabel = createBranchLabel();
  30408. addAntecedent(preDoLabel, currentFlow);
  30409. currentFlow = preDoLabel;
  30410. bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
  30411. addAntecedent(preConditionLabel, currentFlow);
  30412. currentFlow = finishFlowLabel(preConditionLabel);
  30413. bindCondition(node.expression, preDoLabel, postDoLabel);
  30414. currentFlow = finishFlowLabel(postDoLabel);
  30415. }
  30416. function bindForStatement(node) {
  30417. var preLoopLabel = setContinueTarget(node, createLoopLabel());
  30418. var preBodyLabel = createBranchLabel();
  30419. var postLoopLabel = createBranchLabel();
  30420. bind(node.initializer);
  30421. addAntecedent(preLoopLabel, currentFlow);
  30422. currentFlow = preLoopLabel;
  30423. bindCondition(node.condition, preBodyLabel, postLoopLabel);
  30424. currentFlow = finishFlowLabel(preBodyLabel);
  30425. bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
  30426. bind(node.incrementor);
  30427. addAntecedent(preLoopLabel, currentFlow);
  30428. currentFlow = finishFlowLabel(postLoopLabel);
  30429. }
  30430. function bindForInOrForOfStatement(node) {
  30431. var preLoopLabel = setContinueTarget(node, createLoopLabel());
  30432. var postLoopLabel = createBranchLabel();
  30433. bind(node.expression);
  30434. addAntecedent(preLoopLabel, currentFlow);
  30435. currentFlow = preLoopLabel;
  30436. if (node.kind === 232 /* ForOfStatement */) {
  30437. bind(node.awaitModifier);
  30438. }
  30439. addAntecedent(postLoopLabel, currentFlow);
  30440. bind(node.initializer);
  30441. if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
  30442. bindAssignmentTargetFlow(node.initializer);
  30443. }
  30444. bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
  30445. addAntecedent(preLoopLabel, currentFlow);
  30446. currentFlow = finishFlowLabel(postLoopLabel);
  30447. }
  30448. function bindIfStatement(node) {
  30449. var thenLabel = createBranchLabel();
  30450. var elseLabel = createBranchLabel();
  30451. var postIfLabel = createBranchLabel();
  30452. bindCondition(node.expression, thenLabel, elseLabel);
  30453. currentFlow = finishFlowLabel(thenLabel);
  30454. bind(node.thenStatement);
  30455. addAntecedent(postIfLabel, currentFlow);
  30456. currentFlow = finishFlowLabel(elseLabel);
  30457. bind(node.elseStatement);
  30458. addAntecedent(postIfLabel, currentFlow);
  30459. currentFlow = finishFlowLabel(postIfLabel);
  30460. }
  30461. function bindReturnOrThrow(node) {
  30462. bind(node.expression);
  30463. if (node.kind === 235 /* ReturnStatement */) {
  30464. hasExplicitReturn = true;
  30465. if (currentReturnTarget) {
  30466. addAntecedent(currentReturnTarget, currentFlow);
  30467. }
  30468. }
  30469. currentFlow = unreachableFlow;
  30470. }
  30471. function findActiveLabel(name) {
  30472. for (var label = activeLabelList; label; label = label.next) {
  30473. if (label.name === name) {
  30474. return label;
  30475. }
  30476. }
  30477. return undefined;
  30478. }
  30479. function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
  30480. var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
  30481. if (flowLabel) {
  30482. addAntecedent(flowLabel, currentFlow);
  30483. currentFlow = unreachableFlow;
  30484. }
  30485. }
  30486. function bindBreakOrContinueStatement(node) {
  30487. bind(node.label);
  30488. if (node.label) {
  30489. var activeLabel = findActiveLabel(node.label.escapedText);
  30490. if (activeLabel) {
  30491. activeLabel.referenced = true;
  30492. bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
  30493. }
  30494. }
  30495. else {
  30496. bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
  30497. }
  30498. }
  30499. function bindTryStatement(node) {
  30500. var preFinallyLabel = createBranchLabel();
  30501. // We conservatively assume that *any* code in the try block can cause an exception, but we only need
  30502. // to track code that causes mutations (because only mutations widen the possible control flow type of
  30503. // a variable). The currentExceptionTarget is the target label for control flows that result from
  30504. // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them
  30505. // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current
  30506. // control flow to represent exceptions that occur before any mutations.
  30507. var saveReturnTarget = currentReturnTarget;
  30508. var saveExceptionTarget = currentExceptionTarget;
  30509. currentReturnTarget = createBranchLabel();
  30510. currentExceptionTarget = node.catchClause ? createBranchLabel() : currentReturnTarget;
  30511. addAntecedent(currentExceptionTarget, currentFlow);
  30512. bind(node.tryBlock);
  30513. addAntecedent(preFinallyLabel, currentFlow);
  30514. var flowAfterTry = currentFlow;
  30515. var flowAfterCatch = unreachableFlow;
  30516. if (node.catchClause) {
  30517. // Start of catch clause is the target of exceptions from try block.
  30518. currentFlow = finishFlowLabel(currentExceptionTarget);
  30519. // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
  30520. // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
  30521. // acts like a second try block.
  30522. currentExceptionTarget = currentReturnTarget;
  30523. addAntecedent(currentExceptionTarget, currentFlow);
  30524. bind(node.catchClause);
  30525. addAntecedent(preFinallyLabel, currentFlow);
  30526. flowAfterCatch = currentFlow;
  30527. }
  30528. var exceptionTarget = finishFlowLabel(currentExceptionTarget);
  30529. currentReturnTarget = saveReturnTarget;
  30530. currentExceptionTarget = saveExceptionTarget;
  30531. if (node.finallyBlock) {
  30532. // Possible ways control can reach the finally block:
  30533. // 1) Normal completion of try block of a try-finally or try-catch-finally
  30534. // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
  30535. // 3) Return in try or catch block of a try-finally or try-catch-finally
  30536. // 4) Exception in try block of a try-finally
  30537. // 5) Exception in catch block of a try-catch-finally
  30538. // When analyzing a control flow graph that starts inside a finally block we want to consider all
  30539. // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
  30540. // the finally block, we only want to consider the first two (if we're past a finally block then it
  30541. // must have completed normally). To make this possible, we inject two extra nodes into the control
  30542. // flow graph: An after-finally with an antecedent of the control flow at the end of the finally
  30543. // block, and a pre-finally with an antecedent that represents all exceptional control flows. The
  30544. // 'lock' property of the pre-finally references the after-finally, and the after-finally has a
  30545. // boolean 'locked' property that we set to true when analyzing a control flow that contained the
  30546. // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of
  30547. // the pre-finally (i.e. the exceptional control flows) are skipped.
  30548. var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} });
  30549. addAntecedent(preFinallyLabel, preFinallyFlow);
  30550. currentFlow = finishFlowLabel(preFinallyLabel);
  30551. bind(node.finallyBlock);
  30552. // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
  30553. // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
  30554. // result in an unreachable current control flow.
  30555. if (!(currentFlow.flags & 1 /* Unreachable */)) {
  30556. if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) {
  30557. currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow
  30558. ? reportedUnreachableFlow
  30559. : unreachableFlow;
  30560. }
  30561. }
  30562. if (!(currentFlow.flags & 1 /* Unreachable */)) {
  30563. var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow });
  30564. preFinallyFlow.lock = afterFinallyFlow;
  30565. currentFlow = afterFinallyFlow;
  30566. }
  30567. }
  30568. else {
  30569. currentFlow = finishFlowLabel(preFinallyLabel);
  30570. }
  30571. }
  30572. function bindSwitchStatement(node) {
  30573. var postSwitchLabel = createBranchLabel();
  30574. bind(node.expression);
  30575. var saveBreakTarget = currentBreakTarget;
  30576. var savePreSwitchCaseFlow = preSwitchCaseFlow;
  30577. currentBreakTarget = postSwitchLabel;
  30578. preSwitchCaseFlow = currentFlow;
  30579. bind(node.caseBlock);
  30580. addAntecedent(postSwitchLabel, currentFlow);
  30581. var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
  30582. // We mark a switch statement as possibly exhaustive if it has no default clause and if all
  30583. // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
  30584. // this property in control flow analysis, it's there only for backwards compatibility.
  30585. node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
  30586. if (!hasDefault) {
  30587. addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
  30588. }
  30589. currentBreakTarget = saveBreakTarget;
  30590. preSwitchCaseFlow = savePreSwitchCaseFlow;
  30591. currentFlow = finishFlowLabel(postSwitchLabel);
  30592. }
  30593. function bindCaseBlock(node) {
  30594. var savedSubtreeTransformFlags = subtreeTransformFlags;
  30595. subtreeTransformFlags = 0;
  30596. var clauses = node.clauses;
  30597. var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
  30598. var fallthroughFlow = unreachableFlow;
  30599. for (var i = 0; i < clauses.length; i++) {
  30600. var clauseStart = i;
  30601. while (!clauses[i].statements.length && i + 1 < clauses.length) {
  30602. bind(clauses[i]);
  30603. i++;
  30604. }
  30605. var preCaseLabel = createBranchLabel();
  30606. addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
  30607. addAntecedent(preCaseLabel, fallthroughFlow);
  30608. currentFlow = finishFlowLabel(preCaseLabel);
  30609. var clause = clauses[i];
  30610. bind(clause);
  30611. fallthroughFlow = currentFlow;
  30612. if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
  30613. clause.fallthroughFlowNode = currentFlow;
  30614. }
  30615. }
  30616. clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
  30617. subtreeTransformFlags |= savedSubtreeTransformFlags;
  30618. }
  30619. function bindCaseClause(node) {
  30620. var saveCurrentFlow = currentFlow;
  30621. currentFlow = preSwitchCaseFlow;
  30622. bind(node.expression);
  30623. currentFlow = saveCurrentFlow;
  30624. bindEach(node.statements);
  30625. }
  30626. function bindExpressionStatement(node) {
  30627. bind(node.expression);
  30628. // A top level call expression with a dotted function name and at least one argument
  30629. // is potentially an assertion and is therefore included in the control flow.
  30630. if (node.expression.kind === 196 /* CallExpression */) {
  30631. var call = node.expression;
  30632. if (ts.isDottedName(call.expression)) {
  30633. currentFlow = createFlowCall(currentFlow, call);
  30634. }
  30635. }
  30636. }
  30637. function bindLabeledStatement(node) {
  30638. var postStatementLabel = createBranchLabel();
  30639. activeLabelList = {
  30640. next: activeLabelList,
  30641. name: node.label.escapedText,
  30642. breakTarget: postStatementLabel,
  30643. continueTarget: undefined,
  30644. referenced: false
  30645. };
  30646. bind(node.label);
  30647. bind(node.statement);
  30648. if (!activeLabelList.referenced && !options.allowUnusedLabels) {
  30649. errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
  30650. }
  30651. activeLabelList = activeLabelList.next;
  30652. addAntecedent(postStatementLabel, currentFlow);
  30653. currentFlow = finishFlowLabel(postStatementLabel);
  30654. }
  30655. function bindDestructuringTargetFlow(node) {
  30656. if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
  30657. bindAssignmentTargetFlow(node.left);
  30658. }
  30659. else {
  30660. bindAssignmentTargetFlow(node);
  30661. }
  30662. }
  30663. function bindAssignmentTargetFlow(node) {
  30664. if (isNarrowableReference(node)) {
  30665. currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
  30666. }
  30667. else if (node.kind === 192 /* ArrayLiteralExpression */) {
  30668. for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
  30669. var e = _a[_i];
  30670. if (e.kind === 213 /* SpreadElement */) {
  30671. bindAssignmentTargetFlow(e.expression);
  30672. }
  30673. else {
  30674. bindDestructuringTargetFlow(e);
  30675. }
  30676. }
  30677. }
  30678. else if (node.kind === 193 /* ObjectLiteralExpression */) {
  30679. for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
  30680. var p = _c[_b];
  30681. if (p.kind === 281 /* PropertyAssignment */) {
  30682. bindDestructuringTargetFlow(p.initializer);
  30683. }
  30684. else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
  30685. bindAssignmentTargetFlow(p.name);
  30686. }
  30687. else if (p.kind === 283 /* SpreadAssignment */) {
  30688. bindAssignmentTargetFlow(p.expression);
  30689. }
  30690. }
  30691. }
  30692. }
  30693. function bindLogicalExpression(node, trueTarget, falseTarget) {
  30694. var preRightLabel = createBranchLabel();
  30695. if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
  30696. bindCondition(node.left, preRightLabel, falseTarget);
  30697. }
  30698. else {
  30699. bindCondition(node.left, trueTarget, preRightLabel);
  30700. }
  30701. currentFlow = finishFlowLabel(preRightLabel);
  30702. bind(node.operatorToken);
  30703. bindCondition(node.right, trueTarget, falseTarget);
  30704. }
  30705. function bindPrefixUnaryExpressionFlow(node) {
  30706. if (node.operator === 53 /* ExclamationToken */) {
  30707. var saveTrueTarget = currentTrueTarget;
  30708. currentTrueTarget = currentFalseTarget;
  30709. currentFalseTarget = saveTrueTarget;
  30710. bindEachChild(node);
  30711. currentFalseTarget = currentTrueTarget;
  30712. currentTrueTarget = saveTrueTarget;
  30713. }
  30714. else {
  30715. bindEachChild(node);
  30716. if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
  30717. bindAssignmentTargetFlow(node.operand);
  30718. }
  30719. }
  30720. }
  30721. function bindPostfixUnaryExpressionFlow(node) {
  30722. bindEachChild(node);
  30723. if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
  30724. bindAssignmentTargetFlow(node.operand);
  30725. }
  30726. }
  30727. var BindBinaryExpressionFlowState;
  30728. (function (BindBinaryExpressionFlowState) {
  30729. BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
  30730. BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
  30731. BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
  30732. BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
  30733. BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
  30734. })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
  30735. function bindBinaryExpressionFlow(node) {
  30736. var workStacks = {
  30737. expr: [node],
  30738. state: [1 /* MaybeBindLeft */],
  30739. inStrictMode: [undefined],
  30740. parent: [undefined],
  30741. subtreeFlags: [undefined]
  30742. };
  30743. var stackIndex = 0;
  30744. while (stackIndex >= 0) {
  30745. node = workStacks.expr[stackIndex];
  30746. switch (workStacks.state[stackIndex]) {
  30747. case 0 /* BindThenBindChildren */: {
  30748. // This state is used only when recuring, to emulate the work that `bind` does before
  30749. // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
  30750. node.parent = parent;
  30751. var saveInStrictMode = inStrictMode;
  30752. bindWorker(node);
  30753. var saveParent = parent;
  30754. parent = node;
  30755. var subtreeFlagsState = void 0;
  30756. // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
  30757. // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
  30758. if (skipTransformFlagAggregation) {
  30759. // do nothing extra
  30760. }
  30761. else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
  30762. skipTransformFlagAggregation = true;
  30763. subtreeFlagsState = -1;
  30764. }
  30765. else {
  30766. var savedSubtreeTransformFlags = subtreeTransformFlags;
  30767. subtreeTransformFlags = 0;
  30768. subtreeFlagsState = savedSubtreeTransformFlags;
  30769. }
  30770. advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
  30771. break;
  30772. }
  30773. case 1 /* MaybeBindLeft */: {
  30774. var operator = node.operatorToken.kind;
  30775. // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
  30776. // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
  30777. // For now, though, since the common cases are chained `+`, leaving it recursive is fine
  30778. if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
  30779. if (isTopLevelLogicalExpression(node)) {
  30780. var postExpressionLabel = createBranchLabel();
  30781. bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
  30782. currentFlow = finishFlowLabel(postExpressionLabel);
  30783. }
  30784. else {
  30785. bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
  30786. }
  30787. completeNode();
  30788. }
  30789. else {
  30790. advanceState(2 /* BindToken */);
  30791. maybeBind(node.left);
  30792. }
  30793. break;
  30794. }
  30795. case 2 /* BindToken */: {
  30796. advanceState(3 /* BindRight */);
  30797. maybeBind(node.operatorToken);
  30798. break;
  30799. }
  30800. case 3 /* BindRight */: {
  30801. advanceState(4 /* FinishBind */);
  30802. maybeBind(node.right);
  30803. break;
  30804. }
  30805. case 4 /* FinishBind */: {
  30806. var operator = node.operatorToken.kind;
  30807. if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
  30808. bindAssignmentTargetFlow(node.left);
  30809. if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
  30810. var elementAccess = node.left;
  30811. if (isNarrowableOperand(elementAccess.expression)) {
  30812. currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
  30813. }
  30814. }
  30815. }
  30816. completeNode();
  30817. break;
  30818. }
  30819. default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
  30820. }
  30821. }
  30822. /**
  30823. * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
  30824. * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
  30825. */
  30826. function advanceState(state, isInStrictMode, parent, subtreeFlags) {
  30827. workStacks.state[stackIndex] = state;
  30828. if (isInStrictMode !== undefined) {
  30829. workStacks.inStrictMode[stackIndex] = isInStrictMode;
  30830. }
  30831. if (parent !== undefined) {
  30832. workStacks.parent[stackIndex] = parent;
  30833. }
  30834. if (subtreeFlags !== undefined) {
  30835. workStacks.subtreeFlags[stackIndex] = subtreeFlags;
  30836. }
  30837. }
  30838. function completeNode() {
  30839. if (workStacks.inStrictMode[stackIndex] !== undefined) {
  30840. if (workStacks.subtreeFlags[stackIndex] === -1) {
  30841. skipTransformFlagAggregation = false;
  30842. subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
  30843. }
  30844. else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
  30845. subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
  30846. }
  30847. inStrictMode = workStacks.inStrictMode[stackIndex];
  30848. parent = workStacks.parent[stackIndex];
  30849. }
  30850. stackIndex--;
  30851. }
  30852. /**
  30853. * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
  30854. */
  30855. function maybeBind(node) {
  30856. if (node && ts.isBinaryExpression(node)) {
  30857. stackIndex++;
  30858. workStacks.expr[stackIndex] = node;
  30859. workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
  30860. workStacks.inStrictMode[stackIndex] = undefined;
  30861. workStacks.parent[stackIndex] = undefined;
  30862. workStacks.subtreeFlags[stackIndex] = undefined;
  30863. }
  30864. else {
  30865. bind(node);
  30866. }
  30867. }
  30868. }
  30869. function bindDeleteExpressionFlow(node) {
  30870. bindEachChild(node);
  30871. if (node.expression.kind === 194 /* PropertyAccessExpression */) {
  30872. bindAssignmentTargetFlow(node.expression);
  30873. }
  30874. }
  30875. function bindConditionalExpressionFlow(node) {
  30876. var trueLabel = createBranchLabel();
  30877. var falseLabel = createBranchLabel();
  30878. var postExpressionLabel = createBranchLabel();
  30879. bindCondition(node.condition, trueLabel, falseLabel);
  30880. currentFlow = finishFlowLabel(trueLabel);
  30881. bind(node.questionToken);
  30882. bind(node.whenTrue);
  30883. addAntecedent(postExpressionLabel, currentFlow);
  30884. currentFlow = finishFlowLabel(falseLabel);
  30885. bind(node.colonToken);
  30886. bind(node.whenFalse);
  30887. addAntecedent(postExpressionLabel, currentFlow);
  30888. currentFlow = finishFlowLabel(postExpressionLabel);
  30889. }
  30890. function bindInitializedVariableFlow(node) {
  30891. var name = !ts.isOmittedExpression(node) ? node.name : undefined;
  30892. if (ts.isBindingPattern(name)) {
  30893. for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
  30894. var child = _a[_i];
  30895. bindInitializedVariableFlow(child);
  30896. }
  30897. }
  30898. else {
  30899. currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
  30900. }
  30901. }
  30902. function bindVariableDeclarationFlow(node) {
  30903. bindEachChild(node);
  30904. if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
  30905. bindInitializedVariableFlow(node);
  30906. }
  30907. }
  30908. function bindJSDocTypeAlias(node) {
  30909. node.tagName.parent = node;
  30910. if (node.kind !== 315 /* JSDocEnumTag */ && node.fullName) {
  30911. setParentPointers(node, node.fullName);
  30912. }
  30913. }
  30914. function bindJSDocClassTag(node) {
  30915. bindEachChild(node);
  30916. var host = ts.getHostSignatureFromJSDoc(node);
  30917. if (host && host.kind !== 161 /* MethodDeclaration */) {
  30918. addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
  30919. }
  30920. }
  30921. function bindOptionalExpression(node, trueTarget, falseTarget) {
  30922. doWithConditionalBranches(bind, node, trueTarget, falseTarget);
  30923. if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
  30924. addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
  30925. addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
  30926. }
  30927. }
  30928. function bindOptionalChainRest(node) {
  30929. bind(node.questionDotToken);
  30930. switch (node.kind) {
  30931. case 194 /* PropertyAccessExpression */:
  30932. bind(node.name);
  30933. break;
  30934. case 195 /* ElementAccessExpression */:
  30935. bind(node.argumentExpression);
  30936. break;
  30937. case 196 /* CallExpression */:
  30938. bindEach(node.typeArguments);
  30939. bindEach(node.arguments);
  30940. break;
  30941. }
  30942. }
  30943. function bindOptionalChain(node, trueTarget, falseTarget) {
  30944. // For an optional chain, we emulate the behavior of a logical expression:
  30945. //
  30946. // a?.b -> a && a.b
  30947. // a?.b.c -> a && a.b.c
  30948. // a?.b?.c -> a && a.b && a.b.c
  30949. // a?.[x = 1] -> a && a[x = 1]
  30950. //
  30951. // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
  30952. // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
  30953. // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
  30954. // chain node. We then treat the entire node as the right side of the expression.
  30955. var preChainLabel = node.questionDotToken ? createBranchLabel() : undefined;
  30956. bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
  30957. if (preChainLabel) {
  30958. currentFlow = finishFlowLabel(preChainLabel);
  30959. }
  30960. doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
  30961. if (ts.isOutermostOptionalChain(node)) {
  30962. addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
  30963. addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
  30964. }
  30965. }
  30966. function bindOptionalChainFlow(node) {
  30967. if (isTopLevelLogicalExpression(node)) {
  30968. var postExpressionLabel = createBranchLabel();
  30969. bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
  30970. currentFlow = finishFlowLabel(postExpressionLabel);
  30971. }
  30972. else {
  30973. bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
  30974. }
  30975. }
  30976. function bindAccessExpressionFlow(node) {
  30977. if (ts.isOptionalChain(node)) {
  30978. bindOptionalChainFlow(node);
  30979. }
  30980. else {
  30981. bindEachChild(node);
  30982. }
  30983. }
  30984. function bindCallExpressionFlow(node) {
  30985. if (ts.isOptionalChain(node)) {
  30986. bindOptionalChainFlow(node);
  30987. }
  30988. else {
  30989. // If the target of the call expression is a function expression or arrow function we have
  30990. // an immediately invoked function expression (IIFE). Initialize the flowNode property to
  30991. // the current control flow (which includes evaluation of the IIFE arguments).
  30992. var expr = ts.skipParentheses(node.expression);
  30993. if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
  30994. bindEach(node.typeArguments);
  30995. bindEach(node.arguments);
  30996. bind(node.expression);
  30997. }
  30998. else {
  30999. bindEachChild(node);
  31000. }
  31001. }
  31002. if (node.expression.kind === 194 /* PropertyAccessExpression */) {
  31003. var propertyAccess = node.expression;
  31004. if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
  31005. currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
  31006. }
  31007. }
  31008. }
  31009. function getContainerFlags(node) {
  31010. switch (node.kind) {
  31011. case 214 /* ClassExpression */:
  31012. case 245 /* ClassDeclaration */:
  31013. case 248 /* EnumDeclaration */:
  31014. case 193 /* ObjectLiteralExpression */:
  31015. case 173 /* TypeLiteral */:
  31016. case 304 /* JSDocTypeLiteral */:
  31017. case 274 /* JsxAttributes */:
  31018. return 1 /* IsContainer */;
  31019. case 246 /* InterfaceDeclaration */:
  31020. return 1 /* IsContainer */ | 64 /* IsInterface */;
  31021. case 249 /* ModuleDeclaration */:
  31022. case 247 /* TypeAliasDeclaration */:
  31023. case 186 /* MappedType */:
  31024. return 1 /* IsContainer */ | 32 /* HasLocals */;
  31025. case 290 /* SourceFile */:
  31026. return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
  31027. case 161 /* MethodDeclaration */:
  31028. if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
  31029. return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
  31030. }
  31031. // falls through
  31032. case 162 /* Constructor */:
  31033. case 244 /* FunctionDeclaration */:
  31034. case 160 /* MethodSignature */:
  31035. case 163 /* GetAccessor */:
  31036. case 164 /* SetAccessor */:
  31037. case 165 /* CallSignature */:
  31038. case 305 /* JSDocSignature */:
  31039. case 300 /* JSDocFunctionType */:
  31040. case 170 /* FunctionType */:
  31041. case 166 /* ConstructSignature */:
  31042. case 167 /* IndexSignature */:
  31043. case 171 /* ConstructorType */:
  31044. return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
  31045. case 201 /* FunctionExpression */:
  31046. case 202 /* ArrowFunction */:
  31047. return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
  31048. case 250 /* ModuleBlock */:
  31049. return 4 /* IsControlFlowContainer */;
  31050. case 159 /* PropertyDeclaration */:
  31051. return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
  31052. case 280 /* CatchClause */:
  31053. case 230 /* ForStatement */:
  31054. case 231 /* ForInStatement */:
  31055. case 232 /* ForOfStatement */:
  31056. case 251 /* CaseBlock */:
  31057. return 2 /* IsBlockScopedContainer */;
  31058. case 223 /* Block */:
  31059. // do not treat blocks directly inside a function as a block-scoped-container.
  31060. // Locals that reside in this block should go to the function locals. Otherwise 'x'
  31061. // would not appear to be a redeclaration of a block scoped local in the following
  31062. // example:
  31063. //
  31064. // function foo() {
  31065. // var x;
  31066. // let x;
  31067. // }
  31068. //
  31069. // If we placed 'var x' into the function locals and 'let x' into the locals of
  31070. // the block, then there would be no collision.
  31071. //
  31072. // By not creating a new block-scoped-container here, we ensure that both 'var x'
  31073. // and 'let x' go into the Function-container's locals, and we do get a collision
  31074. // conflict.
  31075. return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
  31076. }
  31077. return 0 /* None */;
  31078. }
  31079. function addToContainerChain(next) {
  31080. if (lastContainer) {
  31081. lastContainer.nextContainer = next;
  31082. }
  31083. lastContainer = next;
  31084. }
  31085. function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
  31086. switch (container.kind) {
  31087. // Modules, source files, and classes need specialized handling for how their
  31088. // members are declared (for example, a member of a class will go into a specific
  31089. // symbol table depending on if it is static or not). We defer to specialized
  31090. // handlers to take care of declaring these child members.
  31091. case 249 /* ModuleDeclaration */:
  31092. return declareModuleMember(node, symbolFlags, symbolExcludes);
  31093. case 290 /* SourceFile */:
  31094. return declareSourceFileMember(node, symbolFlags, symbolExcludes);
  31095. case 214 /* ClassExpression */:
  31096. case 245 /* ClassDeclaration */:
  31097. return declareClassMember(node, symbolFlags, symbolExcludes);
  31098. case 248 /* EnumDeclaration */:
  31099. return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
  31100. case 173 /* TypeLiteral */:
  31101. case 304 /* JSDocTypeLiteral */:
  31102. case 193 /* ObjectLiteralExpression */:
  31103. case 246 /* InterfaceDeclaration */:
  31104. case 274 /* JsxAttributes */:
  31105. // Interface/Object-types always have their children added to the 'members' of
  31106. // their container. They are only accessible through an instance of their
  31107. // container, and are never in scope otherwise (even inside the body of the
  31108. // object / type / interface declaring them). An exception is type parameters,
  31109. // which are in scope without qualification (similar to 'locals').
  31110. return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
  31111. case 170 /* FunctionType */:
  31112. case 171 /* ConstructorType */:
  31113. case 165 /* CallSignature */:
  31114. case 166 /* ConstructSignature */:
  31115. case 305 /* JSDocSignature */:
  31116. case 167 /* IndexSignature */:
  31117. case 161 /* MethodDeclaration */:
  31118. case 160 /* MethodSignature */:
  31119. case 162 /* Constructor */:
  31120. case 163 /* GetAccessor */:
  31121. case 164 /* SetAccessor */:
  31122. case 244 /* FunctionDeclaration */:
  31123. case 201 /* FunctionExpression */:
  31124. case 202 /* ArrowFunction */:
  31125. case 300 /* JSDocFunctionType */:
  31126. case 321 /* JSDocTypedefTag */:
  31127. case 314 /* JSDocCallbackTag */:
  31128. case 247 /* TypeAliasDeclaration */:
  31129. case 186 /* MappedType */:
  31130. // All the children of these container types are never visible through another
  31131. // symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
  31132. // they're only accessed 'lexically' (i.e. from code that exists underneath
  31133. // their container in the tree). To accomplish this, we simply add their declared
  31134. // symbol to the 'locals' of the container. These symbols can then be found as
  31135. // the type checker walks up the containers, checking them for matching names.
  31136. return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
  31137. }
  31138. }
  31139. function declareClassMember(node, symbolFlags, symbolExcludes) {
  31140. return ts.hasModifier(node, 32 /* Static */)
  31141. ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
  31142. : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
  31143. }
  31144. function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
  31145. return ts.isExternalModule(file)
  31146. ? declareModuleMember(node, symbolFlags, symbolExcludes)
  31147. : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
  31148. }
  31149. function hasExportDeclarations(node) {
  31150. var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
  31151. return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
  31152. }
  31153. function setExportContextFlag(node) {
  31154. // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
  31155. // declarations with export modifiers) is an export context in which declarations are implicitly exported.
  31156. if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
  31157. node.flags |= 64 /* ExportContext */;
  31158. }
  31159. else {
  31160. node.flags &= ~64 /* ExportContext */;
  31161. }
  31162. }
  31163. function bindModuleDeclaration(node) {
  31164. setExportContextFlag(node);
  31165. if (ts.isAmbientModule(node)) {
  31166. if (ts.hasModifier(node, 1 /* Export */)) {
  31167. errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
  31168. }
  31169. if (ts.isModuleAugmentationExternal(node)) {
  31170. declareModuleSymbol(node);
  31171. }
  31172. else {
  31173. var pattern = void 0;
  31174. if (node.name.kind === 10 /* StringLiteral */) {
  31175. var text = node.name.text;
  31176. if (ts.hasZeroOrOneAsteriskCharacter(text)) {
  31177. pattern = ts.tryParsePattern(text);
  31178. }
  31179. else {
  31180. errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
  31181. }
  31182. }
  31183. var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
  31184. file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
  31185. }
  31186. }
  31187. else {
  31188. var state = declareModuleSymbol(node);
  31189. if (state !== 0 /* NonInstantiated */) {
  31190. var symbol = node.symbol;
  31191. // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
  31192. symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
  31193. // Current must be `const enum` only
  31194. && state === 2 /* ConstEnumOnly */
  31195. // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
  31196. && symbol.constEnumOnlyModule !== false;
  31197. }
  31198. }
  31199. }
  31200. function declareModuleSymbol(node) {
  31201. var state = getModuleInstanceState(node);
  31202. var instantiated = state !== 0 /* NonInstantiated */;
  31203. declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
  31204. return state;
  31205. }
  31206. function bindFunctionOrConstructorType(node) {
  31207. // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
  31208. // to the one we would get for: { <...>(...): T }
  31209. //
  31210. // We do that by making an anonymous type literal symbol, and then setting the function
  31211. // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
  31212. // from an actual type literal symbol you would have gotten had you used the long form.
  31213. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
  31214. addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
  31215. var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
  31216. addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
  31217. typeLiteralSymbol.members = ts.createSymbolTable();
  31218. typeLiteralSymbol.members.set(symbol.escapedName, symbol);
  31219. }
  31220. function bindObjectLiteralExpression(node) {
  31221. var ElementKind;
  31222. (function (ElementKind) {
  31223. ElementKind[ElementKind["Property"] = 1] = "Property";
  31224. ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
  31225. })(ElementKind || (ElementKind = {}));
  31226. if (inStrictMode && !ts.isAssignmentTarget(node)) {
  31227. var seen = ts.createUnderscoreEscapedMap();
  31228. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  31229. var prop = _a[_i];
  31230. if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
  31231. continue;
  31232. }
  31233. var identifier = prop.name;
  31234. // ECMA-262 11.1.5 Object Initializer
  31235. // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
  31236. // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
  31237. // IsDataDescriptor(propId.descriptor) is true.
  31238. // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
  31239. // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
  31240. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
  31241. // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
  31242. var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
  31243. ? 1 /* Property */
  31244. : 2 /* Accessor */;
  31245. var existingKind = seen.get(identifier.escapedText);
  31246. if (!existingKind) {
  31247. seen.set(identifier.escapedText, currentKind);
  31248. continue;
  31249. }
  31250. if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
  31251. var span = ts.getErrorSpanForNode(file, identifier);
  31252. file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
  31253. }
  31254. }
  31255. }
  31256. return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
  31257. }
  31258. function bindJsxAttributes(node) {
  31259. return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
  31260. }
  31261. function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
  31262. return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
  31263. }
  31264. function bindAnonymousDeclaration(node, symbolFlags, name) {
  31265. var symbol = createSymbol(symbolFlags, name);
  31266. if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
  31267. symbol.parent = container.symbol;
  31268. }
  31269. addDeclarationToSymbol(symbol, node, symbolFlags);
  31270. return symbol;
  31271. }
  31272. function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
  31273. switch (blockScopeContainer.kind) {
  31274. case 249 /* ModuleDeclaration */:
  31275. declareModuleMember(node, symbolFlags, symbolExcludes);
  31276. break;
  31277. case 290 /* SourceFile */:
  31278. if (ts.isExternalOrCommonJsModule(container)) {
  31279. declareModuleMember(node, symbolFlags, symbolExcludes);
  31280. break;
  31281. }
  31282. // falls through
  31283. default:
  31284. if (!blockScopeContainer.locals) {
  31285. blockScopeContainer.locals = ts.createSymbolTable();
  31286. addToContainerChain(blockScopeContainer);
  31287. }
  31288. declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
  31289. }
  31290. }
  31291. function delayedBindJSDocTypedefTag() {
  31292. if (!delayedTypeAliases) {
  31293. return;
  31294. }
  31295. var saveContainer = container;
  31296. var saveLastContainer = lastContainer;
  31297. var saveBlockScopeContainer = blockScopeContainer;
  31298. var saveParent = parent;
  31299. var saveCurrentFlow = currentFlow;
  31300. for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
  31301. var typeAlias = delayedTypeAliases_1[_i];
  31302. var host = ts.getJSDocHost(typeAlias);
  31303. container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
  31304. blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
  31305. currentFlow = initFlowNode({ flags: 2 /* Start */ });
  31306. parent = typeAlias;
  31307. bind(typeAlias.typeExpression);
  31308. var declName = ts.getNameOfDeclaration(typeAlias);
  31309. if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
  31310. // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
  31311. var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
  31312. if (isTopLevel) {
  31313. bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
  31314. var oldContainer = container;
  31315. switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
  31316. case 1 /* ExportsProperty */:
  31317. case 2 /* ModuleExports */:
  31318. if (!ts.isExternalOrCommonJsModule(file)) {
  31319. container = undefined;
  31320. }
  31321. else {
  31322. container = file;
  31323. }
  31324. break;
  31325. case 4 /* ThisProperty */:
  31326. container = declName.parent.expression;
  31327. break;
  31328. case 3 /* PrototypeProperty */:
  31329. container = declName.parent.expression.name;
  31330. break;
  31331. case 5 /* Property */:
  31332. container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
  31333. : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
  31334. : declName.parent.expression;
  31335. break;
  31336. case 0 /* None */:
  31337. return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
  31338. }
  31339. if (container) {
  31340. declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
  31341. }
  31342. container = oldContainer;
  31343. }
  31344. }
  31345. else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
  31346. parent = typeAlias.parent;
  31347. bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
  31348. }
  31349. else {
  31350. bind(typeAlias.fullName);
  31351. }
  31352. }
  31353. container = saveContainer;
  31354. lastContainer = saveLastContainer;
  31355. blockScopeContainer = saveBlockScopeContainer;
  31356. parent = saveParent;
  31357. currentFlow = saveCurrentFlow;
  31358. }
  31359. // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
  31360. // check for reserved words used as identifiers in strict mode code.
  31361. function checkStrictModeIdentifier(node) {
  31362. if (inStrictMode &&
  31363. node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
  31364. node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
  31365. !ts.isIdentifierName(node) &&
  31366. !(node.flags & 8388608 /* Ambient */) &&
  31367. !(node.flags & 4194304 /* JSDoc */)) {
  31368. // Report error only if there are no parse errors in file
  31369. if (!file.parseDiagnostics.length) {
  31370. file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
  31371. }
  31372. }
  31373. }
  31374. function getStrictModeIdentifierMessage(node) {
  31375. // Provide specialized messages to help the user understand why we think they're in
  31376. // strict mode.
  31377. if (ts.getContainingClass(node)) {
  31378. return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
  31379. }
  31380. if (file.externalModuleIndicator) {
  31381. return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
  31382. }
  31383. return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
  31384. }
  31385. // The binder visits every node, so this is a good place to check for
  31386. // the reserved private name (there is only one)
  31387. function checkPrivateIdentifier(node) {
  31388. if (node.escapedText === "#constructor") {
  31389. // Report error only if there are no parse errors in file
  31390. if (!file.parseDiagnostics.length) {
  31391. file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
  31392. }
  31393. }
  31394. }
  31395. function checkStrictModeBinaryExpression(node) {
  31396. if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
  31397. // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
  31398. // Assignment operator(11.13) or of a PostfixExpression(11.3)
  31399. checkStrictModeEvalOrArguments(node, node.left);
  31400. }
  31401. }
  31402. function checkStrictModeCatchClause(node) {
  31403. // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
  31404. // Catch production is eval or arguments
  31405. if (inStrictMode && node.variableDeclaration) {
  31406. checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
  31407. }
  31408. }
  31409. function checkStrictModeDeleteExpression(node) {
  31410. // Grammar checking
  31411. if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
  31412. // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
  31413. // UnaryExpression is a direct reference to a variable, function argument, or function name
  31414. var span = ts.getErrorSpanForNode(file, node.expression);
  31415. file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
  31416. }
  31417. }
  31418. function isEvalOrArgumentsIdentifier(node) {
  31419. return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
  31420. }
  31421. function checkStrictModeEvalOrArguments(contextNode, name) {
  31422. if (name && name.kind === 75 /* Identifier */) {
  31423. var identifier = name;
  31424. if (isEvalOrArgumentsIdentifier(identifier)) {
  31425. // We check first if the name is inside class declaration or class expression; if so give explicit message
  31426. // otherwise report generic error message.
  31427. var span = ts.getErrorSpanForNode(file, name);
  31428. file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
  31429. }
  31430. }
  31431. }
  31432. function getStrictModeEvalOrArgumentsMessage(node) {
  31433. // Provide specialized messages to help the user understand why we think they're in
  31434. // strict mode.
  31435. if (ts.getContainingClass(node)) {
  31436. return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
  31437. }
  31438. if (file.externalModuleIndicator) {
  31439. return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
  31440. }
  31441. return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
  31442. }
  31443. function checkStrictModeFunctionName(node) {
  31444. if (inStrictMode) {
  31445. // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
  31446. checkStrictModeEvalOrArguments(node, node.name);
  31447. }
  31448. }
  31449. function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
  31450. // Provide specialized messages to help the user understand why we think they're in
  31451. // strict mode.
  31452. if (ts.getContainingClass(node)) {
  31453. return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;
  31454. }
  31455. if (file.externalModuleIndicator) {
  31456. return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
  31457. }
  31458. return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
  31459. }
  31460. function checkStrictModeFunctionDeclaration(node) {
  31461. if (languageVersion < 2 /* ES2015 */) {
  31462. // Report error if function is not top level function declaration
  31463. if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
  31464. blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
  31465. !ts.isFunctionLike(blockScopeContainer)) {
  31466. // We check first if the name is inside class declaration or class expression; if so give explicit message
  31467. // otherwise report generic error message.
  31468. var errorSpan = ts.getErrorSpanForNode(file, node);
  31469. file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
  31470. }
  31471. }
  31472. }
  31473. function checkStrictModeNumericLiteral(node) {
  31474. if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
  31475. file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
  31476. }
  31477. }
  31478. function checkStrictModePostfixUnaryExpression(node) {
  31479. // Grammar checking
  31480. // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
  31481. // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
  31482. // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
  31483. if (inStrictMode) {
  31484. checkStrictModeEvalOrArguments(node, node.operand);
  31485. }
  31486. }
  31487. function checkStrictModePrefixUnaryExpression(node) {
  31488. // Grammar checking
  31489. if (inStrictMode) {
  31490. if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
  31491. checkStrictModeEvalOrArguments(node, node.operand);
  31492. }
  31493. }
  31494. }
  31495. function checkStrictModeWithStatement(node) {
  31496. // Grammar checking for withStatement
  31497. if (inStrictMode) {
  31498. errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
  31499. }
  31500. }
  31501. function checkStrictModeLabeledStatement(node) {
  31502. // Grammar checking for labeledStatement
  31503. if (inStrictMode && options.target >= 2 /* ES2015 */) {
  31504. if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
  31505. errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
  31506. }
  31507. }
  31508. }
  31509. function errorOnFirstToken(node, message, arg0, arg1, arg2) {
  31510. var span = ts.getSpanOfTokenAtPosition(file, node.pos);
  31511. file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
  31512. }
  31513. function errorOrSuggestionOnNode(isError, node, message) {
  31514. errorOrSuggestionOnRange(isError, node, node, message);
  31515. }
  31516. function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
  31517. addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
  31518. }
  31519. function addErrorOrSuggestionDiagnostic(isError, range, message) {
  31520. var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
  31521. if (isError) {
  31522. file.bindDiagnostics.push(diag);
  31523. }
  31524. else {
  31525. file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
  31526. }
  31527. }
  31528. function bind(node) {
  31529. if (!node) {
  31530. return;
  31531. }
  31532. node.parent = parent;
  31533. var saveInStrictMode = inStrictMode;
  31534. // Even though in the AST the jsdoc @typedef node belongs to the current node,
  31535. // its symbol might be in the same scope with the current node's symbol. Consider:
  31536. //
  31537. // /** @typedef {string | number} MyType */
  31538. // function foo();
  31539. //
  31540. // Here the current node is "foo", which is a container, but the scope of "MyType" should
  31541. // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
  31542. // and skip binding this tag later when binding all the other jsdoc tags.
  31543. // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
  31544. // and then potentially add the symbol to an appropriate symbol table. Possible
  31545. // destination symbol tables are:
  31546. //
  31547. // 1) The 'exports' table of the current container's symbol.
  31548. // 2) The 'members' table of the current container's symbol.
  31549. // 3) The 'locals' table of the current container.
  31550. //
  31551. // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
  31552. // (like TypeLiterals for example) will not be put in any table.
  31553. bindWorker(node);
  31554. // Then we recurse into the children of the node to bind them as well. For certain
  31555. // symbols we do specialized work when we recurse. For example, we'll keep track of
  31556. // the current 'container' node when it changes. This helps us know which symbol table
  31557. // a local should go into for example. Since terminal nodes are known not to have
  31558. // children, as an optimization we don't process those.
  31559. if (node.kind > 152 /* LastToken */) {
  31560. var saveParent = parent;
  31561. parent = node;
  31562. var containerFlags = getContainerFlags(node);
  31563. if (containerFlags === 0 /* None */) {
  31564. bindChildren(node);
  31565. }
  31566. else {
  31567. bindContainer(node, containerFlags);
  31568. }
  31569. parent = saveParent;
  31570. }
  31571. else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
  31572. subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
  31573. var saveParent = parent;
  31574. if (node.kind === 1 /* EndOfFileToken */)
  31575. parent = node;
  31576. bindJSDoc(node);
  31577. parent = saveParent;
  31578. }
  31579. inStrictMode = saveInStrictMode;
  31580. }
  31581. function bindJSDoc(node) {
  31582. if (ts.hasJSDocNodes(node)) {
  31583. if (ts.isInJSFile(node)) {
  31584. for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
  31585. var j = _a[_i];
  31586. bind(j);
  31587. }
  31588. }
  31589. else {
  31590. for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
  31591. var j = _c[_b];
  31592. setParentPointers(node, j);
  31593. }
  31594. }
  31595. }
  31596. }
  31597. function updateStrictModeStatementList(statements) {
  31598. if (!inStrictMode) {
  31599. for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
  31600. var statement = statements_2[_i];
  31601. if (!ts.isPrologueDirective(statement)) {
  31602. return;
  31603. }
  31604. if (isUseStrictPrologueDirective(statement)) {
  31605. inStrictMode = true;
  31606. return;
  31607. }
  31608. }
  31609. }
  31610. }
  31611. /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
  31612. function isUseStrictPrologueDirective(node) {
  31613. var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
  31614. // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
  31615. // string to contain unicode escapes (as per ES5).
  31616. return nodeText === '"use strict"' || nodeText === "'use strict'";
  31617. }
  31618. function bindWorker(node) {
  31619. switch (node.kind) {
  31620. /* Strict mode checks */
  31621. case 75 /* Identifier */:
  31622. // for typedef type names with namespaces, bind the new jsdoc type symbol here
  31623. // because it requires all containing namespaces to be in effect, namely the
  31624. // current "blockScopeContainer" needs to be set to its immediate namespace parent.
  31625. if (node.isInJSDocNamespace) {
  31626. var parentNode = node.parent;
  31627. while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
  31628. parentNode = parentNode.parent;
  31629. }
  31630. bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
  31631. break;
  31632. }
  31633. // falls through
  31634. case 104 /* ThisKeyword */:
  31635. if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
  31636. node.flowNode = currentFlow;
  31637. }
  31638. return checkStrictModeIdentifier(node);
  31639. case 76 /* PrivateIdentifier */:
  31640. return checkPrivateIdentifier(node);
  31641. case 194 /* PropertyAccessExpression */:
  31642. case 195 /* ElementAccessExpression */:
  31643. var expr = node;
  31644. if (currentFlow && isNarrowableReference(expr)) {
  31645. expr.flowNode = currentFlow;
  31646. }
  31647. if (ts.isSpecialPropertyDeclaration(expr)) {
  31648. bindSpecialPropertyDeclaration(expr);
  31649. }
  31650. if (ts.isInJSFile(expr) &&
  31651. file.commonJsModuleIndicator &&
  31652. ts.isModuleExportsAccessExpression(expr) &&
  31653. !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
  31654. declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
  31655. }
  31656. break;
  31657. case 209 /* BinaryExpression */:
  31658. var specialKind = ts.getAssignmentDeclarationKind(node);
  31659. switch (specialKind) {
  31660. case 1 /* ExportsProperty */:
  31661. bindExportsPropertyAssignment(node);
  31662. break;
  31663. case 2 /* ModuleExports */:
  31664. bindModuleExportsAssignment(node);
  31665. break;
  31666. case 3 /* PrototypeProperty */:
  31667. bindPrototypePropertyAssignment(node.left, node);
  31668. break;
  31669. case 6 /* Prototype */:
  31670. bindPrototypeAssignment(node);
  31671. break;
  31672. case 4 /* ThisProperty */:
  31673. bindThisPropertyAssignment(node);
  31674. break;
  31675. case 5 /* Property */:
  31676. bindSpecialPropertyAssignment(node);
  31677. break;
  31678. case 0 /* None */:
  31679. // Nothing to do
  31680. break;
  31681. default:
  31682. ts.Debug.fail("Unknown binary expression special property assignment kind");
  31683. }
  31684. return checkStrictModeBinaryExpression(node);
  31685. case 280 /* CatchClause */:
  31686. return checkStrictModeCatchClause(node);
  31687. case 203 /* DeleteExpression */:
  31688. return checkStrictModeDeleteExpression(node);
  31689. case 8 /* NumericLiteral */:
  31690. return checkStrictModeNumericLiteral(node);
  31691. case 208 /* PostfixUnaryExpression */:
  31692. return checkStrictModePostfixUnaryExpression(node);
  31693. case 207 /* PrefixUnaryExpression */:
  31694. return checkStrictModePrefixUnaryExpression(node);
  31695. case 236 /* WithStatement */:
  31696. return checkStrictModeWithStatement(node);
  31697. case 238 /* LabeledStatement */:
  31698. return checkStrictModeLabeledStatement(node);
  31699. case 183 /* ThisType */:
  31700. seenThisKeyword = true;
  31701. return;
  31702. case 168 /* TypePredicate */:
  31703. break; // Binding the children will handle everything
  31704. case 155 /* TypeParameter */:
  31705. return bindTypeParameter(node);
  31706. case 156 /* Parameter */:
  31707. return bindParameter(node);
  31708. case 242 /* VariableDeclaration */:
  31709. return bindVariableDeclarationOrBindingElement(node);
  31710. case 191 /* BindingElement */:
  31711. node.flowNode = currentFlow;
  31712. return bindVariableDeclarationOrBindingElement(node);
  31713. case 159 /* PropertyDeclaration */:
  31714. case 158 /* PropertySignature */:
  31715. return bindPropertyWorker(node);
  31716. case 281 /* PropertyAssignment */:
  31717. case 282 /* ShorthandPropertyAssignment */:
  31718. return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
  31719. case 284 /* EnumMember */:
  31720. return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
  31721. case 165 /* CallSignature */:
  31722. case 166 /* ConstructSignature */:
  31723. case 167 /* IndexSignature */:
  31724. return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
  31725. case 161 /* MethodDeclaration */:
  31726. case 160 /* MethodSignature */:
  31727. // If this is an ObjectLiteralExpression method, then it sits in the same space
  31728. // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
  31729. // so that it will conflict with any other object literal members with the same
  31730. // name.
  31731. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
  31732. case 244 /* FunctionDeclaration */:
  31733. return bindFunctionDeclaration(node);
  31734. case 162 /* Constructor */:
  31735. return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
  31736. case 163 /* GetAccessor */:
  31737. return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
  31738. case 164 /* SetAccessor */:
  31739. return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
  31740. case 170 /* FunctionType */:
  31741. case 300 /* JSDocFunctionType */:
  31742. case 305 /* JSDocSignature */:
  31743. case 171 /* ConstructorType */:
  31744. return bindFunctionOrConstructorType(node);
  31745. case 173 /* TypeLiteral */:
  31746. case 304 /* JSDocTypeLiteral */:
  31747. case 186 /* MappedType */:
  31748. return bindAnonymousTypeWorker(node);
  31749. case 309 /* JSDocClassTag */:
  31750. return bindJSDocClassTag(node);
  31751. case 193 /* ObjectLiteralExpression */:
  31752. return bindObjectLiteralExpression(node);
  31753. case 201 /* FunctionExpression */:
  31754. case 202 /* ArrowFunction */:
  31755. return bindFunctionExpression(node);
  31756. case 196 /* CallExpression */:
  31757. var assignmentKind = ts.getAssignmentDeclarationKind(node);
  31758. switch (assignmentKind) {
  31759. case 7 /* ObjectDefinePropertyValue */:
  31760. return bindObjectDefinePropertyAssignment(node);
  31761. case 8 /* ObjectDefinePropertyExports */:
  31762. return bindObjectDefinePropertyExport(node);
  31763. case 9 /* ObjectDefinePrototypeProperty */:
  31764. return bindObjectDefinePrototypeProperty(node);
  31765. case 0 /* None */:
  31766. break; // Nothing to do
  31767. default:
  31768. return ts.Debug.fail("Unknown call expression assignment declaration kind");
  31769. }
  31770. if (ts.isInJSFile(node)) {
  31771. bindCallExpression(node);
  31772. }
  31773. break;
  31774. // Members of classes, interfaces, and modules
  31775. case 214 /* ClassExpression */:
  31776. case 245 /* ClassDeclaration */:
  31777. // All classes are automatically in strict mode in ES6.
  31778. inStrictMode = true;
  31779. return bindClassLikeDeclaration(node);
  31780. case 246 /* InterfaceDeclaration */:
  31781. return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
  31782. case 247 /* TypeAliasDeclaration */:
  31783. return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
  31784. case 248 /* EnumDeclaration */:
  31785. return bindEnumDeclaration(node);
  31786. case 249 /* ModuleDeclaration */:
  31787. return bindModuleDeclaration(node);
  31788. // Jsx-attributes
  31789. case 274 /* JsxAttributes */:
  31790. return bindJsxAttributes(node);
  31791. case 273 /* JsxAttribute */:
  31792. return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
  31793. // Imports and exports
  31794. case 253 /* ImportEqualsDeclaration */:
  31795. case 256 /* NamespaceImport */:
  31796. case 258 /* ImportSpecifier */:
  31797. case 263 /* ExportSpecifier */:
  31798. return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
  31799. case 252 /* NamespaceExportDeclaration */:
  31800. return bindNamespaceExportDeclaration(node);
  31801. case 255 /* ImportClause */:
  31802. return bindImportClause(node);
  31803. case 260 /* ExportDeclaration */:
  31804. return bindExportDeclaration(node);
  31805. case 259 /* ExportAssignment */:
  31806. return bindExportAssignment(node);
  31807. case 290 /* SourceFile */:
  31808. updateStrictModeStatementList(node.statements);
  31809. return bindSourceFileIfExternalModule();
  31810. case 223 /* Block */:
  31811. if (!ts.isFunctionLike(node.parent)) {
  31812. return;
  31813. }
  31814. // falls through
  31815. case 250 /* ModuleBlock */:
  31816. return updateStrictModeStatementList(node.statements);
  31817. case 316 /* JSDocParameterTag */:
  31818. if (node.parent.kind === 305 /* JSDocSignature */) {
  31819. return bindParameter(node);
  31820. }
  31821. if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
  31822. break;
  31823. }
  31824. // falls through
  31825. case 322 /* JSDocPropertyTag */:
  31826. var propTag = node;
  31827. var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
  31828. 4 /* Property */ | 16777216 /* Optional */ :
  31829. 4 /* Property */;
  31830. return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
  31831. case 321 /* JSDocTypedefTag */:
  31832. case 314 /* JSDocCallbackTag */:
  31833. case 315 /* JSDocEnumTag */:
  31834. return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
  31835. }
  31836. }
  31837. function bindPropertyWorker(node) {
  31838. return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
  31839. }
  31840. function bindAnonymousTypeWorker(node) {
  31841. return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
  31842. }
  31843. function bindSourceFileIfExternalModule() {
  31844. setExportContextFlag(file);
  31845. if (ts.isExternalModule(file)) {
  31846. bindSourceFileAsExternalModule();
  31847. }
  31848. else if (ts.isJsonSourceFile(file)) {
  31849. bindSourceFileAsExternalModule();
  31850. // Create symbol equivalent for the module.exports = {}
  31851. var originalSymbol = file.symbol;
  31852. declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
  31853. file.symbol = originalSymbol;
  31854. }
  31855. }
  31856. function bindSourceFileAsExternalModule() {
  31857. bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
  31858. }
  31859. function bindExportAssignment(node) {
  31860. if (!container.symbol || !container.symbol.exports) {
  31861. // Export assignment in some sort of block construct
  31862. bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
  31863. }
  31864. else {
  31865. var flags = ts.exportAssignmentIsAlias(node)
  31866. // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
  31867. ? 2097152 /* Alias */
  31868. // An export default clause with any other expression exports a value
  31869. : 4 /* Property */;
  31870. // If there is an `export default x;` alias declaration, can't `export default` anything else.
  31871. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
  31872. var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
  31873. if (node.isExportEquals) {
  31874. // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
  31875. setValueDeclaration(symbol, node);
  31876. }
  31877. }
  31878. }
  31879. function bindNamespaceExportDeclaration(node) {
  31880. if (node.modifiers && node.modifiers.length) {
  31881. file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
  31882. }
  31883. var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
  31884. : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
  31885. : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
  31886. : undefined;
  31887. if (diag) {
  31888. file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
  31889. }
  31890. else {
  31891. file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
  31892. declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
  31893. }
  31894. }
  31895. function bindExportDeclaration(node) {
  31896. if (!container.symbol || !container.symbol.exports) {
  31897. // Export * in some sort of block construct
  31898. bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
  31899. }
  31900. else if (!node.exportClause) {
  31901. // All export * declarations are collected in an __export symbol
  31902. declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
  31903. }
  31904. else if (ts.isNamespaceExport(node.exportClause)) {
  31905. // declareSymbol walks up parents to find name text, parent _must_ be set
  31906. // but won't be set by the normal binder walk until `bindChildren` later on.
  31907. node.exportClause.parent = node;
  31908. declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
  31909. }
  31910. }
  31911. function bindImportClause(node) {
  31912. if (node.name) {
  31913. declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
  31914. }
  31915. }
  31916. function setCommonJsModuleIndicator(node) {
  31917. if (file.externalModuleIndicator) {
  31918. return false;
  31919. }
  31920. if (!file.commonJsModuleIndicator) {
  31921. file.commonJsModuleIndicator = node;
  31922. bindSourceFileAsExternalModule();
  31923. }
  31924. return true;
  31925. }
  31926. function bindObjectDefinePropertyExport(node) {
  31927. if (!setCommonJsModuleIndicator(node)) {
  31928. return;
  31929. }
  31930. var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
  31931. if (symbol) {
  31932. addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
  31933. }
  31934. return symbol;
  31935. });
  31936. if (symbol) {
  31937. var flags = 4 /* Property */ | 1048576 /* ExportValue */;
  31938. declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
  31939. }
  31940. }
  31941. function bindExportsPropertyAssignment(node) {
  31942. // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
  31943. // expression is the declaration
  31944. if (!setCommonJsModuleIndicator(node)) {
  31945. return;
  31946. }
  31947. var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
  31948. if (symbol) {
  31949. addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
  31950. }
  31951. return symbol;
  31952. });
  31953. if (symbol) {
  31954. var flags = ts.isClassExpression(node.right) ?
  31955. 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
  31956. 4 /* Property */ | 1048576 /* ExportValue */;
  31957. declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
  31958. }
  31959. }
  31960. function bindModuleExportsAssignment(node) {
  31961. // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
  31962. // is still pointing to 'module.exports'.
  31963. // We do not want to consider this as 'export=' since a module can have only one of these.
  31964. // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
  31965. if (!setCommonJsModuleIndicator(node)) {
  31966. return;
  31967. }
  31968. var assignedExpression = ts.getRightMostAssignedExpression(node.right);
  31969. if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
  31970. return;
  31971. }
  31972. // 'module.exports = expr' assignment
  31973. var flags = ts.exportAssignmentIsAlias(node)
  31974. ? 2097152 /* Alias */
  31975. : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
  31976. var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
  31977. setValueDeclaration(symbol, node);
  31978. }
  31979. function bindThisPropertyAssignment(node) {
  31980. ts.Debug.assert(ts.isInJSFile(node));
  31981. // private identifiers *must* be declared (even in JS files)
  31982. var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
  31983. || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
  31984. if (hasPrivateIdentifier) {
  31985. return;
  31986. }
  31987. var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
  31988. switch (thisContainer.kind) {
  31989. case 244 /* FunctionDeclaration */:
  31990. case 201 /* FunctionExpression */:
  31991. var constructorSymbol = thisContainer.symbol;
  31992. // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
  31993. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
  31994. var l = thisContainer.parent.left;
  31995. if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
  31996. constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
  31997. }
  31998. }
  31999. if (constructorSymbol && constructorSymbol.valueDeclaration) {
  32000. // Declare a 'member' if the container is an ES5 class or ES6 constructor
  32001. constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
  32002. // It's acceptable for multiple 'this' assignments of the same identifier to occur
  32003. if (ts.hasDynamicName(node)) {
  32004. bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
  32005. }
  32006. else {
  32007. declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
  32008. }
  32009. addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
  32010. }
  32011. break;
  32012. case 162 /* Constructor */:
  32013. case 159 /* PropertyDeclaration */:
  32014. case 161 /* MethodDeclaration */:
  32015. case 163 /* GetAccessor */:
  32016. case 164 /* SetAccessor */:
  32017. // this.foo assignment in a JavaScript class
  32018. // Bind this property to the containing class
  32019. var containingClass = thisContainer.parent;
  32020. var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
  32021. if (ts.hasDynamicName(node)) {
  32022. bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
  32023. }
  32024. else {
  32025. declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
  32026. }
  32027. break;
  32028. case 290 /* SourceFile */:
  32029. // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
  32030. if (ts.hasDynamicName(node)) {
  32031. break;
  32032. }
  32033. else if (thisContainer.commonJsModuleIndicator) {
  32034. declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
  32035. }
  32036. else {
  32037. declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
  32038. }
  32039. break;
  32040. default:
  32041. ts.Debug.failBadSyntaxKind(thisContainer);
  32042. }
  32043. }
  32044. function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
  32045. bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
  32046. addLateBoundAssignmentDeclarationToSymbol(node, symbol);
  32047. }
  32048. function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
  32049. if (symbol) {
  32050. var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
  32051. members.set("" + ts.getNodeId(node), node);
  32052. }
  32053. }
  32054. function bindSpecialPropertyDeclaration(node) {
  32055. if (node.expression.kind === 104 /* ThisKeyword */) {
  32056. bindThisPropertyAssignment(node);
  32057. }
  32058. else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
  32059. if (ts.isPrototypeAccess(node.expression)) {
  32060. bindPrototypePropertyAssignment(node, node.parent);
  32061. }
  32062. else {
  32063. bindStaticPropertyAssignment(node);
  32064. }
  32065. }
  32066. }
  32067. /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
  32068. function bindPrototypeAssignment(node) {
  32069. node.left.parent = node;
  32070. node.right.parent = node;
  32071. bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
  32072. }
  32073. function bindObjectDefinePrototypeProperty(node) {
  32074. var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
  32075. if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
  32076. // Ensure the namespace symbol becomes class-like
  32077. addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
  32078. }
  32079. bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
  32080. }
  32081. /**
  32082. * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
  32083. * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
  32084. */
  32085. function bindPrototypePropertyAssignment(lhs, parent) {
  32086. // Look up the function in the local scope, since prototype assignments should
  32087. // follow the function declaration
  32088. var classPrototype = lhs.expression;
  32089. var constructorFunction = classPrototype.expression;
  32090. // Fix up parent pointers since we're going to use these nodes before we bind into them
  32091. lhs.parent = parent;
  32092. constructorFunction.parent = classPrototype;
  32093. classPrototype.parent = lhs;
  32094. bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
  32095. }
  32096. function bindObjectDefinePropertyAssignment(node) {
  32097. var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
  32098. var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
  32099. namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
  32100. bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
  32101. }
  32102. function bindSpecialPropertyAssignment(node) {
  32103. // Class declarations in Typescript do not allow property declarations
  32104. var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
  32105. if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
  32106. return;
  32107. }
  32108. // Fix up parent pointers since we're going to use these nodes before we bind into them
  32109. node.left.parent = node;
  32110. node.right.parent = node;
  32111. if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
  32112. // This can be an alias for the 'exports' or 'module.exports' names, e.g.
  32113. // var util = module.exports;
  32114. // util.property = function ...
  32115. bindExportsPropertyAssignment(node);
  32116. }
  32117. else {
  32118. if (ts.hasDynamicName(node)) {
  32119. bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
  32120. var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
  32121. addLateBoundAssignmentDeclarationToSymbol(node, sym);
  32122. }
  32123. else {
  32124. bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticAccessExpression));
  32125. }
  32126. }
  32127. }
  32128. /**
  32129. * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared.
  32130. * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
  32131. */
  32132. function bindStaticPropertyAssignment(node) {
  32133. node.expression.parent = node;
  32134. bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
  32135. }
  32136. function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
  32137. if (isToplevel && !isPrototypeProperty) {
  32138. // make symbols or add declarations for intermediate containers
  32139. var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
  32140. var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
  32141. namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
  32142. if (symbol) {
  32143. addDeclarationToSymbol(symbol, id, flags_1);
  32144. return symbol;
  32145. }
  32146. else {
  32147. var table = parent ? parent.exports :
  32148. file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
  32149. return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
  32150. }
  32151. });
  32152. }
  32153. if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
  32154. addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
  32155. }
  32156. return namespaceSymbol;
  32157. }
  32158. function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
  32159. if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
  32160. return;
  32161. }
  32162. // Set up the members collection if it doesn't exist already
  32163. var symbolTable = isPrototypeProperty ?
  32164. (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
  32165. (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
  32166. var includes = 0 /* None */;
  32167. var excludes = 0 /* None */;
  32168. // Method-like
  32169. if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
  32170. includes = 8192 /* Method */;
  32171. excludes = 103359 /* MethodExcludes */;
  32172. }
  32173. // Maybe accessor-like
  32174. else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
  32175. if (ts.some(declaration.arguments[2].properties, function (p) {
  32176. var id = ts.getNameOfDeclaration(p);
  32177. return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
  32178. })) {
  32179. // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
  32180. // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
  32181. includes |= 65536 /* SetAccessor */ | 4 /* Property */;
  32182. excludes |= 78783 /* SetAccessorExcludes */;
  32183. }
  32184. if (ts.some(declaration.arguments[2].properties, function (p) {
  32185. var id = ts.getNameOfDeclaration(p);
  32186. return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
  32187. })) {
  32188. includes |= 32768 /* GetAccessor */ | 4 /* Property */;
  32189. excludes |= 46015 /* GetAccessorExcludes */;
  32190. }
  32191. }
  32192. if (includes === 0 /* None */) {
  32193. includes = 4 /* Property */;
  32194. excludes = 0 /* PropertyExcludes */;
  32195. }
  32196. declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
  32197. }
  32198. function isTopLevelNamespaceAssignment(propertyAccess) {
  32199. return ts.isBinaryExpression(propertyAccess.parent)
  32200. ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
  32201. : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
  32202. }
  32203. function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
  32204. var namespaceSymbol = lookupSymbolForPropertyAccess(name);
  32205. var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
  32206. namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
  32207. bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
  32208. }
  32209. /**
  32210. * Javascript expando values are:
  32211. * - Functions
  32212. * - classes
  32213. * - namespaces
  32214. * - variables initialized with function expressions
  32215. * - with class expressions
  32216. * - with empty object literals
  32217. * - with non-empty object literals if assigned to the prototype property
  32218. */
  32219. function isExpandoSymbol(symbol) {
  32220. if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
  32221. return true;
  32222. }
  32223. var node = symbol.valueDeclaration;
  32224. if (node && ts.isCallExpression(node)) {
  32225. return !!ts.getAssignedExpandoInitializer(node);
  32226. }
  32227. var init = !node ? undefined :
  32228. ts.isVariableDeclaration(node) ? node.initializer :
  32229. ts.isBinaryExpression(node) ? node.right :
  32230. ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
  32231. undefined;
  32232. init = init && ts.getRightMostAssignedExpression(init);
  32233. if (init) {
  32234. var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
  32235. return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
  32236. }
  32237. return false;
  32238. }
  32239. function getParentOfBinaryExpression(expr) {
  32240. while (ts.isBinaryExpression(expr.parent)) {
  32241. expr = expr.parent;
  32242. }
  32243. return expr.parent;
  32244. }
  32245. function lookupSymbolForPropertyAccess(node, lookupContainer) {
  32246. if (lookupContainer === void 0) { lookupContainer = container; }
  32247. if (ts.isIdentifier(node)) {
  32248. return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
  32249. }
  32250. else {
  32251. var symbol = lookupSymbolForPropertyAccess(node.expression);
  32252. return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
  32253. }
  32254. }
  32255. function forEachIdentifierInEntityName(e, parent, action) {
  32256. if (isExportsOrModuleExportsOrAlias(file, e)) {
  32257. return file.symbol;
  32258. }
  32259. else if (ts.isIdentifier(e)) {
  32260. return action(e, lookupSymbolForPropertyAccess(e), parent);
  32261. }
  32262. else {
  32263. var s = forEachIdentifierInEntityName(e.expression, parent, action);
  32264. var name = ts.getNameOrArgument(e);
  32265. // unreachable
  32266. if (ts.isPrivateIdentifier(name)) {
  32267. ts.Debug.fail("unexpected PrivateIdentifier");
  32268. }
  32269. return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
  32270. }
  32271. }
  32272. function bindCallExpression(node) {
  32273. // We're only inspecting call expressions to detect CommonJS modules, so we can skip
  32274. // this check if we've already seen the module indicator
  32275. if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
  32276. setCommonJsModuleIndicator(node);
  32277. }
  32278. }
  32279. function bindClassLikeDeclaration(node) {
  32280. if (node.kind === 245 /* ClassDeclaration */) {
  32281. bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
  32282. }
  32283. else {
  32284. var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
  32285. bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
  32286. // Add name of class expression into the map for semantic classifier
  32287. if (node.name) {
  32288. classifiableNames.set(node.name.escapedText, true);
  32289. }
  32290. }
  32291. var symbol = node.symbol;
  32292. // TypeScript 1.0 spec (April 2014): 8.4
  32293. // Every class automatically contains a static property member named 'prototype', the
  32294. // type of which is an instantiation of the class type with type Any supplied as a type
  32295. // argument for each type parameter. It is an error to explicitly declare a static
  32296. // property member with the name 'prototype'.
  32297. //
  32298. // Note: we check for this here because this class may be merging into a module. The
  32299. // module might have an exported variable called 'prototype'. We can't allow that as
  32300. // that would clash with the built-in 'prototype' for the class.
  32301. var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
  32302. var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
  32303. if (symbolExport) {
  32304. if (node.name) {
  32305. node.name.parent = node;
  32306. }
  32307. file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
  32308. }
  32309. symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
  32310. prototypeSymbol.parent = symbol;
  32311. }
  32312. function bindEnumDeclaration(node) {
  32313. return ts.isEnumConst(node)
  32314. ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
  32315. : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
  32316. }
  32317. function bindVariableDeclarationOrBindingElement(node) {
  32318. if (inStrictMode) {
  32319. checkStrictModeEvalOrArguments(node, node.name);
  32320. }
  32321. if (!ts.isBindingPattern(node.name)) {
  32322. if (ts.isBlockOrCatchScoped(node)) {
  32323. bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
  32324. }
  32325. else if (ts.isParameterDeclaration(node)) {
  32326. // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
  32327. // because its parent chain has already been set up, since parents are set before descending into children.
  32328. //
  32329. // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
  32330. // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
  32331. // For example:
  32332. // function foo([a,a]) {} // Duplicate Identifier error
  32333. // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
  32334. // // which correctly set excluded symbols
  32335. declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
  32336. }
  32337. else {
  32338. declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
  32339. }
  32340. }
  32341. }
  32342. function bindParameter(node) {
  32343. if (node.kind === 316 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
  32344. return;
  32345. }
  32346. if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
  32347. // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
  32348. // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
  32349. checkStrictModeEvalOrArguments(node, node.name);
  32350. }
  32351. if (ts.isBindingPattern(node.name)) {
  32352. bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
  32353. }
  32354. else {
  32355. declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
  32356. }
  32357. // If this is a property-parameter, then also declare the property symbol into the
  32358. // containing class.
  32359. if (ts.isParameterPropertyDeclaration(node, node.parent)) {
  32360. var classDeclaration = node.parent.parent;
  32361. declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
  32362. }
  32363. }
  32364. function bindFunctionDeclaration(node) {
  32365. if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
  32366. if (ts.isAsyncFunction(node)) {
  32367. emitFlags |= 2048 /* HasAsyncFunctions */;
  32368. }
  32369. }
  32370. checkStrictModeFunctionName(node);
  32371. if (inStrictMode) {
  32372. checkStrictModeFunctionDeclaration(node);
  32373. bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
  32374. }
  32375. else {
  32376. declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
  32377. }
  32378. }
  32379. function bindFunctionExpression(node) {
  32380. if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
  32381. if (ts.isAsyncFunction(node)) {
  32382. emitFlags |= 2048 /* HasAsyncFunctions */;
  32383. }
  32384. }
  32385. if (currentFlow) {
  32386. node.flowNode = currentFlow;
  32387. }
  32388. checkStrictModeFunctionName(node);
  32389. var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
  32390. return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
  32391. }
  32392. function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
  32393. if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
  32394. emitFlags |= 2048 /* HasAsyncFunctions */;
  32395. }
  32396. if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
  32397. node.flowNode = currentFlow;
  32398. }
  32399. return ts.hasDynamicName(node)
  32400. ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
  32401. : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
  32402. }
  32403. function getInferTypeContainer(node) {
  32404. var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
  32405. return extendsType && extendsType.parent;
  32406. }
  32407. function bindTypeParameter(node) {
  32408. if (ts.isJSDocTemplateTag(node.parent)) {
  32409. var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
  32410. if (container_1) {
  32411. if (!container_1.locals) {
  32412. container_1.locals = ts.createSymbolTable();
  32413. }
  32414. declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
  32415. }
  32416. else {
  32417. declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
  32418. }
  32419. }
  32420. else if (node.parent.kind === 181 /* InferType */) {
  32421. var container_2 = getInferTypeContainer(node.parent);
  32422. if (container_2) {
  32423. if (!container_2.locals) {
  32424. container_2.locals = ts.createSymbolTable();
  32425. }
  32426. declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
  32427. }
  32428. else {
  32429. bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
  32430. }
  32431. }
  32432. else {
  32433. declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
  32434. }
  32435. }
  32436. // reachability checks
  32437. function shouldReportErrorOnModuleDeclaration(node) {
  32438. var instanceState = getModuleInstanceState(node);
  32439. return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
  32440. }
  32441. function checkUnreachable(node) {
  32442. if (!(currentFlow.flags & 1 /* Unreachable */)) {
  32443. return false;
  32444. }
  32445. if (currentFlow === unreachableFlow) {
  32446. var reportError =
  32447. // report error on all statements except empty ones
  32448. (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
  32449. // report error on class declarations
  32450. node.kind === 245 /* ClassDeclaration */ ||
  32451. // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
  32452. (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
  32453. if (reportError) {
  32454. currentFlow = reportedUnreachableFlow;
  32455. if (!options.allowUnreachableCode) {
  32456. // unreachable code is reported if
  32457. // - user has explicitly asked about it AND
  32458. // - statement is in not ambient context (statements in ambient context is already an error
  32459. // so we should not report extras) AND
  32460. // - node is not variable statement OR
  32461. // - node is block scoped variable statement OR
  32462. // - node is not block scoped variable statement and at least one variable declaration has initializer
  32463. // Rationale: we don't want to report errors on non-initialized var's since they are hoisted
  32464. // On the other side we do want to report errors on non-initialized 'lets' because of TDZ
  32465. var isError_1 = ts.unreachableCodeIsError(options) &&
  32466. !(node.flags & 8388608 /* Ambient */) &&
  32467. (!ts.isVariableStatement(node) ||
  32468. !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
  32469. node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
  32470. eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
  32471. }
  32472. }
  32473. }
  32474. return true;
  32475. }
  32476. }
  32477. function eachUnreachableRange(node, cb) {
  32478. if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
  32479. var statements = node.parent.statements;
  32480. var slice_1 = ts.sliceAfter(statements, node);
  32481. ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
  32482. }
  32483. else {
  32484. cb(node, node);
  32485. }
  32486. }
  32487. // As opposed to a pure declaration like an `interface`
  32488. function isExecutableStatement(s) {
  32489. // Don't remove statements that can validly be used before they appear.
  32490. return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
  32491. // `var x;` may declare a variable used above
  32492. !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
  32493. }
  32494. function isPurelyTypeDeclaration(s) {
  32495. switch (s.kind) {
  32496. case 246 /* InterfaceDeclaration */:
  32497. case 247 /* TypeAliasDeclaration */:
  32498. return true;
  32499. case 249 /* ModuleDeclaration */:
  32500. return getModuleInstanceState(s) !== 1 /* Instantiated */;
  32501. case 248 /* EnumDeclaration */:
  32502. return ts.hasModifier(s, 2048 /* Const */);
  32503. default:
  32504. return false;
  32505. }
  32506. }
  32507. function isExportsOrModuleExportsOrAlias(sourceFile, node) {
  32508. var i = 0;
  32509. var q = [node];
  32510. while (q.length && i < 100) {
  32511. i++;
  32512. node = q.shift();
  32513. if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
  32514. return true;
  32515. }
  32516. else if (ts.isIdentifier(node)) {
  32517. var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
  32518. if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
  32519. var init = symbol.valueDeclaration.initializer;
  32520. q.push(init);
  32521. if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
  32522. q.push(init.left);
  32523. q.push(init.right);
  32524. }
  32525. }
  32526. }
  32527. }
  32528. return false;
  32529. }
  32530. ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
  32531. function lookupSymbolForNameWorker(container, name) {
  32532. var local = container.locals && container.locals.get(name);
  32533. if (local) {
  32534. return local.exportSymbol || local;
  32535. }
  32536. if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
  32537. return container.jsGlobalAugmentations.get(name);
  32538. }
  32539. return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
  32540. }
  32541. /**
  32542. * Computes the transform flags for a node, given the transform flags of its subtree
  32543. *
  32544. * @param node The node to analyze
  32545. * @param subtreeFlags Transform flags computed for this node's subtree
  32546. */
  32547. function computeTransformFlagsForNode(node, subtreeFlags) {
  32548. var kind = node.kind;
  32549. switch (kind) {
  32550. case 196 /* CallExpression */:
  32551. return computeCallExpression(node, subtreeFlags);
  32552. case 197 /* NewExpression */:
  32553. return computeNewExpression(node, subtreeFlags);
  32554. case 249 /* ModuleDeclaration */:
  32555. return computeModuleDeclaration(node, subtreeFlags);
  32556. case 200 /* ParenthesizedExpression */:
  32557. return computeParenthesizedExpression(node, subtreeFlags);
  32558. case 209 /* BinaryExpression */:
  32559. return computeBinaryExpression(node, subtreeFlags);
  32560. case 226 /* ExpressionStatement */:
  32561. return computeExpressionStatement(node, subtreeFlags);
  32562. case 156 /* Parameter */:
  32563. return computeParameter(node, subtreeFlags);
  32564. case 202 /* ArrowFunction */:
  32565. return computeArrowFunction(node, subtreeFlags);
  32566. case 201 /* FunctionExpression */:
  32567. return computeFunctionExpression(node, subtreeFlags);
  32568. case 244 /* FunctionDeclaration */:
  32569. return computeFunctionDeclaration(node, subtreeFlags);
  32570. case 242 /* VariableDeclaration */:
  32571. return computeVariableDeclaration(node, subtreeFlags);
  32572. case 243 /* VariableDeclarationList */:
  32573. return computeVariableDeclarationList(node, subtreeFlags);
  32574. case 225 /* VariableStatement */:
  32575. return computeVariableStatement(node, subtreeFlags);
  32576. case 238 /* LabeledStatement */:
  32577. return computeLabeledStatement(node, subtreeFlags);
  32578. case 245 /* ClassDeclaration */:
  32579. return computeClassDeclaration(node, subtreeFlags);
  32580. case 214 /* ClassExpression */:
  32581. return computeClassExpression(node, subtreeFlags);
  32582. case 279 /* HeritageClause */:
  32583. return computeHeritageClause(node, subtreeFlags);
  32584. case 280 /* CatchClause */:
  32585. return computeCatchClause(node, subtreeFlags);
  32586. case 216 /* ExpressionWithTypeArguments */:
  32587. return computeExpressionWithTypeArguments(node, subtreeFlags);
  32588. case 162 /* Constructor */:
  32589. return computeConstructor(node, subtreeFlags);
  32590. case 159 /* PropertyDeclaration */:
  32591. return computePropertyDeclaration(node, subtreeFlags);
  32592. case 161 /* MethodDeclaration */:
  32593. return computeMethod(node, subtreeFlags);
  32594. case 163 /* GetAccessor */:
  32595. case 164 /* SetAccessor */:
  32596. return computeAccessor(node, subtreeFlags);
  32597. case 253 /* ImportEqualsDeclaration */:
  32598. return computeImportEquals(node, subtreeFlags);
  32599. case 194 /* PropertyAccessExpression */:
  32600. return computePropertyAccess(node, subtreeFlags);
  32601. case 195 /* ElementAccessExpression */:
  32602. return computeElementAccess(node, subtreeFlags);
  32603. default:
  32604. return computeOther(node, kind, subtreeFlags);
  32605. }
  32606. }
  32607. ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
  32608. function computeCallExpression(node, subtreeFlags) {
  32609. var transformFlags = subtreeFlags;
  32610. var callee = ts.skipOuterExpressions(node.expression);
  32611. var expression = node.expression;
  32612. if (node.flags & 32 /* OptionalChain */) {
  32613. transformFlags |= 8 /* ContainsES2020 */;
  32614. }
  32615. if (node.typeArguments) {
  32616. transformFlags |= 1 /* AssertTypeScript */;
  32617. }
  32618. if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
  32619. // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
  32620. // node.
  32621. transformFlags |= 256 /* AssertES2015 */;
  32622. if (ts.isSuperProperty(callee)) {
  32623. transformFlags |= 4096 /* ContainsLexicalThis */;
  32624. }
  32625. }
  32626. if (expression.kind === 96 /* ImportKeyword */) {
  32627. transformFlags |= 2097152 /* ContainsDynamicImport */;
  32628. }
  32629. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32630. return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
  32631. }
  32632. function computeNewExpression(node, subtreeFlags) {
  32633. var transformFlags = subtreeFlags;
  32634. if (node.typeArguments) {
  32635. transformFlags |= 1 /* AssertTypeScript */;
  32636. }
  32637. if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
  32638. // If the this node contains a SpreadElementExpression then it is an ES6
  32639. // node.
  32640. transformFlags |= 256 /* AssertES2015 */;
  32641. }
  32642. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32643. return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
  32644. }
  32645. function computeBinaryExpression(node, subtreeFlags) {
  32646. var transformFlags = subtreeFlags;
  32647. var operatorTokenKind = node.operatorToken.kind;
  32648. var leftKind = node.left.kind;
  32649. if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
  32650. transformFlags |= 8 /* AssertES2020 */;
  32651. }
  32652. else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
  32653. // Destructuring object assignments with are ES2015 syntax
  32654. // and possibly ES2018 if they contain rest
  32655. transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
  32656. }
  32657. else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
  32658. // Destructuring assignments are ES2015 syntax.
  32659. transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
  32660. }
  32661. else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
  32662. || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
  32663. // Exponentiation is ES2016 syntax.
  32664. transformFlags |= 128 /* AssertES2016 */;
  32665. }
  32666. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32667. return transformFlags & ~536870912 /* NodeExcludes */;
  32668. }
  32669. function computeParameter(node, subtreeFlags) {
  32670. var transformFlags = subtreeFlags;
  32671. var name = node.name;
  32672. var initializer = node.initializer;
  32673. var dotDotDotToken = node.dotDotDotToken;
  32674. // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
  32675. // syntax.
  32676. if (node.questionToken
  32677. || node.type
  32678. || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
  32679. || ts.isThisIdentifier(name)) {
  32680. transformFlags |= 1 /* AssertTypeScript */;
  32681. }
  32682. // If a parameter has an accessibility modifier, then it is TypeScript syntax.
  32683. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
  32684. transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
  32685. }
  32686. // parameters with object rest destructuring are ES2018 syntax
  32687. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32688. transformFlags |= 32 /* AssertES2018 */;
  32689. }
  32690. // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
  32691. // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
  32692. if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
  32693. transformFlags |= 256 /* AssertES2015 */;
  32694. }
  32695. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32696. return transformFlags & ~536870912 /* ParameterExcludes */;
  32697. }
  32698. function computeParenthesizedExpression(node, subtreeFlags) {
  32699. var transformFlags = subtreeFlags;
  32700. var expression = node.expression;
  32701. var expressionKind = expression.kind;
  32702. // If the node is synthesized, it means the emitter put the parentheses there,
  32703. // not the user. If we didn't want them, the emitter would not have put them
  32704. // there.
  32705. if (expressionKind === 217 /* AsExpression */
  32706. || expressionKind === 199 /* TypeAssertionExpression */) {
  32707. transformFlags |= 1 /* AssertTypeScript */;
  32708. }
  32709. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32710. return transformFlags & ~536870912 /* OuterExpressionExcludes */;
  32711. }
  32712. function computeClassDeclaration(node, subtreeFlags) {
  32713. var transformFlags;
  32714. if (ts.hasModifier(node, 2 /* Ambient */)) {
  32715. // An ambient declaration is TypeScript syntax.
  32716. transformFlags = 1 /* AssertTypeScript */;
  32717. }
  32718. else {
  32719. // A ClassDeclaration is ES6 syntax.
  32720. transformFlags = subtreeFlags | 256 /* AssertES2015 */;
  32721. // A class with a parameter property assignment or decorator is TypeScript syntax.
  32722. // An exported declaration may be TypeScript syntax, but is handled by the visitor
  32723. // for a namespace declaration.
  32724. if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
  32725. || node.typeParameters) {
  32726. transformFlags |= 1 /* AssertTypeScript */;
  32727. }
  32728. }
  32729. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32730. return transformFlags & ~536905728 /* ClassExcludes */;
  32731. }
  32732. function computeClassExpression(node, subtreeFlags) {
  32733. // A ClassExpression is ES6 syntax.
  32734. var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
  32735. // A class with a parameter property assignment or decorator is TypeScript syntax.
  32736. if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
  32737. || node.typeParameters) {
  32738. transformFlags |= 1 /* AssertTypeScript */;
  32739. }
  32740. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32741. return transformFlags & ~536905728 /* ClassExcludes */;
  32742. }
  32743. function computeHeritageClause(node, subtreeFlags) {
  32744. var transformFlags = subtreeFlags;
  32745. switch (node.token) {
  32746. case 90 /* ExtendsKeyword */:
  32747. // An `extends` HeritageClause is ES6 syntax.
  32748. transformFlags |= 256 /* AssertES2015 */;
  32749. break;
  32750. case 113 /* ImplementsKeyword */:
  32751. // An `implements` HeritageClause is TypeScript syntax.
  32752. transformFlags |= 1 /* AssertTypeScript */;
  32753. break;
  32754. default:
  32755. ts.Debug.fail("Unexpected token for heritage clause");
  32756. break;
  32757. }
  32758. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32759. return transformFlags & ~536870912 /* NodeExcludes */;
  32760. }
  32761. function computeCatchClause(node, subtreeFlags) {
  32762. var transformFlags = subtreeFlags;
  32763. if (!node.variableDeclaration) {
  32764. transformFlags |= 16 /* AssertES2019 */;
  32765. }
  32766. else if (ts.isBindingPattern(node.variableDeclaration.name)) {
  32767. transformFlags |= 256 /* AssertES2015 */;
  32768. }
  32769. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32770. return transformFlags & ~536887296 /* CatchClauseExcludes */;
  32771. }
  32772. function computeExpressionWithTypeArguments(node, subtreeFlags) {
  32773. // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
  32774. // extends clause of a class.
  32775. var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
  32776. // If an ExpressionWithTypeArguments contains type arguments, then it
  32777. // is TypeScript syntax.
  32778. if (node.typeArguments) {
  32779. transformFlags |= 1 /* AssertTypeScript */;
  32780. }
  32781. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32782. return transformFlags & ~536870912 /* NodeExcludes */;
  32783. }
  32784. function computeConstructor(node, subtreeFlags) {
  32785. var transformFlags = subtreeFlags;
  32786. // TypeScript-specific modifiers and overloads are TypeScript syntax
  32787. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
  32788. || !node.body) {
  32789. transformFlags |= 1 /* AssertTypeScript */;
  32790. }
  32791. // function declarations with object rest destructuring are ES2018 syntax
  32792. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32793. transformFlags |= 32 /* AssertES2018 */;
  32794. }
  32795. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32796. return transformFlags & ~538923008 /* ConstructorExcludes */;
  32797. }
  32798. function computeMethod(node, subtreeFlags) {
  32799. // A MethodDeclaration is ES6 syntax.
  32800. var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
  32801. // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
  32802. // overloads are TypeScript syntax.
  32803. if (node.decorators
  32804. || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
  32805. || node.typeParameters
  32806. || node.type
  32807. || !node.body
  32808. || node.questionToken) {
  32809. transformFlags |= 1 /* AssertTypeScript */;
  32810. }
  32811. // function declarations with object rest destructuring are ES2018 syntax
  32812. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32813. transformFlags |= 32 /* AssertES2018 */;
  32814. }
  32815. // An async method declaration is ES2017 syntax.
  32816. if (ts.hasModifier(node, 256 /* Async */)) {
  32817. transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
  32818. }
  32819. if (node.asteriskToken) {
  32820. transformFlags |= 512 /* AssertGenerator */;
  32821. }
  32822. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32823. return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
  32824. }
  32825. function computeAccessor(node, subtreeFlags) {
  32826. var transformFlags = subtreeFlags;
  32827. // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
  32828. // TypeScript syntax.
  32829. if (node.decorators
  32830. || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
  32831. || node.type
  32832. || !node.body) {
  32833. transformFlags |= 1 /* AssertTypeScript */;
  32834. }
  32835. // function declarations with object rest destructuring are ES2018 syntax
  32836. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32837. transformFlags |= 32 /* AssertES2018 */;
  32838. }
  32839. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32840. return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
  32841. }
  32842. function computePropertyDeclaration(node, subtreeFlags) {
  32843. var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
  32844. // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
  32845. if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
  32846. transformFlags |= 1 /* AssertTypeScript */;
  32847. }
  32848. // Hoisted variables related to class properties should live within the TypeScript class wrapper.
  32849. if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
  32850. transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
  32851. }
  32852. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32853. return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
  32854. }
  32855. function computeFunctionDeclaration(node, subtreeFlags) {
  32856. var transformFlags;
  32857. var modifierFlags = ts.getModifierFlags(node);
  32858. var body = node.body;
  32859. if (!body || (modifierFlags & 2 /* Ambient */)) {
  32860. // An ambient declaration is TypeScript syntax.
  32861. // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
  32862. transformFlags = 1 /* AssertTypeScript */;
  32863. }
  32864. else {
  32865. transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
  32866. // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
  32867. // syntax.
  32868. if (modifierFlags & 2270 /* TypeScriptModifier */
  32869. || node.typeParameters
  32870. || node.type) {
  32871. transformFlags |= 1 /* AssertTypeScript */;
  32872. }
  32873. // An async function declaration is ES2017 syntax.
  32874. if (modifierFlags & 256 /* Async */) {
  32875. transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
  32876. }
  32877. // function declarations with object rest destructuring are ES2018 syntax
  32878. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32879. transformFlags |= 32 /* AssertES2018 */;
  32880. }
  32881. // If a FunctionDeclaration is generator function and is the body of a
  32882. // transformed async function, then this node can be transformed to a
  32883. // down-level generator.
  32884. // Currently we do not support transforming any other generator functions
  32885. // down level.
  32886. if (node.asteriskToken) {
  32887. transformFlags |= 512 /* AssertGenerator */;
  32888. }
  32889. }
  32890. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32891. return transformFlags & ~538925056 /* FunctionExcludes */;
  32892. }
  32893. function computeFunctionExpression(node, subtreeFlags) {
  32894. var transformFlags = subtreeFlags;
  32895. // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
  32896. // syntax.
  32897. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
  32898. || node.typeParameters
  32899. || node.type) {
  32900. transformFlags |= 1 /* AssertTypeScript */;
  32901. }
  32902. // An async function expression is ES2017 syntax.
  32903. if (ts.hasModifier(node, 256 /* Async */)) {
  32904. transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
  32905. }
  32906. // function expressions with object rest destructuring are ES2018 syntax
  32907. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32908. transformFlags |= 32 /* AssertES2018 */;
  32909. }
  32910. // If a FunctionExpression is generator function and is the body of a
  32911. // transformed async function, then this node can be transformed to a
  32912. // down-level generator.
  32913. if (node.asteriskToken) {
  32914. transformFlags |= 512 /* AssertGenerator */;
  32915. }
  32916. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32917. return transformFlags & ~538925056 /* FunctionExcludes */;
  32918. }
  32919. function computeArrowFunction(node, subtreeFlags) {
  32920. // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
  32921. var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
  32922. // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
  32923. // syntax.
  32924. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
  32925. || node.typeParameters
  32926. || node.type) {
  32927. transformFlags |= 1 /* AssertTypeScript */;
  32928. }
  32929. // An async arrow function is ES2017 syntax.
  32930. if (ts.hasModifier(node, 256 /* Async */)) {
  32931. transformFlags |= 64 /* AssertES2017 */;
  32932. }
  32933. // arrow functions with object rest destructuring are ES2018 syntax
  32934. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32935. transformFlags |= 32 /* AssertES2018 */;
  32936. }
  32937. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32938. return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
  32939. }
  32940. function computePropertyAccess(node, subtreeFlags) {
  32941. var transformFlags = subtreeFlags;
  32942. if (node.flags & 32 /* OptionalChain */) {
  32943. transformFlags |= 8 /* ContainsES2020 */;
  32944. }
  32945. // If a PropertyAccessExpression starts with a super keyword, then it is
  32946. // ES6 syntax, and requires a lexical `this` binding.
  32947. if (node.expression.kind === 102 /* SuperKeyword */) {
  32948. // super inside of an async function requires hoisting the super access (ES2017).
  32949. // same for super inside of an async generator, which is ES2018.
  32950. transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
  32951. }
  32952. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32953. return transformFlags & ~536870912 /* PropertyAccessExcludes */;
  32954. }
  32955. function computeElementAccess(node, subtreeFlags) {
  32956. var transformFlags = subtreeFlags;
  32957. if (node.flags & 32 /* OptionalChain */) {
  32958. transformFlags |= 8 /* ContainsES2020 */;
  32959. }
  32960. // If an ElementAccessExpression starts with a super keyword, then it is
  32961. // ES6 syntax, and requires a lexical `this` binding.
  32962. if (node.expression.kind === 102 /* SuperKeyword */) {
  32963. // super inside of an async function requires hoisting the super access (ES2017).
  32964. // same for super inside of an async generator, which is ES2018.
  32965. transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
  32966. }
  32967. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32968. return transformFlags & ~536870912 /* PropertyAccessExcludes */;
  32969. }
  32970. function computeVariableDeclaration(node, subtreeFlags) {
  32971. var transformFlags = subtreeFlags;
  32972. transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
  32973. // A VariableDeclaration containing ObjectRest is ES2018 syntax
  32974. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  32975. transformFlags |= 32 /* AssertES2018 */;
  32976. }
  32977. // Type annotations are TypeScript syntax.
  32978. if (node.type || node.exclamationToken) {
  32979. transformFlags |= 1 /* AssertTypeScript */;
  32980. }
  32981. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32982. return transformFlags & ~536870912 /* NodeExcludes */;
  32983. }
  32984. function computeVariableStatement(node, subtreeFlags) {
  32985. var transformFlags;
  32986. var declarationListTransformFlags = node.declarationList.transformFlags;
  32987. // An ambient declaration is TypeScript syntax.
  32988. if (ts.hasModifier(node, 2 /* Ambient */)) {
  32989. transformFlags = 1 /* AssertTypeScript */;
  32990. }
  32991. else {
  32992. transformFlags = subtreeFlags;
  32993. if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
  32994. transformFlags |= 256 /* AssertES2015 */;
  32995. }
  32996. }
  32997. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  32998. return transformFlags & ~536870912 /* NodeExcludes */;
  32999. }
  33000. function computeLabeledStatement(node, subtreeFlags) {
  33001. var transformFlags = subtreeFlags;
  33002. // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
  33003. if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
  33004. && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
  33005. transformFlags |= 256 /* AssertES2015 */;
  33006. }
  33007. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  33008. return transformFlags & ~536870912 /* NodeExcludes */;
  33009. }
  33010. function computeImportEquals(node, subtreeFlags) {
  33011. var transformFlags = subtreeFlags;
  33012. // An ImportEqualsDeclaration with a namespace reference is TypeScript.
  33013. if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
  33014. transformFlags |= 1 /* AssertTypeScript */;
  33015. }
  33016. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  33017. return transformFlags & ~536870912 /* NodeExcludes */;
  33018. }
  33019. function computeExpressionStatement(node, subtreeFlags) {
  33020. var transformFlags = subtreeFlags;
  33021. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  33022. return transformFlags & ~536870912 /* NodeExcludes */;
  33023. }
  33024. function computeModuleDeclaration(node, subtreeFlags) {
  33025. var transformFlags = 1 /* AssertTypeScript */;
  33026. var modifierFlags = ts.getModifierFlags(node);
  33027. if ((modifierFlags & 2 /* Ambient */) === 0) {
  33028. transformFlags |= subtreeFlags;
  33029. }
  33030. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  33031. return transformFlags & ~537991168 /* ModuleExcludes */;
  33032. }
  33033. function computeVariableDeclarationList(node, subtreeFlags) {
  33034. var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
  33035. if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
  33036. transformFlags |= 256 /* AssertES2015 */;
  33037. }
  33038. // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
  33039. if (node.flags & 3 /* BlockScoped */) {
  33040. transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
  33041. }
  33042. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  33043. return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
  33044. }
  33045. function computeOther(node, kind, subtreeFlags) {
  33046. // Mark transformations needed for each node
  33047. var transformFlags = subtreeFlags;
  33048. var excludeFlags = 536870912 /* NodeExcludes */;
  33049. switch (kind) {
  33050. case 126 /* AsyncKeyword */:
  33051. // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
  33052. transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
  33053. break;
  33054. case 206 /* AwaitExpression */:
  33055. // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
  33056. transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
  33057. break;
  33058. case 199 /* TypeAssertionExpression */:
  33059. case 217 /* AsExpression */:
  33060. case 325 /* PartiallyEmittedExpression */:
  33061. // These nodes are TypeScript syntax.
  33062. transformFlags |= 1 /* AssertTypeScript */;
  33063. excludeFlags = 536870912 /* OuterExpressionExcludes */;
  33064. break;
  33065. case 119 /* PublicKeyword */:
  33066. case 117 /* PrivateKeyword */:
  33067. case 118 /* ProtectedKeyword */:
  33068. case 122 /* AbstractKeyword */:
  33069. case 130 /* DeclareKeyword */:
  33070. case 81 /* ConstKeyword */:
  33071. case 248 /* EnumDeclaration */:
  33072. case 284 /* EnumMember */:
  33073. case 218 /* NonNullExpression */:
  33074. case 138 /* ReadonlyKeyword */:
  33075. // These nodes are TypeScript syntax.
  33076. transformFlags |= 1 /* AssertTypeScript */;
  33077. break;
  33078. case 266 /* JsxElement */:
  33079. case 267 /* JsxSelfClosingElement */:
  33080. case 268 /* JsxOpeningElement */:
  33081. case 11 /* JsxText */:
  33082. case 269 /* JsxClosingElement */:
  33083. case 270 /* JsxFragment */:
  33084. case 271 /* JsxOpeningFragment */:
  33085. case 272 /* JsxClosingFragment */:
  33086. case 273 /* JsxAttribute */:
  33087. case 274 /* JsxAttributes */:
  33088. case 275 /* JsxSpreadAttribute */:
  33089. case 276 /* JsxExpression */:
  33090. // These nodes are Jsx syntax.
  33091. transformFlags |= 2 /* AssertJsx */;
  33092. break;
  33093. case 14 /* NoSubstitutionTemplateLiteral */:
  33094. case 15 /* TemplateHead */:
  33095. case 16 /* TemplateMiddle */:
  33096. case 17 /* TemplateTail */:
  33097. case 211 /* TemplateExpression */:
  33098. case 198 /* TaggedTemplateExpression */:
  33099. case 282 /* ShorthandPropertyAssignment */:
  33100. case 120 /* StaticKeyword */:
  33101. case 219 /* MetaProperty */:
  33102. // These nodes are ES6 syntax.
  33103. transformFlags |= 256 /* AssertES2015 */;
  33104. break;
  33105. case 10 /* StringLiteral */:
  33106. if (node.hasExtendedUnicodeEscape) {
  33107. transformFlags |= 256 /* AssertES2015 */;
  33108. }
  33109. break;
  33110. case 8 /* NumericLiteral */:
  33111. if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
  33112. transformFlags |= 256 /* AssertES2015 */;
  33113. }
  33114. break;
  33115. case 9 /* BigIntLiteral */:
  33116. transformFlags |= 4 /* AssertESNext */;
  33117. break;
  33118. case 232 /* ForOfStatement */:
  33119. // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
  33120. if (node.awaitModifier) {
  33121. transformFlags |= 32 /* AssertES2018 */;
  33122. }
  33123. transformFlags |= 256 /* AssertES2015 */;
  33124. break;
  33125. case 212 /* YieldExpression */:
  33126. // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
  33127. // generator).
  33128. transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
  33129. break;
  33130. case 125 /* AnyKeyword */:
  33131. case 140 /* NumberKeyword */:
  33132. case 151 /* BigIntKeyword */:
  33133. case 137 /* NeverKeyword */:
  33134. case 141 /* ObjectKeyword */:
  33135. case 143 /* StringKeyword */:
  33136. case 128 /* BooleanKeyword */:
  33137. case 144 /* SymbolKeyword */:
  33138. case 110 /* VoidKeyword */:
  33139. case 155 /* TypeParameter */:
  33140. case 158 /* PropertySignature */:
  33141. case 160 /* MethodSignature */:
  33142. case 165 /* CallSignature */:
  33143. case 166 /* ConstructSignature */:
  33144. case 167 /* IndexSignature */:
  33145. case 168 /* TypePredicate */:
  33146. case 169 /* TypeReference */:
  33147. case 170 /* FunctionType */:
  33148. case 171 /* ConstructorType */:
  33149. case 172 /* TypeQuery */:
  33150. case 173 /* TypeLiteral */:
  33151. case 174 /* ArrayType */:
  33152. case 175 /* TupleType */:
  33153. case 176 /* OptionalType */:
  33154. case 177 /* RestType */:
  33155. case 178 /* UnionType */:
  33156. case 179 /* IntersectionType */:
  33157. case 180 /* ConditionalType */:
  33158. case 181 /* InferType */:
  33159. case 182 /* ParenthesizedType */:
  33160. case 246 /* InterfaceDeclaration */:
  33161. case 247 /* TypeAliasDeclaration */:
  33162. case 183 /* ThisType */:
  33163. case 184 /* TypeOperator */:
  33164. case 185 /* IndexedAccessType */:
  33165. case 186 /* MappedType */:
  33166. case 187 /* LiteralType */:
  33167. case 252 /* NamespaceExportDeclaration */:
  33168. // Types and signatures are TypeScript syntax, and exclude all other facts.
  33169. transformFlags = 1 /* AssertTypeScript */;
  33170. excludeFlags = -2 /* TypeExcludes */;
  33171. break;
  33172. case 154 /* ComputedPropertyName */:
  33173. // Even though computed property names are ES6, we don't treat them as such.
  33174. // This is so that they can flow through PropertyName transforms unaffected.
  33175. // Instead, we mark the container as ES6, so that it can properly handle the transform.
  33176. transformFlags |= 32768 /* ContainsComputedPropertyName */;
  33177. break;
  33178. case 213 /* SpreadElement */:
  33179. transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
  33180. break;
  33181. case 283 /* SpreadAssignment */:
  33182. transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
  33183. break;
  33184. case 102 /* SuperKeyword */:
  33185. // This node is ES6 syntax.
  33186. transformFlags |= 256 /* AssertES2015 */;
  33187. excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
  33188. break;
  33189. case 104 /* ThisKeyword */:
  33190. // Mark this node and its ancestors as containing a lexical `this` keyword.
  33191. transformFlags |= 4096 /* ContainsLexicalThis */;
  33192. break;
  33193. case 189 /* ObjectBindingPattern */:
  33194. transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
  33195. if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
  33196. transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
  33197. }
  33198. excludeFlags = 536879104 /* BindingPatternExcludes */;
  33199. break;
  33200. case 190 /* ArrayBindingPattern */:
  33201. transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
  33202. excludeFlags = 536879104 /* BindingPatternExcludes */;
  33203. break;
  33204. case 191 /* BindingElement */:
  33205. transformFlags |= 256 /* AssertES2015 */;
  33206. if (node.dotDotDotToken) {
  33207. transformFlags |= 8192 /* ContainsRestOrSpread */;
  33208. }
  33209. break;
  33210. case 157 /* Decorator */:
  33211. // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
  33212. transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
  33213. break;
  33214. case 193 /* ObjectLiteralExpression */:
  33215. excludeFlags = 536922112 /* ObjectLiteralExcludes */;
  33216. if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
  33217. // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
  33218. // is an ES6 node.
  33219. transformFlags |= 256 /* AssertES2015 */;
  33220. }
  33221. if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
  33222. // If an ObjectLiteralExpression contains a spread element, then it
  33223. // is an ES2018 node.
  33224. transformFlags |= 32 /* AssertES2018 */;
  33225. }
  33226. break;
  33227. case 192 /* ArrayLiteralExpression */:
  33228. excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
  33229. break;
  33230. case 228 /* DoStatement */:
  33231. case 229 /* WhileStatement */:
  33232. case 230 /* ForStatement */:
  33233. case 231 /* ForInStatement */:
  33234. // A loop containing a block scoped binding *may* need to be transformed from ES6.
  33235. if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
  33236. transformFlags |= 256 /* AssertES2015 */;
  33237. }
  33238. break;
  33239. case 290 /* SourceFile */:
  33240. break;
  33241. case 262 /* NamespaceExport */:
  33242. transformFlags |= 4 /* AssertESNext */;
  33243. break;
  33244. case 235 /* ReturnStatement */:
  33245. // Return statements may require an `await` in ES2018.
  33246. transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
  33247. break;
  33248. case 233 /* ContinueStatement */:
  33249. case 234 /* BreakStatement */:
  33250. transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
  33251. break;
  33252. case 76 /* PrivateIdentifier */:
  33253. transformFlags |= 4194304 /* ContainsClassFields */;
  33254. break;
  33255. }
  33256. node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
  33257. return transformFlags & ~excludeFlags;
  33258. }
  33259. function propagatePropertyNameFlags(node, transformFlags) {
  33260. return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
  33261. }
  33262. /**
  33263. * Gets the transform flags to exclude when unioning the transform flags of a subtree.
  33264. *
  33265. * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
  33266. * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
  33267. * than calling this function.
  33268. */
  33269. function getTransformFlagsSubtreeExclusions(kind) {
  33270. if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
  33271. return -2 /* TypeExcludes */;
  33272. }
  33273. switch (kind) {
  33274. case 196 /* CallExpression */:
  33275. case 197 /* NewExpression */:
  33276. case 192 /* ArrayLiteralExpression */:
  33277. return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
  33278. case 249 /* ModuleDeclaration */:
  33279. return 537991168 /* ModuleExcludes */;
  33280. case 156 /* Parameter */:
  33281. return 536870912 /* ParameterExcludes */;
  33282. case 202 /* ArrowFunction */:
  33283. return 538920960 /* ArrowFunctionExcludes */;
  33284. case 201 /* FunctionExpression */:
  33285. case 244 /* FunctionDeclaration */:
  33286. return 538925056 /* FunctionExcludes */;
  33287. case 243 /* VariableDeclarationList */:
  33288. return 537018368 /* VariableDeclarationListExcludes */;
  33289. case 245 /* ClassDeclaration */:
  33290. case 214 /* ClassExpression */:
  33291. return 536905728 /* ClassExcludes */;
  33292. case 162 /* Constructor */:
  33293. return 538923008 /* ConstructorExcludes */;
  33294. case 161 /* MethodDeclaration */:
  33295. case 163 /* GetAccessor */:
  33296. case 164 /* SetAccessor */:
  33297. return 538923008 /* MethodOrAccessorExcludes */;
  33298. case 125 /* AnyKeyword */:
  33299. case 140 /* NumberKeyword */:
  33300. case 151 /* BigIntKeyword */:
  33301. case 137 /* NeverKeyword */:
  33302. case 143 /* StringKeyword */:
  33303. case 141 /* ObjectKeyword */:
  33304. case 128 /* BooleanKeyword */:
  33305. case 144 /* SymbolKeyword */:
  33306. case 110 /* VoidKeyword */:
  33307. case 155 /* TypeParameter */:
  33308. case 158 /* PropertySignature */:
  33309. case 160 /* MethodSignature */:
  33310. case 165 /* CallSignature */:
  33311. case 166 /* ConstructSignature */:
  33312. case 167 /* IndexSignature */:
  33313. case 246 /* InterfaceDeclaration */:
  33314. case 247 /* TypeAliasDeclaration */:
  33315. return -2 /* TypeExcludes */;
  33316. case 193 /* ObjectLiteralExpression */:
  33317. return 536922112 /* ObjectLiteralExcludes */;
  33318. case 280 /* CatchClause */:
  33319. return 536887296 /* CatchClauseExcludes */;
  33320. case 189 /* ObjectBindingPattern */:
  33321. case 190 /* ArrayBindingPattern */:
  33322. return 536879104 /* BindingPatternExcludes */;
  33323. case 199 /* TypeAssertionExpression */:
  33324. case 217 /* AsExpression */:
  33325. case 325 /* PartiallyEmittedExpression */:
  33326. case 200 /* ParenthesizedExpression */:
  33327. case 102 /* SuperKeyword */:
  33328. return 536870912 /* OuterExpressionExcludes */;
  33329. case 194 /* PropertyAccessExpression */:
  33330. case 195 /* ElementAccessExpression */:
  33331. return 536870912 /* PropertyAccessExcludes */;
  33332. default:
  33333. return 536870912 /* NodeExcludes */;
  33334. }
  33335. }
  33336. ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
  33337. /**
  33338. * "Binds" JSDoc nodes in TypeScript code.
  33339. * Since we will never create symbols for JSDoc, we just set parent pointers instead.
  33340. */
  33341. function setParentPointers(parent, child) {
  33342. child.parent = parent;
  33343. ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
  33344. }
  33345. })(ts || (ts = {}));
  33346. /** @internal */
  33347. var ts;
  33348. (function (ts) {
  33349. function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
  33350. return getSymbolWalker;
  33351. function getSymbolWalker(accept) {
  33352. if (accept === void 0) { accept = function () { return true; }; }
  33353. var visitedTypes = []; // Sparse array from id to type
  33354. var visitedSymbols = []; // Sparse array from id to symbol
  33355. return {
  33356. walkType: function (type) {
  33357. try {
  33358. visitType(type);
  33359. return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
  33360. }
  33361. finally {
  33362. ts.clear(visitedTypes);
  33363. ts.clear(visitedSymbols);
  33364. }
  33365. },
  33366. walkSymbol: function (symbol) {
  33367. try {
  33368. visitSymbol(symbol);
  33369. return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
  33370. }
  33371. finally {
  33372. ts.clear(visitedTypes);
  33373. ts.clear(visitedSymbols);
  33374. }
  33375. },
  33376. };
  33377. function visitType(type) {
  33378. if (!type) {
  33379. return;
  33380. }
  33381. if (visitedTypes[type.id]) {
  33382. return;
  33383. }
  33384. visitedTypes[type.id] = type;
  33385. // Reuse visitSymbol to visit the type's symbol,
  33386. // but be sure to bail on recuring into the type if accept declines the symbol.
  33387. var shouldBail = visitSymbol(type.symbol);
  33388. if (shouldBail)
  33389. return;
  33390. // Visit the type's related types, if any
  33391. if (type.flags & 524288 /* Object */) {
  33392. var objectType = type;
  33393. var objectFlags = objectType.objectFlags;
  33394. if (objectFlags & 4 /* Reference */) {
  33395. visitTypeReference(type);
  33396. }
  33397. if (objectFlags & 32 /* Mapped */) {
  33398. visitMappedType(type);
  33399. }
  33400. if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
  33401. visitInterfaceType(type);
  33402. }
  33403. if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
  33404. visitObjectType(objectType);
  33405. }
  33406. }
  33407. if (type.flags & 262144 /* TypeParameter */) {
  33408. visitTypeParameter(type);
  33409. }
  33410. if (type.flags & 3145728 /* UnionOrIntersection */) {
  33411. visitUnionOrIntersectionType(type);
  33412. }
  33413. if (type.flags & 4194304 /* Index */) {
  33414. visitIndexType(type);
  33415. }
  33416. if (type.flags & 8388608 /* IndexedAccess */) {
  33417. visitIndexedAccessType(type);
  33418. }
  33419. }
  33420. function visitTypeReference(type) {
  33421. visitType(type.target);
  33422. ts.forEach(getTypeArguments(type), visitType);
  33423. }
  33424. function visitTypeParameter(type) {
  33425. visitType(getConstraintOfTypeParameter(type));
  33426. }
  33427. function visitUnionOrIntersectionType(type) {
  33428. ts.forEach(type.types, visitType);
  33429. }
  33430. function visitIndexType(type) {
  33431. visitType(type.type);
  33432. }
  33433. function visitIndexedAccessType(type) {
  33434. visitType(type.objectType);
  33435. visitType(type.indexType);
  33436. visitType(type.constraint);
  33437. }
  33438. function visitMappedType(type) {
  33439. visitType(type.typeParameter);
  33440. visitType(type.constraintType);
  33441. visitType(type.templateType);
  33442. visitType(type.modifiersType);
  33443. }
  33444. function visitSignature(signature) {
  33445. var typePredicate = getTypePredicateOfSignature(signature);
  33446. if (typePredicate) {
  33447. visitType(typePredicate.type);
  33448. }
  33449. ts.forEach(signature.typeParameters, visitType);
  33450. for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
  33451. var parameter = _a[_i];
  33452. visitSymbol(parameter);
  33453. }
  33454. visitType(getRestTypeOfSignature(signature));
  33455. visitType(getReturnTypeOfSignature(signature));
  33456. }
  33457. function visitInterfaceType(interfaceT) {
  33458. visitObjectType(interfaceT);
  33459. ts.forEach(interfaceT.typeParameters, visitType);
  33460. ts.forEach(getBaseTypes(interfaceT), visitType);
  33461. visitType(interfaceT.thisType);
  33462. }
  33463. function visitObjectType(type) {
  33464. var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
  33465. visitType(stringIndexType);
  33466. var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
  33467. visitType(numberIndexType);
  33468. // The two checks above *should* have already resolved the type (if needed), so this should be cached
  33469. var resolved = resolveStructuredTypeMembers(type);
  33470. for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
  33471. var signature = _a[_i];
  33472. visitSignature(signature);
  33473. }
  33474. for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
  33475. var signature = _c[_b];
  33476. visitSignature(signature);
  33477. }
  33478. for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
  33479. var p = _e[_d];
  33480. visitSymbol(p);
  33481. }
  33482. }
  33483. function visitSymbol(symbol) {
  33484. if (!symbol) {
  33485. return false;
  33486. }
  33487. var symbolId = ts.getSymbolId(symbol);
  33488. if (visitedSymbols[symbolId]) {
  33489. return false;
  33490. }
  33491. visitedSymbols[symbolId] = symbol;
  33492. if (!accept(symbol)) {
  33493. return true;
  33494. }
  33495. var t = getTypeOfSymbol(symbol);
  33496. visitType(t); // Should handle members on classes and such
  33497. if (symbol.exports) {
  33498. symbol.exports.forEach(visitSymbol);
  33499. }
  33500. ts.forEach(symbol.declarations, function (d) {
  33501. // Type queries are too far resolved when we just visit the symbol's type
  33502. // (their type resolved directly to the member deeply referenced)
  33503. // So to get the intervening symbols, we need to check if there's a type
  33504. // query node on any of the symbol's declarations and get symbols there
  33505. if (d.type && d.type.kind === 172 /* TypeQuery */) {
  33506. var query = d.type;
  33507. var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
  33508. visitSymbol(entity);
  33509. }
  33510. });
  33511. return false;
  33512. }
  33513. }
  33514. }
  33515. ts.createGetSymbolWalker = createGetSymbolWalker;
  33516. })(ts || (ts = {}));
  33517. /* @internal */
  33518. var ts;
  33519. (function (ts) {
  33520. var ambientModuleSymbolRegex = /^".+"$/;
  33521. var anon = "(anonymous)";
  33522. var nextSymbolId = 1;
  33523. var nextNodeId = 1;
  33524. var nextMergeId = 1;
  33525. var nextFlowId = 1;
  33526. var IterationUse;
  33527. (function (IterationUse) {
  33528. IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
  33529. IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
  33530. IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
  33531. IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
  33532. IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
  33533. IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
  33534. IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
  33535. // Spread, Destructuring, Array element assignment
  33536. IterationUse[IterationUse["Element"] = 1] = "Element";
  33537. IterationUse[IterationUse["Spread"] = 33] = "Spread";
  33538. IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
  33539. IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
  33540. IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
  33541. IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
  33542. IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
  33543. IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
  33544. IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
  33545. })(IterationUse || (IterationUse = {}));
  33546. var IterationTypeKind;
  33547. (function (IterationTypeKind) {
  33548. IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
  33549. IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
  33550. IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
  33551. })(IterationTypeKind || (IterationTypeKind = {}));
  33552. var WideningKind;
  33553. (function (WideningKind) {
  33554. WideningKind[WideningKind["Normal"] = 0] = "Normal";
  33555. WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield";
  33556. })(WideningKind || (WideningKind = {}));
  33557. var TypeFacts;
  33558. (function (TypeFacts) {
  33559. TypeFacts[TypeFacts["None"] = 0] = "None";
  33560. TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
  33561. TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
  33562. TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
  33563. TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
  33564. TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
  33565. TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
  33566. TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
  33567. TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
  33568. TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
  33569. TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
  33570. TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
  33571. TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
  33572. TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
  33573. TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
  33574. TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
  33575. TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
  33576. TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
  33577. TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
  33578. TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
  33579. TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
  33580. TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
  33581. TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
  33582. TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
  33583. TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
  33584. TypeFacts[TypeFacts["All"] = 16777215] = "All";
  33585. // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
  33586. // The presence of a particular fact means that the given test is true for some (and possibly all) values
  33587. // of that kind of type.
  33588. TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
  33589. TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
  33590. TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
  33591. TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
  33592. TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
  33593. TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
  33594. TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
  33595. TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
  33596. TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
  33597. TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
  33598. TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
  33599. TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
  33600. TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
  33601. TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
  33602. TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
  33603. TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
  33604. TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
  33605. TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
  33606. TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
  33607. TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
  33608. TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
  33609. TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
  33610. TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
  33611. TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
  33612. TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
  33613. TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
  33614. TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
  33615. TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
  33616. TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
  33617. TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
  33618. TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
  33619. TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
  33620. TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
  33621. TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
  33622. TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
  33623. TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
  33624. TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
  33625. TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
  33626. TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
  33627. TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
  33628. TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
  33629. TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
  33630. })(TypeFacts || (TypeFacts = {}));
  33631. var typeofEQFacts = ts.createMapFromTemplate({
  33632. string: 1 /* TypeofEQString */,
  33633. number: 2 /* TypeofEQNumber */,
  33634. bigint: 4 /* TypeofEQBigInt */,
  33635. boolean: 8 /* TypeofEQBoolean */,
  33636. symbol: 16 /* TypeofEQSymbol */,
  33637. undefined: 65536 /* EQUndefined */,
  33638. object: 32 /* TypeofEQObject */,
  33639. function: 64 /* TypeofEQFunction */
  33640. });
  33641. var typeofNEFacts = ts.createMapFromTemplate({
  33642. string: 256 /* TypeofNEString */,
  33643. number: 512 /* TypeofNENumber */,
  33644. bigint: 1024 /* TypeofNEBigInt */,
  33645. boolean: 2048 /* TypeofNEBoolean */,
  33646. symbol: 4096 /* TypeofNESymbol */,
  33647. undefined: 524288 /* NEUndefined */,
  33648. object: 8192 /* TypeofNEObject */,
  33649. function: 16384 /* TypeofNEFunction */
  33650. });
  33651. var TypeSystemPropertyName;
  33652. (function (TypeSystemPropertyName) {
  33653. TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
  33654. TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
  33655. TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
  33656. TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
  33657. TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
  33658. TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
  33659. TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
  33660. })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
  33661. var CheckMode;
  33662. (function (CheckMode) {
  33663. CheckMode[CheckMode["Normal"] = 0] = "Normal";
  33664. CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
  33665. CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
  33666. CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
  33667. CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
  33668. CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
  33669. })(CheckMode || (CheckMode = {}));
  33670. var AccessFlags;
  33671. (function (AccessFlags) {
  33672. AccessFlags[AccessFlags["None"] = 0] = "None";
  33673. AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
  33674. AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
  33675. AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
  33676. AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
  33677. })(AccessFlags || (AccessFlags = {}));
  33678. var SignatureCheckMode;
  33679. (function (SignatureCheckMode) {
  33680. SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
  33681. SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
  33682. SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
  33683. SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
  33684. SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
  33685. })(SignatureCheckMode || (SignatureCheckMode = {}));
  33686. var IntersectionState;
  33687. (function (IntersectionState) {
  33688. IntersectionState[IntersectionState["None"] = 0] = "None";
  33689. IntersectionState[IntersectionState["Source"] = 1] = "Source";
  33690. IntersectionState[IntersectionState["Target"] = 2] = "Target";
  33691. })(IntersectionState || (IntersectionState = {}));
  33692. var MappedTypeModifiers;
  33693. (function (MappedTypeModifiers) {
  33694. MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
  33695. MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
  33696. MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
  33697. MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
  33698. })(MappedTypeModifiers || (MappedTypeModifiers = {}));
  33699. var ExpandingFlags;
  33700. (function (ExpandingFlags) {
  33701. ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
  33702. ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
  33703. ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
  33704. ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
  33705. })(ExpandingFlags || (ExpandingFlags = {}));
  33706. var MembersOrExportsResolutionKind;
  33707. (function (MembersOrExportsResolutionKind) {
  33708. MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
  33709. MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
  33710. })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
  33711. var UnusedKind;
  33712. (function (UnusedKind) {
  33713. UnusedKind[UnusedKind["Local"] = 0] = "Local";
  33714. UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
  33715. })(UnusedKind || (UnusedKind = {}));
  33716. var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
  33717. var DeclarationMeaning;
  33718. (function (DeclarationMeaning) {
  33719. DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
  33720. DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
  33721. DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
  33722. DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
  33723. DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
  33724. DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
  33725. })(DeclarationMeaning || (DeclarationMeaning = {}));
  33726. var DeclarationSpaces;
  33727. (function (DeclarationSpaces) {
  33728. DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
  33729. DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
  33730. DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
  33731. DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
  33732. })(DeclarationSpaces || (DeclarationSpaces = {}));
  33733. function getNodeId(node) {
  33734. if (!node.id) {
  33735. node.id = nextNodeId;
  33736. nextNodeId++;
  33737. }
  33738. return node.id;
  33739. }
  33740. ts.getNodeId = getNodeId;
  33741. function getSymbolId(symbol) {
  33742. if (!symbol.id) {
  33743. symbol.id = nextSymbolId;
  33744. nextSymbolId++;
  33745. }
  33746. return symbol.id;
  33747. }
  33748. ts.getSymbolId = getSymbolId;
  33749. function isInstantiatedModule(node, preserveConstEnums) {
  33750. var moduleState = ts.getModuleInstanceState(node);
  33751. return moduleState === 1 /* Instantiated */ ||
  33752. (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
  33753. }
  33754. ts.isInstantiatedModule = isInstantiatedModule;
  33755. function createTypeChecker(host, produceDiagnostics) {
  33756. var getPackagesSet = ts.memoize(function () {
  33757. var set = ts.createMap();
  33758. host.getSourceFiles().forEach(function (sf) {
  33759. if (!sf.resolvedModules)
  33760. return;
  33761. ts.forEachEntry(sf.resolvedModules, function (r) {
  33762. if (r && r.packageId)
  33763. set.set(r.packageId.name, true);
  33764. });
  33765. });
  33766. return set;
  33767. });
  33768. // Cancellation that controls whether or not we can cancel in the middle of type checking.
  33769. // In general cancelling is *not* safe for the type checker. We might be in the middle of
  33770. // computing something, and we will leave our internals in an inconsistent state. Callers
  33771. // who set the cancellation token should catch if a cancellation exception occurs, and
  33772. // should throw away and create a new TypeChecker.
  33773. //
  33774. // Currently we only support setting the cancellation token when getting diagnostics. This
  33775. // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
  33776. // they no longer need the information (for example, if the user started editing again).
  33777. var cancellationToken;
  33778. var requestedExternalEmitHelpers;
  33779. var externalHelpersModule;
  33780. var Symbol = ts.objectAllocator.getSymbolConstructor();
  33781. var Type = ts.objectAllocator.getTypeConstructor();
  33782. var Signature = ts.objectAllocator.getSignatureConstructor();
  33783. var typeCount = 0;
  33784. var symbolCount = 0;
  33785. var enumCount = 0;
  33786. var instantiationCount = 0;
  33787. var instantiationDepth = 0;
  33788. var constraintDepth = 0;
  33789. var currentNode;
  33790. var emptySymbols = ts.createSymbolTable();
  33791. var identityMapper = ts.identity;
  33792. var arrayVariances = [1 /* Covariant */];
  33793. var compilerOptions = host.getCompilerOptions();
  33794. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  33795. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  33796. var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
  33797. var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
  33798. var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
  33799. var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
  33800. var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
  33801. var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
  33802. var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
  33803. var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
  33804. var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
  33805. var emitResolver = createResolver();
  33806. var nodeBuilder = createNodeBuilder();
  33807. var globals = ts.createSymbolTable();
  33808. var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
  33809. undefinedSymbol.declarations = [];
  33810. var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
  33811. globalThisSymbol.exports = globals;
  33812. globalThisSymbol.declarations = [];
  33813. globals.set(globalThisSymbol.escapedName, globalThisSymbol);
  33814. var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
  33815. var requireSymbol = createSymbol(4 /* Property */, "require");
  33816. /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
  33817. var apparentArgumentCount;
  33818. // for public members that accept a Node or one of its subtypes, we must guard against
  33819. // synthetic nodes created during transformations by calling `getParseTreeNode`.
  33820. // for most of these, we perform the guard only on `checker` to avoid any possible
  33821. // extra cost of calling `getParseTreeNode` when calling these functions from inside the
  33822. // checker.
  33823. var checker = {
  33824. getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
  33825. getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
  33826. getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
  33827. getTypeCount: function () { return typeCount; },
  33828. getRelationCacheSizes: function () { return ({
  33829. assignable: assignableRelation.size,
  33830. identity: identityRelation.size,
  33831. subtype: subtypeRelation.size,
  33832. strictSubtype: strictSubtypeRelation.size,
  33833. }); },
  33834. isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
  33835. isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
  33836. isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
  33837. getMergedSymbol: getMergedSymbol,
  33838. getDiagnostics: getDiagnostics,
  33839. getGlobalDiagnostics: getGlobalDiagnostics,
  33840. getTypeOfSymbolAtLocation: function (symbol, location) {
  33841. location = ts.getParseTreeNode(location);
  33842. return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
  33843. },
  33844. getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
  33845. var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
  33846. if (parameter === undefined)
  33847. return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
  33848. return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
  33849. },
  33850. getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
  33851. getPropertiesOfType: getPropertiesOfType,
  33852. getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
  33853. getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
  33854. var node = ts.getParseTreeNode(location);
  33855. if (!node) {
  33856. return undefined;
  33857. }
  33858. var propName = ts.escapeLeadingUnderscores(name);
  33859. var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
  33860. return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
  33861. },
  33862. getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
  33863. getIndexInfoOfType: getIndexInfoOfType,
  33864. getSignaturesOfType: getSignaturesOfType,
  33865. getIndexTypeOfType: getIndexTypeOfType,
  33866. getBaseTypes: getBaseTypes,
  33867. getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
  33868. getWidenedType: getWidenedType,
  33869. getTypeFromTypeNode: function (nodeIn) {
  33870. var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
  33871. return node ? getTypeFromTypeNode(node) : errorType;
  33872. },
  33873. getParameterType: getTypeAtPosition,
  33874. getPromisedTypeOfPromise: getPromisedTypeOfPromise,
  33875. getReturnTypeOfSignature: getReturnTypeOfSignature,
  33876. isNullableType: isNullableType,
  33877. getNullableType: getNullableType,
  33878. getNonNullableType: getNonNullableType,
  33879. getNonOptionalType: removeOptionalTypeMarker,
  33880. getTypeArguments: getTypeArguments,
  33881. typeToTypeNode: nodeBuilder.typeToTypeNode,
  33882. indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
  33883. signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
  33884. symbolToEntityName: nodeBuilder.symbolToEntityName,
  33885. symbolToExpression: nodeBuilder.symbolToExpression,
  33886. symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
  33887. symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
  33888. typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
  33889. getSymbolsInScope: function (location, meaning) {
  33890. location = ts.getParseTreeNode(location);
  33891. return location ? getSymbolsInScope(location, meaning) : [];
  33892. },
  33893. getSymbolAtLocation: function (node) {
  33894. node = ts.getParseTreeNode(node);
  33895. return node ? getSymbolAtLocation(node) : undefined;
  33896. },
  33897. getShorthandAssignmentValueSymbol: function (node) {
  33898. node = ts.getParseTreeNode(node);
  33899. return node ? getShorthandAssignmentValueSymbol(node) : undefined;
  33900. },
  33901. getExportSpecifierLocalTargetSymbol: function (nodeIn) {
  33902. var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
  33903. return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
  33904. },
  33905. getExportSymbolOfSymbol: function (symbol) {
  33906. return getMergedSymbol(symbol.exportSymbol || symbol);
  33907. },
  33908. getTypeAtLocation: function (node) {
  33909. node = ts.getParseTreeNode(node);
  33910. return node ? getTypeOfNode(node) : errorType;
  33911. },
  33912. getTypeOfAssignmentPattern: function (nodeIn) {
  33913. var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
  33914. return node && getTypeOfAssignmentPattern(node) || errorType;
  33915. },
  33916. getPropertySymbolOfDestructuringAssignment: function (locationIn) {
  33917. var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
  33918. return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
  33919. },
  33920. signatureToString: function (signature, enclosingDeclaration, flags, kind) {
  33921. return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
  33922. },
  33923. typeToString: function (type, enclosingDeclaration, flags) {
  33924. return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
  33925. },
  33926. symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
  33927. return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
  33928. },
  33929. typePredicateToString: function (predicate, enclosingDeclaration, flags) {
  33930. return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
  33931. },
  33932. writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
  33933. return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
  33934. },
  33935. writeType: function (type, enclosingDeclaration, flags, writer) {
  33936. return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
  33937. },
  33938. writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
  33939. return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
  33940. },
  33941. writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
  33942. return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
  33943. },
  33944. getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
  33945. getRootSymbols: getRootSymbols,
  33946. getContextualType: function (nodeIn, contextFlags) {
  33947. var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
  33948. if (!node) {
  33949. return undefined;
  33950. }
  33951. var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
  33952. var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
  33953. if (contextFlags & 4 /* Completions */ && containingCall) {
  33954. var toMarkSkip = node;
  33955. do {
  33956. getNodeLinks(toMarkSkip).skipDirectInference = true;
  33957. toMarkSkip = toMarkSkip.parent;
  33958. } while (toMarkSkip && toMarkSkip !== containingCall);
  33959. getNodeLinks(containingCall).resolvedSignature = undefined;
  33960. }
  33961. var result = getContextualType(node, contextFlags);
  33962. if (contextFlags & 4 /* Completions */ && containingCall) {
  33963. var toMarkSkip = node;
  33964. do {
  33965. getNodeLinks(toMarkSkip).skipDirectInference = undefined;
  33966. toMarkSkip = toMarkSkip.parent;
  33967. } while (toMarkSkip && toMarkSkip !== containingCall);
  33968. getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
  33969. }
  33970. return result;
  33971. },
  33972. getContextualTypeForObjectLiteralElement: function (nodeIn) {
  33973. var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
  33974. return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
  33975. },
  33976. getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
  33977. var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
  33978. return node && getContextualTypeForArgumentAtIndex(node, argIndex);
  33979. },
  33980. getContextualTypeForJsxAttribute: function (nodeIn) {
  33981. var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
  33982. return node && getContextualTypeForJsxAttribute(node);
  33983. },
  33984. isContextSensitive: isContextSensitive,
  33985. getFullyQualifiedName: getFullyQualifiedName,
  33986. getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
  33987. return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
  33988. },
  33989. getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
  33990. return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
  33991. },
  33992. getExpandedParameters: getExpandedParameters,
  33993. hasEffectiveRestParameter: hasEffectiveRestParameter,
  33994. getConstantValue: function (nodeIn) {
  33995. var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
  33996. return node ? getConstantValue(node) : undefined;
  33997. },
  33998. isValidPropertyAccess: function (nodeIn, propertyName) {
  33999. var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
  34000. return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
  34001. },
  34002. isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
  34003. var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
  34004. return !!node && isValidPropertyAccessForCompletions(node, type, property);
  34005. },
  34006. getSignatureFromDeclaration: function (declarationIn) {
  34007. var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
  34008. return declaration ? getSignatureFromDeclaration(declaration) : undefined;
  34009. },
  34010. isImplementationOfOverload: function (node) {
  34011. var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
  34012. return parsed ? isImplementationOfOverload(parsed) : undefined;
  34013. },
  34014. getImmediateAliasedSymbol: getImmediateAliasedSymbol,
  34015. getAliasedSymbol: resolveAlias,
  34016. getEmitResolver: getEmitResolver,
  34017. getExportsOfModule: getExportsOfModuleAsArray,
  34018. getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
  34019. getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
  34020. getAmbientModules: getAmbientModules,
  34021. getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
  34022. isOptionalParameter: function (nodeIn) {
  34023. var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
  34024. return node ? isOptionalParameter(node) : false;
  34025. },
  34026. tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
  34027. tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
  34028. tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
  34029. // we deliberately exclude augmentations
  34030. // since we are only interested in declarations of the module itself
  34031. return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
  34032. },
  34033. getApparentType: getApparentType,
  34034. getUnionType: getUnionType,
  34035. isTypeAssignableTo: function (source, target) {
  34036. return isTypeAssignableTo(source, target);
  34037. },
  34038. createAnonymousType: createAnonymousType,
  34039. createSignature: createSignature,
  34040. createSymbol: createSymbol,
  34041. createIndexInfo: createIndexInfo,
  34042. getAnyType: function () { return anyType; },
  34043. getStringType: function () { return stringType; },
  34044. getNumberType: function () { return numberType; },
  34045. createPromiseType: createPromiseType,
  34046. createArrayType: createArrayType,
  34047. getElementTypeOfArrayType: getElementTypeOfArrayType,
  34048. getBooleanType: function () { return booleanType; },
  34049. getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
  34050. getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
  34051. getVoidType: function () { return voidType; },
  34052. getUndefinedType: function () { return undefinedType; },
  34053. getNullType: function () { return nullType; },
  34054. getESSymbolType: function () { return esSymbolType; },
  34055. getNeverType: function () { return neverType; },
  34056. getOptionalType: function () { return optionalType; },
  34057. isSymbolAccessible: isSymbolAccessible,
  34058. isArrayType: isArrayType,
  34059. isTupleType: isTupleType,
  34060. isArrayLikeType: isArrayLikeType,
  34061. isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
  34062. getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
  34063. getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
  34064. getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
  34065. getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
  34066. getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
  34067. getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
  34068. getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
  34069. getBaseConstraintOfType: getBaseConstraintOfType,
  34070. getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
  34071. resolveName: function (name, location, meaning, excludeGlobals) {
  34072. return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
  34073. },
  34074. getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
  34075. getAccessibleSymbolChain: getAccessibleSymbolChain,
  34076. getTypePredicateOfSignature: getTypePredicateOfSignature,
  34077. resolveExternalModuleSymbol: resolveExternalModuleSymbol,
  34078. tryGetThisTypeAt: function (node, includeGlobalThis) {
  34079. node = ts.getParseTreeNode(node);
  34080. return node && tryGetThisTypeAt(node, includeGlobalThis);
  34081. },
  34082. getTypeArgumentConstraint: function (nodeIn) {
  34083. var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
  34084. return node && getTypeArgumentConstraint(node);
  34085. },
  34086. getSuggestionDiagnostics: function (file, ct) {
  34087. if (ts.skipTypeChecking(file, compilerOptions, host)) {
  34088. return ts.emptyArray;
  34089. }
  34090. var diagnostics;
  34091. try {
  34092. // Record the cancellation token so it can be checked later on during checkSourceElement.
  34093. // Do this in a finally block so we can ensure that it gets reset back to nothing after
  34094. // this call is done.
  34095. cancellationToken = ct;
  34096. // Ensure file is type checked
  34097. checkSourceFile(file);
  34098. ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
  34099. diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
  34100. checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
  34101. if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
  34102. (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
  34103. }
  34104. });
  34105. return diagnostics || ts.emptyArray;
  34106. }
  34107. finally {
  34108. cancellationToken = undefined;
  34109. }
  34110. },
  34111. runWithCancellationToken: function (token, callback) {
  34112. try {
  34113. cancellationToken = token;
  34114. return callback(checker);
  34115. }
  34116. finally {
  34117. cancellationToken = undefined;
  34118. }
  34119. },
  34120. getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
  34121. isDeclarationVisible: isDeclarationVisible,
  34122. };
  34123. function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
  34124. var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
  34125. apparentArgumentCount = argumentCount;
  34126. var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
  34127. apparentArgumentCount = undefined;
  34128. return res;
  34129. }
  34130. var tupleTypes = ts.createMap();
  34131. var unionTypes = ts.createMap();
  34132. var intersectionTypes = ts.createMap();
  34133. var literalTypes = ts.createMap();
  34134. var indexedAccessTypes = ts.createMap();
  34135. var substitutionTypes = ts.createMap();
  34136. var evolvingArrayTypes = [];
  34137. var undefinedProperties = ts.createMap();
  34138. var unknownSymbol = createSymbol(4 /* Property */, "unknown");
  34139. var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
  34140. var anyType = createIntrinsicType(1 /* Any */, "any");
  34141. var autoType = createIntrinsicType(1 /* Any */, "any");
  34142. var wildcardType = createIntrinsicType(1 /* Any */, "any");
  34143. var errorType = createIntrinsicType(1 /* Any */, "error");
  34144. var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
  34145. var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
  34146. var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
  34147. var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
  34148. var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
  34149. var nullType = createIntrinsicType(65536 /* Null */, "null");
  34150. var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
  34151. var stringType = createIntrinsicType(4 /* String */, "string");
  34152. var numberType = createIntrinsicType(8 /* Number */, "number");
  34153. var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
  34154. var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
  34155. var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
  34156. var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
  34157. var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
  34158. trueType.regularType = regularTrueType;
  34159. trueType.freshType = trueType;
  34160. regularTrueType.regularType = regularTrueType;
  34161. regularTrueType.freshType = trueType;
  34162. falseType.regularType = regularFalseType;
  34163. falseType.freshType = falseType;
  34164. regularFalseType.regularType = regularFalseType;
  34165. regularFalseType.freshType = falseType;
  34166. var booleanType = createBooleanType([regularFalseType, regularTrueType]);
  34167. // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
  34168. // (The union is cached, so simply doing the marking here is sufficient)
  34169. createBooleanType([regularFalseType, trueType]);
  34170. createBooleanType([falseType, regularTrueType]);
  34171. createBooleanType([falseType, trueType]);
  34172. var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
  34173. var voidType = createIntrinsicType(16384 /* Void */, "void");
  34174. var neverType = createIntrinsicType(131072 /* Never */, "never");
  34175. var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
  34176. var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
  34177. var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
  34178. var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
  34179. var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
  34180. var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
  34181. var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
  34182. var numberOrBigIntType = getUnionType([numberType, bigintType]);
  34183. var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34184. var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34185. emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
  34186. var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
  34187. emptyTypeLiteralSymbol.members = ts.createSymbolTable();
  34188. var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34189. var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34190. emptyGenericType.instantiations = ts.createMap();
  34191. var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34192. // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
  34193. // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
  34194. anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
  34195. var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34196. var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34197. var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  34198. var markerSuperType = createTypeParameter();
  34199. var markerSubType = createTypeParameter();
  34200. markerSubType.constraint = markerSuperType;
  34201. var markerOtherType = createTypeParameter();
  34202. var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
  34203. var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
  34204. var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
  34205. var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
  34206. var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
  34207. var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
  34208. var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
  34209. var noIterationTypes = {
  34210. get yieldType() { return ts.Debug.fail("Not supported"); },
  34211. get returnType() { return ts.Debug.fail("Not supported"); },
  34212. get nextType() { return ts.Debug.fail("Not supported"); },
  34213. };
  34214. var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
  34215. var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
  34216. var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
  34217. var asyncIterationTypesResolver = {
  34218. iterableCacheKey: "iterationTypesOfAsyncIterable",
  34219. iteratorCacheKey: "iterationTypesOfAsyncIterator",
  34220. iteratorSymbolName: "asyncIterator",
  34221. getGlobalIteratorType: getGlobalAsyncIteratorType,
  34222. getGlobalIterableType: getGlobalAsyncIterableType,
  34223. getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
  34224. getGlobalGeneratorType: getGlobalAsyncGeneratorType,
  34225. resolveIterationType: getAwaitedType,
  34226. mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
  34227. mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
  34228. mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property,
  34229. };
  34230. var syncIterationTypesResolver = {
  34231. iterableCacheKey: "iterationTypesOfIterable",
  34232. iteratorCacheKey: "iterationTypesOfIterator",
  34233. iteratorSymbolName: "iterator",
  34234. getGlobalIteratorType: getGlobalIteratorType,
  34235. getGlobalIterableType: getGlobalIterableType,
  34236. getGlobalIterableIteratorType: getGlobalIterableIteratorType,
  34237. getGlobalGeneratorType: getGlobalGeneratorType,
  34238. resolveIterationType: function (type, _errorNode) { return type; },
  34239. mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
  34240. mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
  34241. mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
  34242. };
  34243. /** Key is "/path/to/a.ts|/path/to/b.ts". */
  34244. var amalgamatedDuplicates;
  34245. var reverseMappedCache = ts.createMap();
  34246. var ambientModulesCache;
  34247. /**
  34248. * List of every ambient module with a "*" wildcard.
  34249. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
  34250. * This is only used if there is no exact match.
  34251. */
  34252. var patternAmbientModules;
  34253. var patternAmbientModuleAugmentations;
  34254. var globalObjectType;
  34255. var globalFunctionType;
  34256. var globalCallableFunctionType;
  34257. var globalNewableFunctionType;
  34258. var globalArrayType;
  34259. var globalReadonlyArrayType;
  34260. var globalStringType;
  34261. var globalNumberType;
  34262. var globalBooleanType;
  34263. var globalRegExpType;
  34264. var globalThisType;
  34265. var anyArrayType;
  34266. var autoArrayType;
  34267. var anyReadonlyArrayType;
  34268. var deferredGlobalNonNullableTypeAlias;
  34269. // The library files are only loaded when the feature is used.
  34270. // This allows users to just specify library files they want to used through --lib
  34271. // and they will not get an error from not having unrelated library files
  34272. var deferredGlobalESSymbolConstructorSymbol;
  34273. var deferredGlobalESSymbolType;
  34274. var deferredGlobalTypedPropertyDescriptorType;
  34275. var deferredGlobalPromiseType;
  34276. var deferredGlobalPromiseLikeType;
  34277. var deferredGlobalPromiseConstructorSymbol;
  34278. var deferredGlobalPromiseConstructorLikeType;
  34279. var deferredGlobalIterableType;
  34280. var deferredGlobalIteratorType;
  34281. var deferredGlobalIterableIteratorType;
  34282. var deferredGlobalGeneratorType;
  34283. var deferredGlobalIteratorYieldResultType;
  34284. var deferredGlobalIteratorReturnResultType;
  34285. var deferredGlobalAsyncIterableType;
  34286. var deferredGlobalAsyncIteratorType;
  34287. var deferredGlobalAsyncIterableIteratorType;
  34288. var deferredGlobalAsyncGeneratorType;
  34289. var deferredGlobalTemplateStringsArrayType;
  34290. var deferredGlobalImportMetaType;
  34291. var deferredGlobalExtractSymbol;
  34292. var deferredGlobalOmitSymbol;
  34293. var deferredGlobalBigIntType;
  34294. var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
  34295. var flowLoopStart = 0;
  34296. var flowLoopCount = 0;
  34297. var sharedFlowCount = 0;
  34298. var flowAnalysisDisabled = false;
  34299. var flowInvocationCount = 0;
  34300. var lastFlowNode;
  34301. var lastFlowNodeReachable;
  34302. var flowTypeCache;
  34303. var emptyStringType = getLiteralType("");
  34304. var zeroType = getLiteralType(0);
  34305. var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
  34306. var resolutionTargets = [];
  34307. var resolutionResults = [];
  34308. var resolutionPropertyNames = [];
  34309. var suggestionCount = 0;
  34310. var maximumSuggestionCount = 10;
  34311. var mergedSymbols = [];
  34312. var symbolLinks = [];
  34313. var nodeLinks = [];
  34314. var flowLoopCaches = [];
  34315. var flowLoopNodes = [];
  34316. var flowLoopKeys = [];
  34317. var flowLoopTypes = [];
  34318. var sharedFlowNodes = [];
  34319. var sharedFlowTypes = [];
  34320. var flowNodeReachable = [];
  34321. var potentialThisCollisions = [];
  34322. var potentialNewTargetCollisions = [];
  34323. var potentialWeakMapCollisions = [];
  34324. var awaitedTypeStack = [];
  34325. var diagnostics = ts.createDiagnosticCollection();
  34326. var suggestionDiagnostics = ts.createDiagnosticCollection();
  34327. var typeofTypesByName = ts.createMapFromTemplate({
  34328. string: stringType,
  34329. number: numberType,
  34330. bigint: bigintType,
  34331. boolean: booleanType,
  34332. symbol: esSymbolType,
  34333. undefined: undefinedType
  34334. });
  34335. var typeofType = createTypeofType();
  34336. var _jsxNamespace;
  34337. var _jsxFactoryEntity;
  34338. var outofbandVarianceMarkerHandler;
  34339. var subtypeRelation = ts.createMap();
  34340. var strictSubtypeRelation = ts.createMap();
  34341. var assignableRelation = ts.createMap();
  34342. var comparableRelation = ts.createMap();
  34343. var identityRelation = ts.createMap();
  34344. var enumRelation = ts.createMap();
  34345. var builtinGlobals = ts.createSymbolTable();
  34346. builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
  34347. initializeTypeChecker();
  34348. return checker;
  34349. function getJsxNamespace(location) {
  34350. if (location) {
  34351. var file = ts.getSourceFileOfNode(location);
  34352. if (file) {
  34353. if (file.localJsxNamespace) {
  34354. return file.localJsxNamespace;
  34355. }
  34356. var jsxPragma = file.pragmas.get("jsx");
  34357. if (jsxPragma) {
  34358. var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
  34359. file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
  34360. if (file.localJsxFactory) {
  34361. return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
  34362. }
  34363. }
  34364. }
  34365. }
  34366. if (!_jsxNamespace) {
  34367. _jsxNamespace = "React";
  34368. if (compilerOptions.jsxFactory) {
  34369. _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
  34370. if (_jsxFactoryEntity) {
  34371. _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
  34372. }
  34373. }
  34374. else if (compilerOptions.reactNamespace) {
  34375. _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
  34376. }
  34377. }
  34378. return _jsxNamespace;
  34379. }
  34380. function getEmitResolver(sourceFile, cancellationToken) {
  34381. // Ensure we have all the type information in place for this file so that all the
  34382. // emitter questions of this resolver will return the right information.
  34383. getDiagnostics(sourceFile, cancellationToken);
  34384. return emitResolver;
  34385. }
  34386. function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
  34387. var diagnostic = location
  34388. ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
  34389. : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
  34390. var existing = diagnostics.lookup(diagnostic);
  34391. if (existing) {
  34392. return existing;
  34393. }
  34394. else {
  34395. diagnostics.add(diagnostic);
  34396. return diagnostic;
  34397. }
  34398. }
  34399. function error(location, message, arg0, arg1, arg2, arg3) {
  34400. var diagnostic = location
  34401. ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
  34402. : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
  34403. diagnostics.add(diagnostic);
  34404. return diagnostic;
  34405. }
  34406. function addErrorOrSuggestion(isError, diagnostic) {
  34407. if (isError) {
  34408. diagnostics.add(diagnostic);
  34409. }
  34410. else {
  34411. suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
  34412. }
  34413. }
  34414. function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
  34415. addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
  34416. }
  34417. function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
  34418. var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
  34419. if (maybeMissingAwait) {
  34420. var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
  34421. ts.addRelatedInfo(diagnostic, related);
  34422. }
  34423. return diagnostic;
  34424. }
  34425. function createSymbol(flags, name, checkFlags) {
  34426. symbolCount++;
  34427. var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
  34428. symbol.checkFlags = checkFlags || 0;
  34429. return symbol;
  34430. }
  34431. function getExcludedSymbolFlags(flags) {
  34432. var result = 0;
  34433. if (flags & 2 /* BlockScopedVariable */)
  34434. result |= 111551 /* BlockScopedVariableExcludes */;
  34435. if (flags & 1 /* FunctionScopedVariable */)
  34436. result |= 111550 /* FunctionScopedVariableExcludes */;
  34437. if (flags & 4 /* Property */)
  34438. result |= 0 /* PropertyExcludes */;
  34439. if (flags & 8 /* EnumMember */)
  34440. result |= 900095 /* EnumMemberExcludes */;
  34441. if (flags & 16 /* Function */)
  34442. result |= 110991 /* FunctionExcludes */;
  34443. if (flags & 32 /* Class */)
  34444. result |= 899503 /* ClassExcludes */;
  34445. if (flags & 64 /* Interface */)
  34446. result |= 788872 /* InterfaceExcludes */;
  34447. if (flags & 256 /* RegularEnum */)
  34448. result |= 899327 /* RegularEnumExcludes */;
  34449. if (flags & 128 /* ConstEnum */)
  34450. result |= 899967 /* ConstEnumExcludes */;
  34451. if (flags & 512 /* ValueModule */)
  34452. result |= 110735 /* ValueModuleExcludes */;
  34453. if (flags & 8192 /* Method */)
  34454. result |= 103359 /* MethodExcludes */;
  34455. if (flags & 32768 /* GetAccessor */)
  34456. result |= 46015 /* GetAccessorExcludes */;
  34457. if (flags & 65536 /* SetAccessor */)
  34458. result |= 78783 /* SetAccessorExcludes */;
  34459. if (flags & 262144 /* TypeParameter */)
  34460. result |= 526824 /* TypeParameterExcludes */;
  34461. if (flags & 524288 /* TypeAlias */)
  34462. result |= 788968 /* TypeAliasExcludes */;
  34463. if (flags & 2097152 /* Alias */)
  34464. result |= 2097152 /* AliasExcludes */;
  34465. return result;
  34466. }
  34467. function recordMergedSymbol(target, source) {
  34468. if (!source.mergeId) {
  34469. source.mergeId = nextMergeId;
  34470. nextMergeId++;
  34471. }
  34472. mergedSymbols[source.mergeId] = target;
  34473. }
  34474. function cloneSymbol(symbol) {
  34475. var result = createSymbol(symbol.flags, symbol.escapedName);
  34476. result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
  34477. result.parent = symbol.parent;
  34478. if (symbol.valueDeclaration)
  34479. result.valueDeclaration = symbol.valueDeclaration;
  34480. if (symbol.constEnumOnlyModule)
  34481. result.constEnumOnlyModule = true;
  34482. if (symbol.members)
  34483. result.members = ts.cloneMap(symbol.members);
  34484. if (symbol.exports)
  34485. result.exports = ts.cloneMap(symbol.exports);
  34486. recordMergedSymbol(result, symbol);
  34487. return result;
  34488. }
  34489. /**
  34490. * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
  34491. * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
  34492. */
  34493. function mergeSymbol(target, source, unidirectional) {
  34494. if (unidirectional === void 0) { unidirectional = false; }
  34495. if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
  34496. (source.flags | target.flags) & 67108864 /* Assignment */) {
  34497. if (source === target) {
  34498. // This can happen when an export assigned namespace exports something also erroneously exported at the top level
  34499. // See `declarationFileNoCrashOnExtraExportModifier` for an example
  34500. return target;
  34501. }
  34502. if (!(target.flags & 33554432 /* Transient */)) {
  34503. var resolvedTarget = resolveSymbol(target);
  34504. if (resolvedTarget === unknownSymbol) {
  34505. return source;
  34506. }
  34507. target = cloneSymbol(resolvedTarget);
  34508. }
  34509. // Javascript static-property-assignment declarations always merge, even though they are also values
  34510. if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
  34511. // reset flag when merging instantiated module into value module that has only const enums
  34512. target.constEnumOnlyModule = false;
  34513. }
  34514. target.flags |= source.flags;
  34515. if (source.valueDeclaration &&
  34516. (!target.valueDeclaration ||
  34517. ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) ||
  34518. ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) {
  34519. // other kinds of value declarations take precedence over modules and assignment declarations
  34520. target.valueDeclaration = source.valueDeclaration;
  34521. }
  34522. ts.addRange(target.declarations, source.declarations);
  34523. if (source.members) {
  34524. if (!target.members)
  34525. target.members = ts.createSymbolTable();
  34526. mergeSymbolTable(target.members, source.members, unidirectional);
  34527. }
  34528. if (source.exports) {
  34529. if (!target.exports)
  34530. target.exports = ts.createSymbolTable();
  34531. mergeSymbolTable(target.exports, source.exports, unidirectional);
  34532. }
  34533. if (!unidirectional) {
  34534. recordMergedSymbol(target, source);
  34535. }
  34536. }
  34537. else if (target.flags & 1024 /* NamespaceModule */) {
  34538. // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
  34539. // as we will already report a "Declaration name conflicts..." error, and this error
  34540. // won't make much sense.
  34541. if (target !== globalThisSymbol) {
  34542. error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
  34543. }
  34544. }
  34545. else { // error
  34546. var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
  34547. var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
  34548. var message = isEitherEnum
  34549. ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
  34550. : isEitherBlockScoped_1
  34551. ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
  34552. : ts.Diagnostics.Duplicate_identifier_0;
  34553. var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
  34554. var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
  34555. var symbolName_1 = symbolToString(source);
  34556. // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
  34557. if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
  34558. var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
  34559. var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
  34560. var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
  34561. return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
  34562. });
  34563. var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
  34564. return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
  34565. });
  34566. addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
  34567. addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
  34568. }
  34569. else {
  34570. addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
  34571. addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
  34572. }
  34573. }
  34574. return target;
  34575. function addDuplicateLocations(locs, symbol) {
  34576. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  34577. var decl = _a[_i];
  34578. ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl);
  34579. }
  34580. }
  34581. }
  34582. function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
  34583. ts.forEach(target.declarations, function (node) {
  34584. var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
  34585. addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations);
  34586. });
  34587. }
  34588. function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) {
  34589. var err = lookupOrIssueError(errorNode, message, symbolName);
  34590. for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
  34591. var relatedNode = _a[_i];
  34592. err.relatedInformation = err.relatedInformation || [];
  34593. if (ts.length(err.relatedInformation) >= 5)
  34594. continue;
  34595. ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
  34596. }
  34597. }
  34598. function combineSymbolTables(first, second) {
  34599. if (!ts.hasEntries(first))
  34600. return second;
  34601. if (!ts.hasEntries(second))
  34602. return first;
  34603. var combined = ts.createSymbolTable();
  34604. mergeSymbolTable(combined, first);
  34605. mergeSymbolTable(combined, second);
  34606. return combined;
  34607. }
  34608. function mergeSymbolTable(target, source, unidirectional) {
  34609. if (unidirectional === void 0) { unidirectional = false; }
  34610. source.forEach(function (sourceSymbol, id) {
  34611. var targetSymbol = target.get(id);
  34612. target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
  34613. });
  34614. }
  34615. function mergeModuleAugmentation(moduleName) {
  34616. var moduleAugmentation = moduleName.parent;
  34617. if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
  34618. // this is a combined symbol for multiple augmentations within the same file.
  34619. // its symbol already has accumulated information for all declarations
  34620. // so we need to add it just once - do the work only for first declaration
  34621. ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
  34622. return;
  34623. }
  34624. if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
  34625. mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
  34626. }
  34627. else {
  34628. // find a module that about to be augmented
  34629. // do not validate names of augmentations that are defined in ambient context
  34630. var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
  34631. ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
  34632. : undefined;
  34633. var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
  34634. if (!mainModule_1) {
  34635. return;
  34636. }
  34637. // obtain item referenced by 'export='
  34638. mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
  34639. if (mainModule_1.flags & 1920 /* Namespace */) {
  34640. // If we're merging an augmentation to a pattern ambient module, we want to
  34641. // perform the merge unidirectionally from the augmentation ('a.foo') to
  34642. // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
  34643. // all the exports both from the pattern and from the augmentation, but
  34644. // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
  34645. if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
  34646. var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
  34647. if (!patternAmbientModuleAugmentations) {
  34648. patternAmbientModuleAugmentations = ts.createMap();
  34649. }
  34650. // moduleName will be a StringLiteral since this is not `declare global`.
  34651. patternAmbientModuleAugmentations.set(moduleName.text, merged);
  34652. }
  34653. else {
  34654. mergeSymbol(mainModule_1, moduleAugmentation.symbol);
  34655. }
  34656. }
  34657. else {
  34658. // moduleName will be a StringLiteral since this is not `declare global`.
  34659. error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
  34660. }
  34661. }
  34662. }
  34663. function addToSymbolTable(target, source, message) {
  34664. source.forEach(function (sourceSymbol, id) {
  34665. var targetSymbol = target.get(id);
  34666. if (targetSymbol) {
  34667. // Error on redeclarations
  34668. ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
  34669. }
  34670. else {
  34671. target.set(id, sourceSymbol);
  34672. }
  34673. });
  34674. function addDeclarationDiagnostic(id, message) {
  34675. return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
  34676. }
  34677. }
  34678. function getSymbolLinks(symbol) {
  34679. if (symbol.flags & 33554432 /* Transient */)
  34680. return symbol;
  34681. var id = getSymbolId(symbol);
  34682. return symbolLinks[id] || (symbolLinks[id] = {});
  34683. }
  34684. function getNodeLinks(node) {
  34685. var nodeId = getNodeId(node);
  34686. return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
  34687. }
  34688. function isGlobalSourceFile(node) {
  34689. return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
  34690. }
  34691. function getSymbol(symbols, name, meaning) {
  34692. if (meaning) {
  34693. var symbol = symbols.get(name);
  34694. if (symbol) {
  34695. ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
  34696. if (symbol.flags & meaning) {
  34697. return symbol;
  34698. }
  34699. if (symbol.flags & 2097152 /* Alias */) {
  34700. var target = resolveAlias(symbol);
  34701. // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
  34702. if (target === unknownSymbol || target.flags & meaning) {
  34703. return symbol;
  34704. }
  34705. }
  34706. }
  34707. }
  34708. // return undefined if we can't find a symbol.
  34709. }
  34710. /**
  34711. * Get symbols that represent parameter-property-declaration as parameter and as property declaration
  34712. * @param parameter a parameterDeclaration node
  34713. * @param parameterName a name of the parameter to get the symbols for.
  34714. * @return a tuple of two symbols
  34715. */
  34716. function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
  34717. var constructorDeclaration = parameter.parent;
  34718. var classDeclaration = parameter.parent.parent;
  34719. var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
  34720. var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
  34721. if (parameterSymbol && propertySymbol) {
  34722. return [parameterSymbol, propertySymbol];
  34723. }
  34724. return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
  34725. }
  34726. function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
  34727. var declarationFile = ts.getSourceFileOfNode(declaration);
  34728. var useFile = ts.getSourceFileOfNode(usage);
  34729. if (declarationFile !== useFile) {
  34730. if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
  34731. (!compilerOptions.outFile && !compilerOptions.out) ||
  34732. isInTypeQuery(usage) ||
  34733. declaration.flags & 8388608 /* Ambient */) {
  34734. // nodes are in different files and order cannot be determined
  34735. return true;
  34736. }
  34737. // declaration is after usage
  34738. // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
  34739. if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
  34740. return true;
  34741. }
  34742. var sourceFiles = host.getSourceFiles();
  34743. return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
  34744. }
  34745. if (declaration.pos <= usage.pos) {
  34746. // declaration is before usage
  34747. if (declaration.kind === 191 /* BindingElement */) {
  34748. // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
  34749. var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
  34750. if (errorBindingElement) {
  34751. return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
  34752. declaration.pos < errorBindingElement.pos;
  34753. }
  34754. // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
  34755. return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
  34756. }
  34757. else if (declaration.kind === 242 /* VariableDeclaration */) {
  34758. // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
  34759. return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
  34760. }
  34761. else if (ts.isClassDeclaration(declaration)) {
  34762. // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
  34763. return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
  34764. }
  34765. else if (ts.isPropertyDeclaration(declaration)) {
  34766. // still might be illegal if a self-referencing property initializer (eg private x = this.x)
  34767. return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
  34768. }
  34769. else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
  34770. var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent);
  34771. // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
  34772. return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
  34773. && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
  34774. && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3));
  34775. }
  34776. return true;
  34777. }
  34778. // declaration is after usage, but it can still be legal if usage is deferred:
  34779. // 1. inside an export specifier
  34780. // 2. inside a function
  34781. // 3. inside an instance property initializer, a reference to a non-instance property
  34782. // (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
  34783. // 4. inside a static property initializer, a reference to a static method in the same class
  34784. // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
  34785. // or if usage is in a type context:
  34786. // 1. inside a type query (typeof in type position)
  34787. // 2. inside a jsdoc comment
  34788. if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
  34789. // export specifiers do not use the variable, they only make it available for use
  34790. return true;
  34791. }
  34792. // When resolving symbols for exports, the `usage` location passed in can be the export site directly
  34793. if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
  34794. return true;
  34795. }
  34796. var container = ts.getEnclosingBlockScopeContainer(declaration);
  34797. if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) {
  34798. return true;
  34799. }
  34800. if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) {
  34801. if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields) {
  34802. return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) &&
  34803. !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
  34804. }
  34805. else {
  34806. return true;
  34807. }
  34808. }
  34809. return false;
  34810. function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
  34811. var container = ts.getEnclosingBlockScopeContainer(declaration);
  34812. switch (declaration.parent.parent.kind) {
  34813. case 225 /* VariableStatement */:
  34814. case 230 /* ForStatement */:
  34815. case 232 /* ForOfStatement */:
  34816. // variable statement/for/for-of statement case,
  34817. // use site should not be inside variable declaration (initializer of declaration or binding element)
  34818. if (isSameScopeDescendentOf(usage, declaration, container)) {
  34819. return true;
  34820. }
  34821. break;
  34822. }
  34823. // ForIn/ForOf case - use site should not be used in expression part
  34824. var grandparent = declaration.parent.parent;
  34825. return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container);
  34826. }
  34827. function isUsedInFunctionOrInstanceProperty(usage, declaration, container) {
  34828. return !!ts.findAncestor(usage, function (current) {
  34829. if (current === container) {
  34830. return "quit";
  34831. }
  34832. if (ts.isFunctionLike(current)) {
  34833. return true;
  34834. }
  34835. var initializerOfProperty = current.parent &&
  34836. current.parent.kind === 159 /* PropertyDeclaration */ &&
  34837. current.parent.initializer === current;
  34838. if (initializerOfProperty) {
  34839. if (ts.hasModifier(current.parent, 32 /* Static */)) {
  34840. if (declaration.kind === 161 /* MethodDeclaration */) {
  34841. return true;
  34842. }
  34843. }
  34844. else {
  34845. var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
  34846. if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
  34847. return true;
  34848. }
  34849. }
  34850. }
  34851. return false;
  34852. });
  34853. }
  34854. /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
  34855. function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
  34856. // always legal if usage is after declaration
  34857. if (usage.end > declaration.end) {
  34858. return false;
  34859. }
  34860. // still might be legal if usage is deferred (e.g. x: any = () => this.x)
  34861. // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
  34862. var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
  34863. if (node === declaration) {
  34864. return "quit";
  34865. }
  34866. switch (node.kind) {
  34867. case 202 /* ArrowFunction */:
  34868. return true;
  34869. case 159 /* PropertyDeclaration */:
  34870. // even when stopping at any property declaration, they need to come from the same class
  34871. return stopAtAnyPropertyDeclaration &&
  34872. (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
  34873. || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
  34874. ? "quit" : true;
  34875. case 223 /* Block */:
  34876. switch (node.parent.kind) {
  34877. case 163 /* GetAccessor */:
  34878. case 161 /* MethodDeclaration */:
  34879. case 164 /* SetAccessor */:
  34880. return true;
  34881. default:
  34882. return false;
  34883. }
  34884. default:
  34885. return false;
  34886. }
  34887. });
  34888. return ancestorChangingReferenceScope === undefined;
  34889. }
  34890. }
  34891. /**
  34892. * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
  34893. * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
  34894. * the given name can be found.
  34895. *
  34896. * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
  34897. */
  34898. function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
  34899. if (excludeGlobals === void 0) { excludeGlobals = false; }
  34900. return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
  34901. }
  34902. function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
  34903. var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
  34904. var result;
  34905. var lastLocation;
  34906. var lastSelfReferenceLocation;
  34907. var propertyWithInvalidInitializer;
  34908. var associatedDeclarationForContainingInitializer;
  34909. var withinDeferredContext = false;
  34910. var errorLocation = location;
  34911. var grandparent;
  34912. var isInExternalModule = false;
  34913. loop: while (location) {
  34914. // Locals of a source file are not in scope (because they get merged into the global symbol table)
  34915. if (location.locals && !isGlobalSourceFile(location)) {
  34916. if (result = lookup(location.locals, name, meaning)) {
  34917. var useResult = true;
  34918. if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
  34919. // symbol lookup restrictions for function-like declarations
  34920. // - Type parameters of a function are in scope in the entire function declaration, including the parameter
  34921. // list and return type. However, local types are only in scope in the function body.
  34922. // - parameters are only in the scope of function body
  34923. // This restriction does not apply to JSDoc comment types because they are parented
  34924. // at a higher level than type parameters would normally be
  34925. if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
  34926. useResult = result.flags & 262144 /* TypeParameter */
  34927. // type parameters are visible in parameter list, return type and type parameter list
  34928. ? lastLocation === location.type ||
  34929. lastLocation.kind === 156 /* Parameter */ ||
  34930. lastLocation.kind === 155 /* TypeParameter */
  34931. // local types not visible outside the function body
  34932. : false;
  34933. }
  34934. if (meaning & result.flags & 3 /* Variable */) {
  34935. // expression inside parameter will lookup as normal variable scope when targeting es2015+
  34936. var functionLocation = location;
  34937. if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) &&
  34938. functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
  34939. useResult = false;
  34940. }
  34941. else if (result.flags & 1 /* FunctionScopedVariable */) {
  34942. // parameters are visible only inside function body, parameter list and return type
  34943. // technically for parameter list case here we might mix parameters and variables declared in function,
  34944. // however it is detected separately when checking initializers of parameters
  34945. // to make sure that they reference no variables declared after them.
  34946. useResult =
  34947. lastLocation.kind === 156 /* Parameter */ ||
  34948. (lastLocation === location.type &&
  34949. !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
  34950. }
  34951. }
  34952. }
  34953. else if (location.kind === 180 /* ConditionalType */) {
  34954. // A type parameter declared using 'infer T' in a conditional type is visible only in
  34955. // the true branch of the conditional type.
  34956. useResult = lastLocation === location.trueType;
  34957. }
  34958. if (useResult) {
  34959. break loop;
  34960. }
  34961. else {
  34962. result = undefined;
  34963. }
  34964. }
  34965. }
  34966. withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
  34967. switch (location.kind) {
  34968. case 290 /* SourceFile */:
  34969. if (!ts.isExternalOrCommonJsModule(location))
  34970. break;
  34971. isInExternalModule = true;
  34972. // falls through
  34973. case 249 /* ModuleDeclaration */:
  34974. var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
  34975. if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
  34976. // It's an external module. First see if the module has an export default and if the local
  34977. // name of that export default matches.
  34978. if (result = moduleExports.get("default" /* Default */)) {
  34979. var localSymbol = ts.getLocalSymbolForExportDefault(result);
  34980. if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
  34981. break loop;
  34982. }
  34983. result = undefined;
  34984. }
  34985. // Because of module/namespace merging, a module's exports are in scope,
  34986. // yet we never want to treat an export specifier as putting a member in scope.
  34987. // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
  34988. // Two things to note about this:
  34989. // 1. We have to check this without calling getSymbol. The problem with calling getSymbol
  34990. // on an export specifier is that it might find the export specifier itself, and try to
  34991. // resolve it as an alias. This will cause the checker to consider the export specifier
  34992. // a circular alias reference when it might not be.
  34993. // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
  34994. // an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
  34995. // which is not the desired behavior.
  34996. var moduleExport = moduleExports.get(name);
  34997. if (moduleExport &&
  34998. moduleExport.flags === 2097152 /* Alias */ &&
  34999. (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
  35000. break;
  35001. }
  35002. }
  35003. // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
  35004. if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
  35005. if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
  35006. result = undefined;
  35007. }
  35008. else {
  35009. break loop;
  35010. }
  35011. }
  35012. break;
  35013. case 248 /* EnumDeclaration */:
  35014. if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
  35015. break loop;
  35016. }
  35017. break;
  35018. case 159 /* PropertyDeclaration */:
  35019. // TypeScript 1.0 spec (April 2014): 8.4.1
  35020. // Initializer expressions for instance member variables are evaluated in the scope
  35021. // of the class constructor body but are not permitted to reference parameters or
  35022. // local variables of the constructor. This effectively means that entities from outer scopes
  35023. // by the same name as a constructor parameter or local variable are inaccessible
  35024. // in initializer expressions for instance member variables.
  35025. if (!ts.hasModifier(location, 32 /* Static */)) {
  35026. var ctor = findConstructorDeclaration(location.parent);
  35027. if (ctor && ctor.locals) {
  35028. if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
  35029. // Remember the property node, it will be used later to report appropriate error
  35030. propertyWithInvalidInitializer = location;
  35031. }
  35032. }
  35033. }
  35034. break;
  35035. case 245 /* ClassDeclaration */:
  35036. case 214 /* ClassExpression */:
  35037. case 246 /* InterfaceDeclaration */:
  35038. // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
  35039. // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
  35040. // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
  35041. if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
  35042. if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
  35043. // ignore type parameters not declared in this container
  35044. result = undefined;
  35045. break;
  35046. }
  35047. if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
  35048. // TypeScript 1.0 spec (April 2014): 3.4.1
  35049. // The scope of a type parameter extends over the entire declaration with which the type
  35050. // parameter list is associated, with the exception of static member declarations in classes.
  35051. error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
  35052. return undefined;
  35053. }
  35054. break loop;
  35055. }
  35056. if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
  35057. var className = location.name;
  35058. if (className && name === className.escapedText) {
  35059. result = location.symbol;
  35060. break loop;
  35061. }
  35062. }
  35063. break;
  35064. case 216 /* ExpressionWithTypeArguments */:
  35065. // The type parameters of a class are not in scope in the base class expression.
  35066. if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
  35067. var container = location.parent.parent;
  35068. if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
  35069. if (nameNotFoundMessage) {
  35070. error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
  35071. }
  35072. return undefined;
  35073. }
  35074. }
  35075. break;
  35076. // It is not legal to reference a class's own type parameters from a computed property name that
  35077. // belongs to the class. For example:
  35078. //
  35079. // function foo<T>() { return '' }
  35080. // class C<T> { // <-- Class's own type parameter T
  35081. // [foo<T>()]() { } // <-- Reference to T from class's own computed property
  35082. // }
  35083. //
  35084. case 154 /* ComputedPropertyName */:
  35085. grandparent = location.parent.parent;
  35086. if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
  35087. // A reference to this grandparent's type parameters would be an error
  35088. if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
  35089. error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
  35090. return undefined;
  35091. }
  35092. }
  35093. break;
  35094. case 202 /* ArrowFunction */:
  35095. // when targeting ES6 or higher there is no 'arguments' in an arrow function
  35096. // for lower compile targets the resolved symbol is used to emit an error
  35097. if (compilerOptions.target >= 2 /* ES2015 */) {
  35098. break;
  35099. }
  35100. // falls through
  35101. case 161 /* MethodDeclaration */:
  35102. case 162 /* Constructor */:
  35103. case 163 /* GetAccessor */:
  35104. case 164 /* SetAccessor */:
  35105. case 244 /* FunctionDeclaration */:
  35106. if (meaning & 3 /* Variable */ && name === "arguments") {
  35107. result = argumentsSymbol;
  35108. break loop;
  35109. }
  35110. break;
  35111. case 201 /* FunctionExpression */:
  35112. if (meaning & 3 /* Variable */ && name === "arguments") {
  35113. result = argumentsSymbol;
  35114. break loop;
  35115. }
  35116. if (meaning & 16 /* Function */) {
  35117. var functionName = location.name;
  35118. if (functionName && name === functionName.escapedText) {
  35119. result = location.symbol;
  35120. break loop;
  35121. }
  35122. }
  35123. break;
  35124. case 157 /* Decorator */:
  35125. // Decorators are resolved at the class declaration. Resolving at the parameter
  35126. // or member would result in looking up locals in the method.
  35127. //
  35128. // function y() {}
  35129. // class C {
  35130. // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
  35131. // }
  35132. //
  35133. if (location.parent && location.parent.kind === 156 /* Parameter */) {
  35134. location = location.parent;
  35135. }
  35136. //
  35137. // function y() {}
  35138. // class C {
  35139. // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
  35140. // }
  35141. //
  35142. // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
  35143. //
  35144. // type T = number;
  35145. // declare function y(x: T): any;
  35146. // @param(1 as T) // <-- T should resolve to the type alias outside of class C
  35147. // class C<T> {}
  35148. if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
  35149. location = location.parent;
  35150. }
  35151. break;
  35152. case 321 /* JSDocTypedefTag */:
  35153. case 314 /* JSDocCallbackTag */:
  35154. case 315 /* JSDocEnumTag */:
  35155. // js type aliases do not resolve names from their host, so skip past it
  35156. location = ts.getJSDocHost(location);
  35157. break;
  35158. case 156 /* Parameter */:
  35159. if (lastLocation && lastLocation === location.initializer) {
  35160. associatedDeclarationForContainingInitializer = location;
  35161. }
  35162. break;
  35163. case 191 /* BindingElement */:
  35164. if (lastLocation && lastLocation === location.initializer) {
  35165. var root = ts.getRootDeclaration(location);
  35166. if (root.kind === 156 /* Parameter */) {
  35167. associatedDeclarationForContainingInitializer = location;
  35168. }
  35169. }
  35170. break;
  35171. }
  35172. if (isSelfReferenceLocation(location)) {
  35173. lastSelfReferenceLocation = location;
  35174. }
  35175. lastLocation = location;
  35176. location = location.parent;
  35177. }
  35178. // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
  35179. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
  35180. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
  35181. if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
  35182. result.isReferenced |= meaning;
  35183. }
  35184. if (!result) {
  35185. if (lastLocation) {
  35186. ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
  35187. if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
  35188. return lastLocation.symbol;
  35189. }
  35190. }
  35191. if (!excludeGlobals) {
  35192. result = lookup(globals, name, meaning);
  35193. }
  35194. }
  35195. if (!result) {
  35196. if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
  35197. if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
  35198. return requireSymbol;
  35199. }
  35200. }
  35201. }
  35202. if (!result) {
  35203. if (nameNotFoundMessage) {
  35204. if (!errorLocation ||
  35205. !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
  35206. !checkAndReportErrorForExtendingInterface(errorLocation) &&
  35207. !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
  35208. !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
  35209. !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
  35210. !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
  35211. !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
  35212. var suggestion = void 0;
  35213. if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
  35214. suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
  35215. if (suggestion) {
  35216. var suggestionName = symbolToString(suggestion);
  35217. var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
  35218. if (suggestion.valueDeclaration) {
  35219. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
  35220. }
  35221. }
  35222. }
  35223. if (!suggestion) {
  35224. error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
  35225. }
  35226. suggestionCount++;
  35227. }
  35228. }
  35229. return undefined;
  35230. }
  35231. // Perform extra checks only if error reporting was requested
  35232. if (nameNotFoundMessage) {
  35233. if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
  35234. // We have a match, but the reference occurred within a property initializer and the identifier also binds
  35235. // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
  35236. // with ESNext+useDefineForClassFields because the scope semantics are different.
  35237. var propertyName = propertyWithInvalidInitializer.name;
  35238. error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
  35239. return undefined;
  35240. }
  35241. // Only check for block-scoped variable if we have an error location and are looking for the
  35242. // name with variable meaning
  35243. // For example,
  35244. // declare module foo {
  35245. // interface bar {}
  35246. // }
  35247. // const foo/*1*/: foo/*2*/.bar;
  35248. // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
  35249. // block-scoped variable and namespace module. However, only when we
  35250. // try to resolve name in /*1*/ which is used in variable position,
  35251. // we want to check for block-scoped
  35252. if (errorLocation &&
  35253. (meaning & 2 /* BlockScopedVariable */ ||
  35254. ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
  35255. var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
  35256. if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
  35257. checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
  35258. }
  35259. }
  35260. // If we're in an external module, we can't reference value symbols created from UMD export declarations
  35261. if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
  35262. var merged = getMergedSymbol(result);
  35263. if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
  35264. errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name));
  35265. }
  35266. }
  35267. // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right
  35268. if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
  35269. var candidate = getMergedSymbol(getLateBoundSymbol(result));
  35270. var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer);
  35271. // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
  35272. if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) {
  35273. error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name));
  35274. }
  35275. // And it cannot refer to any declarations which come after it
  35276. else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
  35277. error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation));
  35278. }
  35279. }
  35280. if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
  35281. checkSymbolUsageInExpressionContext(result, name, errorLocation);
  35282. }
  35283. }
  35284. return result;
  35285. }
  35286. function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
  35287. if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
  35288. var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
  35289. if (typeOnlyDeclaration) {
  35290. var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
  35291. var message = isExport
  35292. ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
  35293. : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
  35294. var relatedMessage = isExport
  35295. ? ts.Diagnostics._0_was_exported_here
  35296. : ts.Diagnostics._0_was_imported_here;
  35297. var unescapedName = ts.unescapeLeadingUnderscores(name);
  35298. ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
  35299. }
  35300. }
  35301. }
  35302. function getIsDeferredContext(location, lastLocation) {
  35303. if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
  35304. // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
  35305. return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
  35306. (location.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
  35307. }
  35308. if (lastLocation && lastLocation === location.name) {
  35309. return false;
  35310. }
  35311. // generator functions and async functions are not inlined in control flow when immediately invoked
  35312. if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
  35313. return true;
  35314. }
  35315. return !ts.getImmediatelyInvokedFunctionExpression(location);
  35316. }
  35317. function isSelfReferenceLocation(node) {
  35318. switch (node.kind) {
  35319. case 244 /* FunctionDeclaration */:
  35320. case 245 /* ClassDeclaration */:
  35321. case 246 /* InterfaceDeclaration */:
  35322. case 248 /* EnumDeclaration */:
  35323. case 247 /* TypeAliasDeclaration */:
  35324. case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
  35325. return true;
  35326. default:
  35327. return false;
  35328. }
  35329. }
  35330. function diagnosticName(nameArg) {
  35331. return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
  35332. }
  35333. function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
  35334. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  35335. var decl = _a[_i];
  35336. if (decl.kind === 155 /* TypeParameter */) {
  35337. var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
  35338. if (parent === container) {
  35339. return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
  35340. }
  35341. }
  35342. }
  35343. return false;
  35344. }
  35345. function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
  35346. if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
  35347. return false;
  35348. }
  35349. var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
  35350. var location = container;
  35351. while (location) {
  35352. if (ts.isClassLike(location.parent)) {
  35353. var classSymbol = getSymbolOfNode(location.parent);
  35354. if (!classSymbol) {
  35355. break;
  35356. }
  35357. // Check to see if a static member exists.
  35358. var constructorType = getTypeOfSymbol(classSymbol);
  35359. if (getPropertyOfType(constructorType, name)) {
  35360. error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
  35361. return true;
  35362. }
  35363. // No static member is present.
  35364. // Check if we're in an instance method and look for a relevant instance member.
  35365. if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
  35366. var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
  35367. if (getPropertyOfType(instanceType, name)) {
  35368. error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
  35369. return true;
  35370. }
  35371. }
  35372. }
  35373. location = location.parent;
  35374. }
  35375. return false;
  35376. }
  35377. function checkAndReportErrorForExtendingInterface(errorLocation) {
  35378. var expression = getEntityNameForExtendingInterface(errorLocation);
  35379. if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
  35380. error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
  35381. return true;
  35382. }
  35383. return false;
  35384. }
  35385. /**
  35386. * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
  35387. * but returns undefined if that expression is not an EntityNameExpression.
  35388. */
  35389. function getEntityNameForExtendingInterface(node) {
  35390. switch (node.kind) {
  35391. case 75 /* Identifier */:
  35392. case 194 /* PropertyAccessExpression */:
  35393. return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
  35394. case 216 /* ExpressionWithTypeArguments */:
  35395. if (ts.isEntityNameExpression(node.expression)) {
  35396. return node.expression;
  35397. }
  35398. // falls through
  35399. default:
  35400. return undefined;
  35401. }
  35402. }
  35403. function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
  35404. var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
  35405. if (meaning === namespaceMeaning) {
  35406. var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
  35407. var parent = errorLocation.parent;
  35408. if (symbol) {
  35409. if (ts.isQualifiedName(parent)) {
  35410. ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
  35411. var propName = parent.right.escapedText;
  35412. var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
  35413. if (propType) {
  35414. error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName));
  35415. return true;
  35416. }
  35417. }
  35418. error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
  35419. return true;
  35420. }
  35421. }
  35422. return false;
  35423. }
  35424. function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
  35425. if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
  35426. var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
  35427. if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
  35428. error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
  35429. return true;
  35430. }
  35431. }
  35432. return false;
  35433. }
  35434. function isPrimitiveTypeName(name) {
  35435. return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
  35436. }
  35437. function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
  35438. if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
  35439. error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
  35440. return true;
  35441. }
  35442. return false;
  35443. }
  35444. function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
  35445. if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
  35446. if (isPrimitiveTypeName(name)) {
  35447. error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
  35448. return true;
  35449. }
  35450. var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
  35451. if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
  35452. var message = isES2015OrLaterConstructorName(name)
  35453. ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
  35454. : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
  35455. error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
  35456. return true;
  35457. }
  35458. }
  35459. return false;
  35460. }
  35461. function isES2015OrLaterConstructorName(n) {
  35462. switch (n) {
  35463. case "Promise":
  35464. case "Symbol":
  35465. case "Map":
  35466. case "WeakMap":
  35467. case "Set":
  35468. case "WeakSet":
  35469. return true;
  35470. }
  35471. return false;
  35472. }
  35473. function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
  35474. if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
  35475. var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
  35476. if (symbol) {
  35477. error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
  35478. return true;
  35479. }
  35480. }
  35481. else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
  35482. var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
  35483. if (symbol) {
  35484. error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
  35485. return true;
  35486. }
  35487. }
  35488. return false;
  35489. }
  35490. function checkResolvedBlockScopedVariable(result, errorLocation) {
  35491. ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
  35492. if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
  35493. // constructor functions aren't block scoped
  35494. return;
  35495. }
  35496. // Block-scoped variables cannot be used before their definition
  35497. var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
  35498. if (declaration === undefined)
  35499. return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
  35500. if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
  35501. var diagnosticMessage = void 0;
  35502. var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
  35503. if (result.flags & 2 /* BlockScopedVariable */) {
  35504. diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
  35505. }
  35506. else if (result.flags & 32 /* Class */) {
  35507. diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
  35508. }
  35509. else if (result.flags & 256 /* RegularEnum */) {
  35510. diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
  35511. }
  35512. else {
  35513. ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
  35514. if (compilerOptions.preserveConstEnums) {
  35515. diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
  35516. }
  35517. }
  35518. if (diagnosticMessage) {
  35519. ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
  35520. }
  35521. }
  35522. }
  35523. /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
  35524. * If at any point current node is equal to 'parent' node - return true.
  35525. * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
  35526. */
  35527. function isSameScopeDescendentOf(initial, parent, stopAt) {
  35528. return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
  35529. }
  35530. function getAnyImportSyntax(node) {
  35531. switch (node.kind) {
  35532. case 253 /* ImportEqualsDeclaration */:
  35533. return node;
  35534. case 255 /* ImportClause */:
  35535. return node.parent;
  35536. case 256 /* NamespaceImport */:
  35537. return node.parent.parent;
  35538. case 258 /* ImportSpecifier */:
  35539. return node.parent.parent.parent;
  35540. default:
  35541. return undefined;
  35542. }
  35543. }
  35544. function getDeclarationOfAliasSymbol(symbol) {
  35545. return ts.find(symbol.declarations, isAliasSymbolDeclaration);
  35546. }
  35547. /**
  35548. * An alias symbol is created by one of the following declarations:
  35549. * import <symbol> = ...
  35550. * import <symbol> from ...
  35551. * import * as <symbol> from ...
  35552. * import { x as <symbol> } from ...
  35553. * export { x as <symbol> } from ...
  35554. * export * as ns <symbol> from ...
  35555. * export = <EntityNameExpression>
  35556. * export default <EntityNameExpression>
  35557. * module.exports = <EntityNameExpression>
  35558. * {<Identifier>}
  35559. * {name: <EntityNameExpression>}
  35560. */
  35561. function isAliasSymbolDeclaration(node) {
  35562. return node.kind === 253 /* ImportEqualsDeclaration */ ||
  35563. node.kind === 252 /* NamespaceExportDeclaration */ ||
  35564. node.kind === 255 /* ImportClause */ && !!node.name ||
  35565. node.kind === 256 /* NamespaceImport */ ||
  35566. node.kind === 262 /* NamespaceExport */ ||
  35567. node.kind === 258 /* ImportSpecifier */ ||
  35568. node.kind === 263 /* ExportSpecifier */ ||
  35569. node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
  35570. ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
  35571. ts.isPropertyAccessExpression(node)
  35572. && ts.isBinaryExpression(node.parent)
  35573. && node.parent.left === node
  35574. && node.parent.operatorToken.kind === 62 /* EqualsToken */
  35575. && isAliasableOrJsExpression(node.parent.right) ||
  35576. node.kind === 282 /* ShorthandPropertyAssignment */ ||
  35577. node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
  35578. }
  35579. function isAliasableOrJsExpression(e) {
  35580. return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
  35581. }
  35582. function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
  35583. if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
  35584. var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
  35585. var resolved_4 = resolveExternalModuleSymbol(immediate);
  35586. markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
  35587. return resolved_4;
  35588. }
  35589. var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
  35590. checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
  35591. return resolved;
  35592. }
  35593. function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
  35594. if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
  35595. var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
  35596. var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
  35597. var message = isExport
  35598. ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
  35599. : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
  35600. var relatedMessage = isExport
  35601. ? ts.Diagnostics._0_was_exported_here
  35602. : ts.Diagnostics._0_was_imported_here;
  35603. // Non-null assertion is safe because the optionality comes from ImportClause,
  35604. // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
  35605. var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
  35606. ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
  35607. }
  35608. }
  35609. function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
  35610. var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
  35611. if (exportValue) {
  35612. return getPropertyOfType(getTypeOfSymbol(exportValue), name);
  35613. }
  35614. var exportSymbol = moduleSymbol.exports.get(name);
  35615. var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
  35616. markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
  35617. return resolved;
  35618. }
  35619. function isSyntacticDefault(node) {
  35620. return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
  35621. }
  35622. function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
  35623. if (!allowSyntheticDefaultImports) {
  35624. return false;
  35625. }
  35626. // Declaration files (and ambient modules)
  35627. if (!file || file.isDeclarationFile) {
  35628. // Definitely cannot have a synthetic default if they have a syntactic default member specified
  35629. var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
  35630. if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
  35631. return false;
  35632. }
  35633. // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
  35634. // So we check a bit more,
  35635. if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
  35636. // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
  35637. // it definitely is a module and does not have a synthetic default
  35638. return false;
  35639. }
  35640. // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
  35641. // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
  35642. // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
  35643. return true;
  35644. }
  35645. // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
  35646. if (!ts.isSourceFileJS(file)) {
  35647. return hasExportAssignmentSymbol(moduleSymbol);
  35648. }
  35649. // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker
  35650. return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
  35651. }
  35652. function getTargetOfImportClause(node, dontResolveAlias) {
  35653. var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
  35654. if (moduleSymbol) {
  35655. var exportDefaultSymbol = void 0;
  35656. if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
  35657. exportDefaultSymbol = moduleSymbol;
  35658. }
  35659. else {
  35660. exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
  35661. }
  35662. var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
  35663. var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
  35664. if (!exportDefaultSymbol && !hasSyntheticDefault) {
  35665. if (hasExportAssignmentSymbol(moduleSymbol)) {
  35666. var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
  35667. var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
  35668. var exportAssignment = exportEqualsSymbol.valueDeclaration;
  35669. var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
  35670. ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName));
  35671. }
  35672. else {
  35673. if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) {
  35674. error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol));
  35675. }
  35676. else {
  35677. error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
  35678. }
  35679. }
  35680. }
  35681. else if (hasSyntheticDefault) {
  35682. // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
  35683. var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
  35684. markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
  35685. return resolved;
  35686. }
  35687. markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
  35688. return exportDefaultSymbol;
  35689. }
  35690. }
  35691. function getTargetOfNamespaceImport(node, dontResolveAlias) {
  35692. var moduleSpecifier = node.parent.parent.moduleSpecifier;
  35693. var immediate = resolveExternalModuleName(node, moduleSpecifier);
  35694. var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
  35695. markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
  35696. return resolved;
  35697. }
  35698. function getTargetOfNamespaceExport(node, dontResolveAlias) {
  35699. var moduleSpecifier = node.parent.moduleSpecifier;
  35700. var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
  35701. var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
  35702. markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
  35703. return resolved;
  35704. }
  35705. // This function creates a synthetic symbol that combines the value side of one symbol with the
  35706. // type/namespace side of another symbol. Consider this example:
  35707. //
  35708. // declare module graphics {
  35709. // interface Point {
  35710. // x: number;
  35711. // y: number;
  35712. // }
  35713. // }
  35714. // declare var graphics: {
  35715. // Point: new (x: number, y: number) => graphics.Point;
  35716. // }
  35717. // declare module "graphics" {
  35718. // export = graphics;
  35719. // }
  35720. //
  35721. // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
  35722. // property with the type/namespace side interface 'Point'.
  35723. function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
  35724. if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
  35725. return unknownSymbol;
  35726. }
  35727. if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
  35728. return valueSymbol;
  35729. }
  35730. var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
  35731. result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
  35732. result.parent = valueSymbol.parent || typeSymbol.parent;
  35733. if (valueSymbol.valueDeclaration)
  35734. result.valueDeclaration = valueSymbol.valueDeclaration;
  35735. if (typeSymbol.members)
  35736. result.members = ts.cloneMap(typeSymbol.members);
  35737. if (valueSymbol.exports)
  35738. result.exports = ts.cloneMap(valueSymbol.exports);
  35739. return result;
  35740. }
  35741. function getExportOfModule(symbol, specifier, dontResolveAlias) {
  35742. var _a;
  35743. if (symbol.flags & 1536 /* Module */) {
  35744. var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
  35745. var exportSymbol = getExportsOfSymbol(symbol).get(name);
  35746. var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
  35747. markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
  35748. return resolved;
  35749. }
  35750. }
  35751. function getPropertyOfVariable(symbol, name) {
  35752. if (symbol.flags & 3 /* Variable */) {
  35753. var typeAnnotation = symbol.valueDeclaration.type;
  35754. if (typeAnnotation) {
  35755. return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
  35756. }
  35757. }
  35758. }
  35759. function getExternalModuleMember(node, specifier, dontResolveAlias) {
  35760. if (dontResolveAlias === void 0) { dontResolveAlias = false; }
  35761. var _a;
  35762. var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
  35763. var name = specifier.propertyName || specifier.name;
  35764. var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
  35765. var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
  35766. if (targetSymbol) {
  35767. if (name.escapedText) {
  35768. if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
  35769. return moduleSymbol;
  35770. }
  35771. var symbolFromVariable = void 0;
  35772. // First check if module was specified with "export=". If so, get the member from the resolved type
  35773. if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
  35774. symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
  35775. }
  35776. else {
  35777. symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
  35778. }
  35779. // if symbolFromVariable is export - get its final target
  35780. symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
  35781. var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
  35782. if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
  35783. var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
  35784. if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
  35785. symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
  35786. }
  35787. }
  35788. var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
  35789. combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
  35790. symbolFromModule || symbolFromVariable;
  35791. if (!symbol) {
  35792. var moduleName = getFullyQualifiedName(moduleSymbol, node);
  35793. var declarationName = ts.declarationNameToString(name);
  35794. var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
  35795. if (suggestion !== undefined) {
  35796. var suggestionName = symbolToString(suggestion);
  35797. var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
  35798. if (suggestion.valueDeclaration) {
  35799. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
  35800. }
  35801. }
  35802. else {
  35803. if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
  35804. error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
  35805. }
  35806. else {
  35807. reportNonExportedMember(name, declarationName, moduleSymbol, moduleName);
  35808. }
  35809. }
  35810. }
  35811. return symbol;
  35812. }
  35813. }
  35814. }
  35815. function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) {
  35816. var _a;
  35817. var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
  35818. var exports = moduleSymbol.exports;
  35819. if (localSymbol) {
  35820. var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */)
  35821. ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); })
  35822. : undefined;
  35823. var diagnostic = exportedSymbol
  35824. ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol))
  35825. : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
  35826. ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
  35827. return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
  35828. })));
  35829. }
  35830. else {
  35831. error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
  35832. }
  35833. }
  35834. function getTargetOfImportSpecifier(node, dontResolveAlias) {
  35835. var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
  35836. markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
  35837. return resolved;
  35838. }
  35839. function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
  35840. var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
  35841. markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
  35842. return resolved;
  35843. }
  35844. function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
  35845. var resolved = node.parent.parent.moduleSpecifier ?
  35846. getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
  35847. resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
  35848. markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
  35849. return resolved;
  35850. }
  35851. function getTargetOfExportAssignment(node, dontResolveAlias) {
  35852. var expression = (ts.isExportAssignment(node) ? node.expression : node.right);
  35853. var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
  35854. markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
  35855. return resolved;
  35856. }
  35857. function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
  35858. if (ts.isClassExpression(expression)) {
  35859. return checkExpressionCached(expression).symbol;
  35860. }
  35861. if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
  35862. return undefined;
  35863. }
  35864. var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
  35865. if (aliasLike) {
  35866. return aliasLike;
  35867. }
  35868. checkExpressionCached(expression);
  35869. return getNodeLinks(expression).resolvedSymbol;
  35870. }
  35871. function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
  35872. var expression = node.initializer;
  35873. return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
  35874. }
  35875. function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
  35876. if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
  35877. return undefined;
  35878. }
  35879. return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
  35880. }
  35881. function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
  35882. if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
  35883. switch (node.kind) {
  35884. case 253 /* ImportEqualsDeclaration */:
  35885. return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
  35886. case 255 /* ImportClause */:
  35887. return getTargetOfImportClause(node, dontRecursivelyResolve);
  35888. case 256 /* NamespaceImport */:
  35889. return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
  35890. case 262 /* NamespaceExport */:
  35891. return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
  35892. case 258 /* ImportSpecifier */:
  35893. return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
  35894. case 263 /* ExportSpecifier */:
  35895. return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
  35896. case 259 /* ExportAssignment */:
  35897. case 209 /* BinaryExpression */:
  35898. return getTargetOfExportAssignment(node, dontRecursivelyResolve);
  35899. case 252 /* NamespaceExportDeclaration */:
  35900. return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
  35901. case 282 /* ShorthandPropertyAssignment */:
  35902. return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
  35903. case 281 /* PropertyAssignment */:
  35904. return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
  35905. case 194 /* PropertyAccessExpression */:
  35906. return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
  35907. default:
  35908. return ts.Debug.fail();
  35909. }
  35910. }
  35911. /**
  35912. * Indicates that a symbol is an alias that does not merge with a local declaration.
  35913. * OR Is a JSContainer which may merge an alias with a local declaration
  35914. */
  35915. function isNonLocalAlias(symbol, excludes) {
  35916. if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
  35917. if (!symbol)
  35918. return false;
  35919. return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
  35920. }
  35921. function resolveSymbol(symbol, dontResolveAlias) {
  35922. return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
  35923. }
  35924. function resolveAlias(symbol) {
  35925. ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
  35926. var links = getSymbolLinks(symbol);
  35927. if (!links.target) {
  35928. links.target = resolvingSymbol;
  35929. var node = getDeclarationOfAliasSymbol(symbol);
  35930. if (!node)
  35931. return ts.Debug.fail();
  35932. var target = getTargetOfAliasDeclaration(node);
  35933. if (links.target === resolvingSymbol) {
  35934. links.target = target || unknownSymbol;
  35935. }
  35936. else {
  35937. error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
  35938. }
  35939. }
  35940. else if (links.target === resolvingSymbol) {
  35941. links.target = unknownSymbol;
  35942. }
  35943. return links.target;
  35944. }
  35945. /**
  35946. * Marks a symbol as type-only if its declaration is syntactically type-only.
  35947. * If it is not itself marked type-only, but resolves to a type-only alias
  35948. * somewhere in its resolution chain, save a reference to the type-only alias declaration
  35949. * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
  35950. *
  35951. * This function is called on each alias declaration that could be type-only or resolve to
  35952. * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
  35953. * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
  35954. * and issue an error if so.
  35955. *
  35956. * @param aliasDeclaration The alias declaration not marked as type-only
  35957. * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
  35958. * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
  35959. * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
  35960. * must still be checked for a type-only marker, overwriting the previous negative result if found.
  35961. * @param immediateTarget The symbol to which the alias declaration immediately resolves
  35962. * @param finalTarget The symbol to which the alias declaration ultimately resolves
  35963. * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
  35964. */
  35965. function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
  35966. if (!aliasDeclaration)
  35967. return false;
  35968. // If the declaration itself is type-only, mark it and return.
  35969. // No need to check what it resolves to.
  35970. var sourceSymbol = getSymbolOfNode(aliasDeclaration);
  35971. if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
  35972. var links_1 = getSymbolLinks(sourceSymbol);
  35973. links_1.typeOnlyDeclaration = aliasDeclaration;
  35974. return true;
  35975. }
  35976. var links = getSymbolLinks(sourceSymbol);
  35977. return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
  35978. || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
  35979. }
  35980. function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
  35981. var _a, _b, _c;
  35982. if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
  35983. var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
  35984. var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
  35985. aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
  35986. }
  35987. return !!aliasDeclarationLinks.typeOnlyDeclaration;
  35988. }
  35989. /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
  35990. function getTypeOnlyAliasDeclaration(symbol) {
  35991. if (!(symbol.flags & 2097152 /* Alias */)) {
  35992. return undefined;
  35993. }
  35994. var links = getSymbolLinks(symbol);
  35995. return links.typeOnlyDeclaration || undefined;
  35996. }
  35997. function markExportAsReferenced(node) {
  35998. var symbol = getSymbolOfNode(node);
  35999. var target = resolveAlias(symbol);
  36000. if (target) {
  36001. var markAlias = target === unknownSymbol ||
  36002. ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
  36003. if (markAlias) {
  36004. markAliasSymbolAsReferenced(symbol);
  36005. }
  36006. }
  36007. }
  36008. // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
  36009. // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
  36010. // the alias as an expression (which recursively takes us back here if the target references another alias).
  36011. function markAliasSymbolAsReferenced(symbol) {
  36012. var links = getSymbolLinks(symbol);
  36013. if (!links.referenced) {
  36014. links.referenced = true;
  36015. var node = getDeclarationOfAliasSymbol(symbol);
  36016. if (!node)
  36017. return ts.Debug.fail();
  36018. // We defer checking of the reference of an `import =` until the import itself is referenced,
  36019. // This way a chain of imports can be elided if ultimately the final input is only used in a type
  36020. // position.
  36021. if (ts.isInternalModuleImportEqualsDeclaration(node)) {
  36022. var target = resolveSymbol(symbol);
  36023. if (target === unknownSymbol || target.flags & 111551 /* Value */) {
  36024. // import foo = <symbol>
  36025. checkExpressionCached(node.moduleReference);
  36026. }
  36027. }
  36028. }
  36029. }
  36030. // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
  36031. // but their usage in value positions must be tracked to determine if the import can be type-only.
  36032. function markConstEnumAliasAsReferenced(symbol) {
  36033. var links = getSymbolLinks(symbol);
  36034. if (!links.constEnumReferenced) {
  36035. links.constEnumReferenced = true;
  36036. }
  36037. }
  36038. // This function is only for imports with entity names
  36039. function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
  36040. // There are three things we might try to look for. In the following examples,
  36041. // the search term is enclosed in |...|:
  36042. //
  36043. // import a = |b|; // Namespace
  36044. // import a = |b.c|; // Value, type, namespace
  36045. // import a = |b.c|.d; // Namespace
  36046. if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
  36047. entityName = entityName.parent;
  36048. }
  36049. // Check for case 1 and 3 in the above example
  36050. if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
  36051. return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
  36052. }
  36053. else {
  36054. // Case 2 in above example
  36055. // entityName.kind could be a QualifiedName or a Missing identifier
  36056. ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
  36057. return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
  36058. }
  36059. }
  36060. function getFullyQualifiedName(symbol, containingLocation) {
  36061. return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
  36062. }
  36063. /**
  36064. * Resolves a qualified name and any involved aliases.
  36065. */
  36066. function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
  36067. if (ts.nodeIsMissing(name)) {
  36068. return undefined;
  36069. }
  36070. var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
  36071. var symbol;
  36072. if (name.kind === 75 /* Identifier */) {
  36073. var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
  36074. var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
  36075. symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true);
  36076. if (!symbol) {
  36077. return symbolFromJSPrototype;
  36078. }
  36079. }
  36080. else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
  36081. var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
  36082. var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
  36083. var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
  36084. if (!namespace || ts.nodeIsMissing(right)) {
  36085. return undefined;
  36086. }
  36087. else if (namespace === unknownSymbol) {
  36088. return namespace;
  36089. }
  36090. if (ts.isInJSFile(name)) {
  36091. if (namespace.valueDeclaration &&
  36092. ts.isVariableDeclaration(namespace.valueDeclaration) &&
  36093. namespace.valueDeclaration.initializer &&
  36094. isCommonJsRequire(namespace.valueDeclaration.initializer)) {
  36095. var moduleName = namespace.valueDeclaration.initializer.arguments[0];
  36096. var moduleSym = resolveExternalModuleName(moduleName, moduleName);
  36097. if (moduleSym) {
  36098. var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
  36099. if (resolvedModuleSymbol) {
  36100. namespace = resolvedModuleSymbol;
  36101. }
  36102. }
  36103. }
  36104. }
  36105. symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
  36106. if (!symbol) {
  36107. if (!ignoreErrors) {
  36108. error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
  36109. }
  36110. return undefined;
  36111. }
  36112. }
  36113. else {
  36114. throw ts.Debug.assertNever(name, "Unknown entity name kind.");
  36115. }
  36116. ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
  36117. if (ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
  36118. markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
  36119. }
  36120. return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
  36121. }
  36122. /**
  36123. * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
  36124. * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
  36125. * name resolution won't work either.
  36126. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
  36127. */
  36128. function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
  36129. if (isJSDocTypeReference(name.parent)) {
  36130. var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
  36131. if (secondaryLocation) {
  36132. return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
  36133. }
  36134. }
  36135. }
  36136. function getAssignmentDeclarationLocation(node) {
  36137. var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
  36138. if (typeAlias) {
  36139. return;
  36140. }
  36141. var host = ts.getJSDocHost(node);
  36142. if (ts.isExpressionStatement(host) &&
  36143. ts.isBinaryExpression(host.expression) &&
  36144. ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
  36145. // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
  36146. var symbol = getSymbolOfNode(host.expression.left);
  36147. if (symbol) {
  36148. return getDeclarationOfJSPrototypeContainer(symbol);
  36149. }
  36150. }
  36151. if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
  36152. ts.isBinaryExpression(host.parent.parent) &&
  36153. ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
  36154. // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
  36155. var symbol = getSymbolOfNode(host.parent.parent.left);
  36156. if (symbol) {
  36157. return getDeclarationOfJSPrototypeContainer(symbol);
  36158. }
  36159. }
  36160. var sig = ts.getHostSignatureFromJSDocHost(host);
  36161. if (sig) {
  36162. var symbol = getSymbolOfNode(sig);
  36163. return symbol && symbol.valueDeclaration;
  36164. }
  36165. }
  36166. function getDeclarationOfJSPrototypeContainer(symbol) {
  36167. var decl = symbol.parent.valueDeclaration;
  36168. if (!decl) {
  36169. return undefined;
  36170. }
  36171. var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
  36172. ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
  36173. undefined;
  36174. return initializer || decl;
  36175. }
  36176. /**
  36177. * Get the real symbol of a declaration with an expando initializer.
  36178. *
  36179. * Normally, declarations have an associated symbol, but when a declaration has an expando
  36180. * initializer, the expando's symbol is the one that has all the members merged into it.
  36181. */
  36182. function getExpandoSymbol(symbol) {
  36183. var decl = symbol.valueDeclaration;
  36184. if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
  36185. return undefined;
  36186. }
  36187. var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
  36188. if (init) {
  36189. var initSymbol = getSymbolOfNode(init);
  36190. if (initSymbol) {
  36191. return mergeJSSymbols(initSymbol, symbol);
  36192. }
  36193. }
  36194. }
  36195. function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
  36196. return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
  36197. }
  36198. function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
  36199. if (isForAugmentation === void 0) { isForAugmentation = false; }
  36200. return ts.isStringLiteralLike(moduleReferenceExpression)
  36201. ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
  36202. : undefined;
  36203. }
  36204. function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
  36205. if (isForAugmentation === void 0) { isForAugmentation = false; }
  36206. if (ts.startsWith(moduleReference, "@types/")) {
  36207. var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
  36208. var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
  36209. error(errorNode, diag, withoutAtTypePrefix, moduleReference);
  36210. }
  36211. var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
  36212. if (ambientModule) {
  36213. return ambientModule;
  36214. }
  36215. var currentSourceFile = ts.getSourceFileOfNode(location);
  36216. var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
  36217. var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
  36218. var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
  36219. if (sourceFile) {
  36220. if (sourceFile.symbol) {
  36221. if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
  36222. errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
  36223. }
  36224. // merged symbol is module declaration symbol combined with all augmentations
  36225. return getMergedSymbol(sourceFile.symbol);
  36226. }
  36227. if (moduleNotFoundError) {
  36228. // report errors only if it was requested
  36229. error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
  36230. }
  36231. return undefined;
  36232. }
  36233. if (patternAmbientModules) {
  36234. var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
  36235. if (pattern) {
  36236. // If the module reference matched a pattern ambient module ('*.foo') but there's also a
  36237. // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
  36238. // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
  36239. // from a.foo.
  36240. var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
  36241. if (augmentation) {
  36242. return getMergedSymbol(augmentation);
  36243. }
  36244. return getMergedSymbol(pattern.symbol);
  36245. }
  36246. }
  36247. // May be an untyped module. If so, ignore resolutionDiagnostic.
  36248. if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
  36249. if (isForAugmentation) {
  36250. var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
  36251. error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
  36252. }
  36253. else {
  36254. errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
  36255. }
  36256. // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
  36257. return undefined;
  36258. }
  36259. if (moduleNotFoundError) {
  36260. // See if this was possibly a projectReference redirect
  36261. if (resolvedModule) {
  36262. var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
  36263. if (redirect) {
  36264. error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
  36265. return undefined;
  36266. }
  36267. }
  36268. if (resolutionDiagnostic) {
  36269. error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
  36270. }
  36271. else {
  36272. var tsExtension = ts.tryExtractTSExtension(moduleReference);
  36273. if (tsExtension) {
  36274. var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
  36275. error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
  36276. }
  36277. else if (!compilerOptions.resolveJsonModule &&
  36278. ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
  36279. ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
  36280. ts.hasJsonModuleEmitEnabled(compilerOptions)) {
  36281. error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
  36282. }
  36283. else {
  36284. error(errorNode, moduleNotFoundError, moduleReference);
  36285. }
  36286. }
  36287. }
  36288. return undefined;
  36289. }
  36290. function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
  36291. var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
  36292. var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
  36293. ? typesPackageExists(packageId.name)
  36294. ? ts.chainDiagnosticMessages(
  36295. /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name))
  36296. : ts.chainDiagnosticMessages(
  36297. /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
  36298. : undefined;
  36299. errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
  36300. }
  36301. function typesPackageExists(packageName) {
  36302. return getPackagesSet().has(ts.getTypesPackageName(packageName));
  36303. }
  36304. function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
  36305. if (moduleSymbol) {
  36306. var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
  36307. var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
  36308. return getMergedSymbol(exported) || moduleSymbol;
  36309. }
  36310. return undefined;
  36311. }
  36312. function getCommonJsExportEquals(exported, moduleSymbol) {
  36313. if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
  36314. return exported;
  36315. }
  36316. var links = getSymbolLinks(exported);
  36317. if (links.cjsExportMerged) {
  36318. return links.cjsExportMerged;
  36319. }
  36320. var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
  36321. merged.flags = merged.flags | 512 /* ValueModule */;
  36322. if (merged.exports === undefined) {
  36323. merged.exports = ts.createSymbolTable();
  36324. }
  36325. moduleSymbol.exports.forEach(function (s, name) {
  36326. if (name === "export=" /* ExportEquals */)
  36327. return;
  36328. merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
  36329. });
  36330. getSymbolLinks(merged).cjsExportMerged = merged;
  36331. return links.cjsExportMerged = merged;
  36332. }
  36333. // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
  36334. // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
  36335. // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
  36336. function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
  36337. var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
  36338. if (!dontResolveAlias && symbol) {
  36339. if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
  36340. var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
  36341. ? "allowSyntheticDefaultImports"
  36342. : "esModuleInterop";
  36343. error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
  36344. return symbol;
  36345. }
  36346. if (compilerOptions.esModuleInterop) {
  36347. var referenceParent = referencingLocation.parent;
  36348. if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
  36349. ts.isImportCall(referenceParent)) {
  36350. var type = getTypeOfSymbol(symbol);
  36351. var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
  36352. if (!sigs || !sigs.length) {
  36353. sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
  36354. }
  36355. if (sigs && sigs.length) {
  36356. var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
  36357. // Create a new symbol which has the module's type less the call and construct signatures
  36358. var result = createSymbol(symbol.flags, symbol.escapedName);
  36359. result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
  36360. result.parent = symbol.parent;
  36361. result.target = symbol;
  36362. result.originatingImport = referenceParent;
  36363. if (symbol.valueDeclaration)
  36364. result.valueDeclaration = symbol.valueDeclaration;
  36365. if (symbol.constEnumOnlyModule)
  36366. result.constEnumOnlyModule = true;
  36367. if (symbol.members)
  36368. result.members = ts.cloneMap(symbol.members);
  36369. if (symbol.exports)
  36370. result.exports = ts.cloneMap(symbol.exports);
  36371. var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
  36372. result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
  36373. return result;
  36374. }
  36375. }
  36376. }
  36377. }
  36378. return symbol;
  36379. }
  36380. function hasExportAssignmentSymbol(moduleSymbol) {
  36381. return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
  36382. }
  36383. function getExportsOfModuleAsArray(moduleSymbol) {
  36384. return symbolsToArray(getExportsOfModule(moduleSymbol));
  36385. }
  36386. function getExportsAndPropertiesOfModule(moduleSymbol) {
  36387. var exports = getExportsOfModuleAsArray(moduleSymbol);
  36388. var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
  36389. if (exportEquals !== moduleSymbol) {
  36390. ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
  36391. }
  36392. return exports;
  36393. }
  36394. function tryGetMemberInModuleExports(memberName, moduleSymbol) {
  36395. var symbolTable = getExportsOfModule(moduleSymbol);
  36396. if (symbolTable) {
  36397. return symbolTable.get(memberName);
  36398. }
  36399. }
  36400. function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
  36401. var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
  36402. if (symbol) {
  36403. return symbol;
  36404. }
  36405. var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
  36406. if (exportEquals === moduleSymbol) {
  36407. return undefined;
  36408. }
  36409. var type = getTypeOfSymbol(exportEquals);
  36410. return type.flags & 131068 /* Primitive */ ||
  36411. ts.getObjectFlags(type) & 1 /* Class */ ||
  36412. isArrayOrTupleLikeType(type)
  36413. ? undefined
  36414. : getPropertyOfType(type, memberName);
  36415. }
  36416. function getExportsOfSymbol(symbol) {
  36417. return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
  36418. symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
  36419. symbol.exports || emptySymbols;
  36420. }
  36421. function getExportsOfModule(moduleSymbol) {
  36422. var links = getSymbolLinks(moduleSymbol);
  36423. return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
  36424. }
  36425. /**
  36426. * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
  36427. * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
  36428. */
  36429. function extendExportSymbols(target, source, lookupTable, exportNode) {
  36430. if (!source)
  36431. return;
  36432. source.forEach(function (sourceSymbol, id) {
  36433. if (id === "default" /* Default */)
  36434. return;
  36435. var targetSymbol = target.get(id);
  36436. if (!targetSymbol) {
  36437. target.set(id, sourceSymbol);
  36438. if (lookupTable && exportNode) {
  36439. lookupTable.set(id, {
  36440. specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
  36441. });
  36442. }
  36443. }
  36444. else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
  36445. var collisionTracker = lookupTable.get(id);
  36446. if (!collisionTracker.exportsWithDuplicate) {
  36447. collisionTracker.exportsWithDuplicate = [exportNode];
  36448. }
  36449. else {
  36450. collisionTracker.exportsWithDuplicate.push(exportNode);
  36451. }
  36452. }
  36453. });
  36454. }
  36455. function getExportsOfModuleWorker(moduleSymbol) {
  36456. var visitedSymbols = [];
  36457. // A module defined by an 'export=' consists of one export that needs to be resolved
  36458. moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
  36459. return visit(moduleSymbol) || emptySymbols;
  36460. // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
  36461. // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
  36462. function visit(symbol) {
  36463. if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
  36464. return;
  36465. }
  36466. var symbols = ts.cloneMap(symbol.exports);
  36467. // All export * declarations are collected in an __export symbol by the binder
  36468. var exportStars = symbol.exports.get("__export" /* ExportStar */);
  36469. if (exportStars) {
  36470. var nestedSymbols = ts.createSymbolTable();
  36471. var lookupTable_1 = ts.createMap();
  36472. for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
  36473. var node = _a[_i];
  36474. var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
  36475. var exportedSymbols = visit(resolvedModule);
  36476. extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
  36477. }
  36478. lookupTable_1.forEach(function (_a, id) {
  36479. var exportsWithDuplicate = _a.exportsWithDuplicate;
  36480. // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
  36481. if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
  36482. return;
  36483. }
  36484. for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
  36485. var node = exportsWithDuplicate_1[_i];
  36486. diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id)));
  36487. }
  36488. });
  36489. extendExportSymbols(symbols, nestedSymbols);
  36490. }
  36491. return symbols;
  36492. }
  36493. }
  36494. function getMergedSymbol(symbol) {
  36495. var merged;
  36496. return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
  36497. }
  36498. function getSymbolOfNode(node) {
  36499. return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
  36500. }
  36501. function getParentOfSymbol(symbol) {
  36502. return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
  36503. }
  36504. function getAlternativeContainingModules(symbol, enclosingDeclaration) {
  36505. var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
  36506. var id = "" + getNodeId(containingFile);
  36507. var links = getSymbolLinks(symbol);
  36508. var results;
  36509. if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
  36510. return results;
  36511. }
  36512. if (containingFile && containingFile.imports) {
  36513. // Try to make an import using an import already in the enclosing file, if possible
  36514. for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
  36515. var importRef = _a[_i];
  36516. if (ts.nodeIsSynthesized(importRef))
  36517. continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
  36518. var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
  36519. if (!resolvedModule)
  36520. continue;
  36521. var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
  36522. if (!ref)
  36523. continue;
  36524. results = ts.append(results, resolvedModule);
  36525. }
  36526. if (ts.length(results)) {
  36527. (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
  36528. return results;
  36529. }
  36530. }
  36531. if (links.extendedContainers) {
  36532. return links.extendedContainers;
  36533. }
  36534. // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
  36535. var otherFiles = host.getSourceFiles();
  36536. for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
  36537. var file = otherFiles_1[_b];
  36538. if (!ts.isExternalModule(file))
  36539. continue;
  36540. var sym = getSymbolOfNode(file);
  36541. var ref = getAliasForSymbolInContainer(sym, symbol);
  36542. if (!ref)
  36543. continue;
  36544. results = ts.append(results, sym);
  36545. }
  36546. return links.extendedContainers = results || ts.emptyArray;
  36547. }
  36548. /**
  36549. * Attempts to find the symbol corresponding to the container a symbol is in - usually this
  36550. * is just its' `.parent`, but for locals, this value is `undefined`
  36551. */
  36552. function getContainersOfSymbol(symbol, enclosingDeclaration) {
  36553. var container = getParentOfSymbol(symbol);
  36554. // Type parameters end up in the `members` lists but are not externally visible
  36555. if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
  36556. var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
  36557. var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
  36558. if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
  36559. return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
  36560. }
  36561. var res = ts.append(additionalContainers, container);
  36562. return ts.concatenate(res, reexportContainers);
  36563. }
  36564. var candidates = ts.mapDefined(symbol.declarations, function (d) {
  36565. if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
  36566. return getSymbolOfNode(d.parent);
  36567. }
  36568. if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
  36569. if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
  36570. return getSymbolOfNode(ts.getSourceFileOfNode(d));
  36571. }
  36572. checkExpressionCached(d.parent.left.expression);
  36573. return getNodeLinks(d.parent.left.expression).resolvedSymbol;
  36574. }
  36575. });
  36576. if (!ts.length(candidates)) {
  36577. return undefined;
  36578. }
  36579. return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
  36580. function fileSymbolIfFileSymbolExportEqualsContainer(d) {
  36581. var fileSymbol = getExternalModuleContainer(d);
  36582. var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
  36583. return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
  36584. }
  36585. }
  36586. function getAliasForSymbolInContainer(container, symbol) {
  36587. if (container === getParentOfSymbol(symbol)) {
  36588. // fast path, `symbol` is either already the alias or isn't aliased
  36589. return symbol;
  36590. }
  36591. // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
  36592. // the container itself as the alias for the symbol
  36593. var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
  36594. if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
  36595. return container;
  36596. }
  36597. var exports = getExportsOfSymbol(container);
  36598. var quick = exports.get(symbol.escapedName);
  36599. if (quick && getSymbolIfSameReference(quick, symbol)) {
  36600. return quick;
  36601. }
  36602. return ts.forEachEntry(exports, function (exported) {
  36603. if (getSymbolIfSameReference(exported, symbol)) {
  36604. return exported;
  36605. }
  36606. });
  36607. }
  36608. /**
  36609. * Checks if two symbols, through aliasing and/or merging, refer to the same thing
  36610. */
  36611. function getSymbolIfSameReference(s1, s2) {
  36612. if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
  36613. return s1;
  36614. }
  36615. }
  36616. function getExportSymbolOfValueSymbolIfExported(symbol) {
  36617. return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
  36618. }
  36619. function symbolIsValue(symbol) {
  36620. return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
  36621. }
  36622. function findConstructorDeclaration(node) {
  36623. var members = node.members;
  36624. for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
  36625. var member = members_3[_i];
  36626. if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
  36627. return member;
  36628. }
  36629. }
  36630. }
  36631. function createType(flags) {
  36632. var result = new Type(checker, flags);
  36633. typeCount++;
  36634. result.id = typeCount;
  36635. return result;
  36636. }
  36637. function createIntrinsicType(kind, intrinsicName, objectFlags) {
  36638. if (objectFlags === void 0) { objectFlags = 0; }
  36639. var type = createType(kind);
  36640. type.intrinsicName = intrinsicName;
  36641. type.objectFlags = objectFlags;
  36642. return type;
  36643. }
  36644. function createBooleanType(trueFalseTypes) {
  36645. var type = getUnionType(trueFalseTypes);
  36646. type.flags |= 16 /* Boolean */;
  36647. type.intrinsicName = "boolean";
  36648. return type;
  36649. }
  36650. function createObjectType(objectFlags, symbol) {
  36651. var type = createType(524288 /* Object */);
  36652. type.objectFlags = objectFlags;
  36653. type.symbol = symbol;
  36654. type.members = undefined;
  36655. type.properties = undefined;
  36656. type.callSignatures = undefined;
  36657. type.constructSignatures = undefined;
  36658. type.stringIndexInfo = undefined;
  36659. type.numberIndexInfo = undefined;
  36660. return type;
  36661. }
  36662. function createTypeofType() {
  36663. return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
  36664. }
  36665. function createTypeParameter(symbol) {
  36666. var type = createType(262144 /* TypeParameter */);
  36667. if (symbol)
  36668. type.symbol = symbol;
  36669. return type;
  36670. }
  36671. // A reserved member name starts with two underscores, but the third character cannot be an underscore,
  36672. // @, or #. A third underscore indicates an escaped form of an identifier that started
  36673. // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
  36674. // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
  36675. function isReservedMemberName(name) {
  36676. return name.charCodeAt(0) === 95 /* _ */ &&
  36677. name.charCodeAt(1) === 95 /* _ */ &&
  36678. name.charCodeAt(2) !== 95 /* _ */ &&
  36679. name.charCodeAt(2) !== 64 /* at */ &&
  36680. name.charCodeAt(2) !== 35 /* hash */;
  36681. }
  36682. function getNamedMembers(members) {
  36683. var result;
  36684. members.forEach(function (symbol, id) {
  36685. if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
  36686. (result || (result = [])).push(symbol);
  36687. }
  36688. });
  36689. return result || ts.emptyArray;
  36690. }
  36691. function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
  36692. type.members = members;
  36693. type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
  36694. type.callSignatures = callSignatures;
  36695. type.constructSignatures = constructSignatures;
  36696. type.stringIndexInfo = stringIndexInfo;
  36697. type.numberIndexInfo = numberIndexInfo;
  36698. return type;
  36699. }
  36700. function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
  36701. return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
  36702. }
  36703. function forEachSymbolTableInScope(enclosingDeclaration, callback) {
  36704. var result;
  36705. var _loop_6 = function (location) {
  36706. // Locals of a source file are not in scope (because they get merged into the global symbol table)
  36707. if (location.locals && !isGlobalSourceFile(location)) {
  36708. if (result = callback(location.locals)) {
  36709. return { value: result };
  36710. }
  36711. }
  36712. switch (location.kind) {
  36713. case 290 /* SourceFile */:
  36714. if (!ts.isExternalOrCommonJsModule(location)) {
  36715. break;
  36716. }
  36717. // falls through
  36718. case 249 /* ModuleDeclaration */:
  36719. var sym = getSymbolOfNode(location);
  36720. // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
  36721. // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
  36722. // to one another anyway)
  36723. if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
  36724. return { value: result };
  36725. }
  36726. break;
  36727. case 245 /* ClassDeclaration */:
  36728. case 214 /* ClassExpression */:
  36729. case 246 /* InterfaceDeclaration */:
  36730. // Type parameters are bound into `members` lists so they can merge across declarations
  36731. // This is troublesome, since in all other respects, they behave like locals :cries:
  36732. // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
  36733. // lookup logic in terms of `resolveName` would be nice
  36734. // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
  36735. // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
  36736. // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
  36737. var table_1;
  36738. // TODO: Should this filtered table be cached in some way?
  36739. (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
  36740. if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
  36741. (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
  36742. }
  36743. });
  36744. if (table_1 && (result = callback(table_1))) {
  36745. return { value: result };
  36746. }
  36747. break;
  36748. }
  36749. };
  36750. for (var location = enclosingDeclaration; location; location = location.parent) {
  36751. var state_2 = _loop_6(location);
  36752. if (typeof state_2 === "object")
  36753. return state_2.value;
  36754. }
  36755. return callback(globals);
  36756. }
  36757. function getQualifiedLeftMeaning(rightMeaning) {
  36758. // If we are looking in value space, the parent meaning is value, other wise it is namespace
  36759. return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
  36760. }
  36761. function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
  36762. if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
  36763. if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
  36764. return undefined;
  36765. }
  36766. var id = "" + getSymbolId(symbol);
  36767. var visitedSymbolTables = visitedSymbolTablesMap.get(id);
  36768. if (!visitedSymbolTables) {
  36769. visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
  36770. }
  36771. return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
  36772. /**
  36773. * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already)
  36774. */
  36775. function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
  36776. if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
  36777. return undefined;
  36778. }
  36779. var result = trySymbolTable(symbols, ignoreQualification);
  36780. visitedSymbolTables.pop();
  36781. return result;
  36782. }
  36783. function canQualifySymbol(symbolFromSymbolTable, meaning) {
  36784. // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
  36785. return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
  36786. // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
  36787. !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
  36788. }
  36789. function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
  36790. return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
  36791. // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
  36792. // and if symbolFromSymbolTable or alias resolution matches the symbol,
  36793. // check the symbol can be qualified, it is only then this symbol is accessible
  36794. !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
  36795. (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
  36796. }
  36797. function trySymbolTable(symbols, ignoreQualification) {
  36798. // If symbol is directly available by its name in the symbol table
  36799. if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
  36800. return [symbol];
  36801. }
  36802. // Check if symbol is any of the aliases in scope
  36803. var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
  36804. if (symbolFromSymbolTable.flags & 2097152 /* Alias */
  36805. && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
  36806. && symbolFromSymbolTable.escapedName !== "default" /* Default */
  36807. && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
  36808. // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
  36809. && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
  36810. // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
  36811. // See similar comment in `resolveName` for details
  36812. && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
  36813. var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
  36814. var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
  36815. if (candidate) {
  36816. return candidate;
  36817. }
  36818. }
  36819. if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
  36820. if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
  36821. return [symbol];
  36822. }
  36823. }
  36824. });
  36825. // If there's no result and we're looking at the global symbol table, treat `globalThis` like an alias and try to lookup thru that
  36826. return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
  36827. }
  36828. function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
  36829. if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
  36830. return [symbolFromSymbolTable];
  36831. }
  36832. // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
  36833. // but only if the symbolFromSymbolTable can be qualified
  36834. var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
  36835. var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
  36836. if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
  36837. return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
  36838. }
  36839. }
  36840. }
  36841. function needsQualification(symbol, enclosingDeclaration, meaning) {
  36842. var qualify = false;
  36843. forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
  36844. // If symbol of this name is not available in the symbol table we are ok
  36845. var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
  36846. if (!symbolFromSymbolTable) {
  36847. // Continue to the next symbol table
  36848. return false;
  36849. }
  36850. // If the symbol with this name is present it should refer to the symbol
  36851. if (symbolFromSymbolTable === symbol) {
  36852. // No need to qualify
  36853. return true;
  36854. }
  36855. // Qualify if the symbol from symbol table has same meaning as expected
  36856. symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
  36857. if (symbolFromSymbolTable.flags & meaning) {
  36858. qualify = true;
  36859. return true;
  36860. }
  36861. // Continue to the next symbol table
  36862. return false;
  36863. });
  36864. return qualify;
  36865. }
  36866. function isPropertyOrMethodDeclarationSymbol(symbol) {
  36867. if (symbol.declarations && symbol.declarations.length) {
  36868. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  36869. var declaration = _a[_i];
  36870. switch (declaration.kind) {
  36871. case 159 /* PropertyDeclaration */:
  36872. case 161 /* MethodDeclaration */:
  36873. case 163 /* GetAccessor */:
  36874. case 164 /* SetAccessor */:
  36875. continue;
  36876. default:
  36877. return false;
  36878. }
  36879. }
  36880. return true;
  36881. }
  36882. return false;
  36883. }
  36884. function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
  36885. var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
  36886. return access.accessibility === 0 /* Accessible */;
  36887. }
  36888. function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
  36889. var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
  36890. return access.accessibility === 0 /* Accessible */;
  36891. }
  36892. function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
  36893. if (!ts.length(symbols))
  36894. return;
  36895. var hadAccessibleChain;
  36896. var earlyModuleBail = false;
  36897. for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
  36898. var symbol = _a[_i];
  36899. // Symbol is accessible if it by itself is accessible
  36900. var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
  36901. if (accessibleSymbolChain) {
  36902. hadAccessibleChain = symbol;
  36903. var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
  36904. if (hasAccessibleDeclarations) {
  36905. return hasAccessibleDeclarations;
  36906. }
  36907. }
  36908. else {
  36909. if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
  36910. if (shouldComputeAliasesToMakeVisible) {
  36911. earlyModuleBail = true;
  36912. // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
  36913. // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
  36914. // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
  36915. // all other visibility options (in order to capture the possible aliases used to reference the module)
  36916. continue;
  36917. }
  36918. // Any meaning of a module symbol is always accessible via an `import` type
  36919. return {
  36920. accessibility: 0 /* Accessible */
  36921. };
  36922. }
  36923. }
  36924. // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
  36925. // It could be a qualified symbol and hence verify the path
  36926. // e.g.:
  36927. // module m {
  36928. // export class c {
  36929. // }
  36930. // }
  36931. // const x: typeof m.c
  36932. // In the above example when we start with checking if typeof m.c symbol is accessible,
  36933. // we are going to see if c can be accessed in scope directly.
  36934. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
  36935. // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
  36936. var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
  36937. // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
  36938. // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
  36939. // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
  36940. var firstDecl = ts.first(symbol.declarations);
  36941. if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
  36942. if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
  36943. containers = [getSymbolOfNode(firstDecl.parent)];
  36944. }
  36945. }
  36946. var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
  36947. if (parentResult) {
  36948. return parentResult;
  36949. }
  36950. }
  36951. if (earlyModuleBail) {
  36952. return {
  36953. accessibility: 0 /* Accessible */
  36954. };
  36955. }
  36956. if (hadAccessibleChain) {
  36957. return {
  36958. accessibility: 1 /* NotAccessible */,
  36959. errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
  36960. errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
  36961. };
  36962. }
  36963. }
  36964. /**
  36965. * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
  36966. *
  36967. * @param symbol a Symbol to check if accessible
  36968. * @param enclosingDeclaration a Node containing reference to the symbol
  36969. * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
  36970. * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
  36971. */
  36972. function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
  36973. if (symbol && enclosingDeclaration) {
  36974. var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
  36975. if (result) {
  36976. return result;
  36977. }
  36978. // This could be a symbol that is not exported in the external module
  36979. // or it could be a symbol from different external module that is not aliased and hence cannot be named
  36980. var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
  36981. if (symbolExternalModule) {
  36982. var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
  36983. if (symbolExternalModule !== enclosingExternalModule) {
  36984. // name from different external module that is not visible
  36985. return {
  36986. accessibility: 2 /* CannotBeNamed */,
  36987. errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
  36988. errorModuleName: symbolToString(symbolExternalModule)
  36989. };
  36990. }
  36991. }
  36992. // Just a local name that is not accessible
  36993. return {
  36994. accessibility: 1 /* NotAccessible */,
  36995. errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
  36996. };
  36997. }
  36998. return { accessibility: 0 /* Accessible */ };
  36999. }
  37000. function getExternalModuleContainer(declaration) {
  37001. var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
  37002. return node && getSymbolOfNode(node);
  37003. }
  37004. function hasExternalModuleSymbol(declaration) {
  37005. return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
  37006. }
  37007. function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
  37008. return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
  37009. }
  37010. function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
  37011. var aliasesToMakeVisible;
  37012. if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
  37013. return undefined;
  37014. }
  37015. return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
  37016. function getIsDeclarationVisible(declaration) {
  37017. if (!isDeclarationVisible(declaration)) {
  37018. // Mark the unexported alias as visible if its parent is visible
  37019. // because these kind of aliases can be used to name types in declaration file
  37020. var anyImportSyntax = getAnyImportSyntax(declaration);
  37021. if (anyImportSyntax &&
  37022. !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
  37023. isDeclarationVisible(anyImportSyntax.parent)) {
  37024. return addVisibleAlias(declaration, anyImportSyntax);
  37025. }
  37026. else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
  37027. !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
  37028. isDeclarationVisible(declaration.parent.parent.parent)) {
  37029. return addVisibleAlias(declaration, declaration.parent.parent);
  37030. }
  37031. else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
  37032. && !ts.hasModifier(declaration, 1 /* Export */)
  37033. && isDeclarationVisible(declaration.parent)) {
  37034. return addVisibleAlias(declaration, declaration);
  37035. }
  37036. // Declaration is not visible
  37037. return false;
  37038. }
  37039. return true;
  37040. }
  37041. function addVisibleAlias(declaration, aliasingStatement) {
  37042. // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
  37043. // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
  37044. // since we will do the emitting later in trackSymbol.
  37045. if (shouldComputeAliasToMakeVisible) {
  37046. getNodeLinks(declaration).isVisible = true;
  37047. aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
  37048. }
  37049. return true;
  37050. }
  37051. }
  37052. function isEntityNameVisible(entityName, enclosingDeclaration) {
  37053. // get symbol of the first identifier of the entityName
  37054. var meaning;
  37055. if (entityName.parent.kind === 172 /* TypeQuery */ ||
  37056. ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
  37057. entityName.parent.kind === 154 /* ComputedPropertyName */) {
  37058. // Typeof value
  37059. meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
  37060. }
  37061. else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
  37062. entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
  37063. // Left identifier from type reference or TypeAlias
  37064. // Entity name of the import declaration
  37065. meaning = 1920 /* Namespace */;
  37066. }
  37067. else {
  37068. // Type Reference or TypeAlias entity = Identifier
  37069. meaning = 788968 /* Type */;
  37070. }
  37071. var firstIdentifier = ts.getFirstIdentifier(entityName);
  37072. var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
  37073. // Verify if the symbol is accessible
  37074. return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
  37075. accessibility: 1 /* NotAccessible */,
  37076. errorSymbolName: ts.getTextOfNode(firstIdentifier),
  37077. errorNode: firstIdentifier
  37078. };
  37079. }
  37080. function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
  37081. if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
  37082. var nodeFlags = 70221824 /* IgnoreErrors */;
  37083. if (flags & 2 /* UseOnlyExternalAliasing */) {
  37084. nodeFlags |= 128 /* UseOnlyExternalAliasing */;
  37085. }
  37086. if (flags & 1 /* WriteTypeParametersOrArguments */) {
  37087. nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
  37088. }
  37089. if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
  37090. nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
  37091. }
  37092. if (flags & 16 /* DoNotIncludeSymbolChain */) {
  37093. nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
  37094. }
  37095. var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
  37096. return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
  37097. function symbolToStringWorker(writer) {
  37098. var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
  37099. var printer = ts.createPrinter({ removeComments: true });
  37100. var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
  37101. printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
  37102. return writer;
  37103. }
  37104. }
  37105. function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
  37106. if (flags === void 0) { flags = 0 /* None */; }
  37107. return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
  37108. function signatureToStringWorker(writer) {
  37109. var sigOutput;
  37110. if (flags & 262144 /* WriteArrowStyleSignature */) {
  37111. sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
  37112. }
  37113. else {
  37114. sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
  37115. }
  37116. var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
  37117. var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
  37118. var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
  37119. printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
  37120. return writer;
  37121. }
  37122. }
  37123. function typeToString(type, enclosingDeclaration, flags, writer) {
  37124. if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
  37125. if (writer === void 0) { writer = ts.createTextWriter(""); }
  37126. var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
  37127. var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
  37128. if (typeNode === undefined)
  37129. return ts.Debug.fail("should always get typenode");
  37130. var options = { removeComments: true };
  37131. var printer = ts.createPrinter(options);
  37132. var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
  37133. printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
  37134. var result = writer.getText();
  37135. var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2;
  37136. if (maxLength && result && result.length >= maxLength) {
  37137. return result.substr(0, maxLength - "...".length) + "...";
  37138. }
  37139. return result;
  37140. }
  37141. function getTypeNamesForErrorDisplay(left, right) {
  37142. var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
  37143. var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
  37144. if (leftStr === rightStr) {
  37145. leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
  37146. rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
  37147. }
  37148. return [leftStr, rightStr];
  37149. }
  37150. function symbolValueDeclarationIsContextSensitive(symbol) {
  37151. return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
  37152. }
  37153. function toNodeBuilderFlags(flags) {
  37154. if (flags === void 0) { flags = 0 /* None */; }
  37155. return flags & 277904747 /* NodeBuilderFlagsMask */;
  37156. }
  37157. function createNodeBuilder() {
  37158. return {
  37159. typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
  37160. return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
  37161. },
  37162. indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
  37163. return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
  37164. },
  37165. signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
  37166. return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
  37167. },
  37168. symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
  37169. return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
  37170. },
  37171. symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
  37172. return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
  37173. },
  37174. symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
  37175. return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
  37176. },
  37177. symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
  37178. return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
  37179. },
  37180. typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
  37181. return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
  37182. },
  37183. symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
  37184. return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
  37185. },
  37186. };
  37187. function withContext(enclosingDeclaration, flags, tracker, cb) {
  37188. ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
  37189. var context = {
  37190. enclosingDeclaration: enclosingDeclaration,
  37191. flags: flags || 0 /* None */,
  37192. // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
  37193. tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
  37194. getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
  37195. getSourceFiles: function () { return host.getSourceFiles(); },
  37196. getCurrentDirectory: ts.maybeBind(host, host.getCurrentDirectory),
  37197. getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
  37198. } : undefined },
  37199. encounteredError: false,
  37200. visitedTypes: undefined,
  37201. symbolDepth: undefined,
  37202. inferTypeParameters: undefined,
  37203. approximateLength: 0
  37204. };
  37205. var resultingNode = cb(context);
  37206. return context.encounteredError ? undefined : resultingNode;
  37207. }
  37208. function checkTruncationLength(context) {
  37209. if (context.truncating)
  37210. return context.truncating;
  37211. return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength;
  37212. }
  37213. function typeToTypeNodeHelper(type, context) {
  37214. if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
  37215. cancellationToken.throwIfCancellationRequested();
  37216. }
  37217. var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
  37218. context.flags &= ~8388608 /* InTypeAlias */;
  37219. if (!type) {
  37220. context.encounteredError = true;
  37221. return undefined; // TODO: GH#18217
  37222. }
  37223. if (type.flags & 1 /* Any */) {
  37224. context.approximateLength += 3;
  37225. return ts.createKeywordTypeNode(125 /* AnyKeyword */);
  37226. }
  37227. if (type.flags & 2 /* Unknown */) {
  37228. return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
  37229. }
  37230. if (type.flags & 4 /* String */) {
  37231. context.approximateLength += 6;
  37232. return ts.createKeywordTypeNode(143 /* StringKeyword */);
  37233. }
  37234. if (type.flags & 8 /* Number */) {
  37235. context.approximateLength += 6;
  37236. return ts.createKeywordTypeNode(140 /* NumberKeyword */);
  37237. }
  37238. if (type.flags & 64 /* BigInt */) {
  37239. context.approximateLength += 6;
  37240. return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
  37241. }
  37242. if (type.flags & 16 /* Boolean */) {
  37243. context.approximateLength += 7;
  37244. return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
  37245. }
  37246. if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
  37247. var parentSymbol = getParentOfSymbol(type.symbol);
  37248. var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
  37249. var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
  37250. ? parentName
  37251. : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
  37252. return enumLiteralName;
  37253. }
  37254. if (type.flags & 1056 /* EnumLike */) {
  37255. return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
  37256. }
  37257. if (type.flags & 128 /* StringLiteral */) {
  37258. context.approximateLength += (type.value.length + 2);
  37259. return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
  37260. }
  37261. if (type.flags & 256 /* NumberLiteral */) {
  37262. var value = type.value;
  37263. context.approximateLength += ("" + value).length;
  37264. return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
  37265. }
  37266. if (type.flags & 2048 /* BigIntLiteral */) {
  37267. context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
  37268. return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
  37269. }
  37270. if (type.flags & 512 /* BooleanLiteral */) {
  37271. context.approximateLength += type.intrinsicName.length;
  37272. return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
  37273. }
  37274. if (type.flags & 8192 /* UniqueESSymbol */) {
  37275. if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
  37276. if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
  37277. context.approximateLength += 6;
  37278. return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
  37279. }
  37280. if (context.tracker.reportInaccessibleUniqueSymbolError) {
  37281. context.tracker.reportInaccessibleUniqueSymbolError();
  37282. }
  37283. }
  37284. context.approximateLength += 13;
  37285. return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
  37286. }
  37287. if (type.flags & 16384 /* Void */) {
  37288. context.approximateLength += 4;
  37289. return ts.createKeywordTypeNode(110 /* VoidKeyword */);
  37290. }
  37291. if (type.flags & 32768 /* Undefined */) {
  37292. context.approximateLength += 9;
  37293. return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
  37294. }
  37295. if (type.flags & 65536 /* Null */) {
  37296. context.approximateLength += 4;
  37297. return ts.createKeywordTypeNode(100 /* NullKeyword */);
  37298. }
  37299. if (type.flags & 131072 /* Never */) {
  37300. context.approximateLength += 5;
  37301. return ts.createKeywordTypeNode(137 /* NeverKeyword */);
  37302. }
  37303. if (type.flags & 4096 /* ESSymbol */) {
  37304. context.approximateLength += 6;
  37305. return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
  37306. }
  37307. if (type.flags & 67108864 /* NonPrimitive */) {
  37308. context.approximateLength += 6;
  37309. return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
  37310. }
  37311. if (isThisTypeParameter(type)) {
  37312. if (context.flags & 4194304 /* InObjectTypeLiteral */) {
  37313. if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
  37314. context.encounteredError = true;
  37315. }
  37316. if (context.tracker.reportInaccessibleThisError) {
  37317. context.tracker.reportInaccessibleThisError();
  37318. }
  37319. }
  37320. context.approximateLength += 4;
  37321. return ts.createThis();
  37322. }
  37323. if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
  37324. var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
  37325. if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
  37326. return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
  37327. return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
  37328. }
  37329. var objectFlags = ts.getObjectFlags(type);
  37330. if (objectFlags & 4 /* Reference */) {
  37331. ts.Debug.assert(!!(type.flags & 524288 /* Object */));
  37332. return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
  37333. }
  37334. if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
  37335. if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
  37336. context.approximateLength += (ts.symbolName(type.symbol).length + 6);
  37337. return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
  37338. }
  37339. if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
  37340. type.flags & 262144 /* TypeParameter */ &&
  37341. !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
  37342. var name = typeParameterToName(type, context);
  37343. context.approximateLength += ts.idText(name).length;
  37344. return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
  37345. }
  37346. // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
  37347. return type.symbol
  37348. ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
  37349. : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
  37350. }
  37351. if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
  37352. var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
  37353. if (ts.length(types) === 1) {
  37354. return typeToTypeNodeHelper(types[0], context);
  37355. }
  37356. var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
  37357. if (typeNodes && typeNodes.length > 0) {
  37358. var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
  37359. return unionOrIntersectionTypeNode;
  37360. }
  37361. else {
  37362. if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
  37363. context.encounteredError = true;
  37364. }
  37365. return undefined; // TODO: GH#18217
  37366. }
  37367. }
  37368. if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
  37369. ts.Debug.assert(!!(type.flags & 524288 /* Object */));
  37370. // The type is an object literal type.
  37371. return createAnonymousTypeNode(type);
  37372. }
  37373. if (type.flags & 4194304 /* Index */) {
  37374. var indexedType = type.type;
  37375. context.approximateLength += 6;
  37376. var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
  37377. return ts.createTypeOperatorNode(indexTypeNode);
  37378. }
  37379. if (type.flags & 8388608 /* IndexedAccess */) {
  37380. var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
  37381. var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
  37382. context.approximateLength += 2;
  37383. return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
  37384. }
  37385. if (type.flags & 16777216 /* Conditional */) {
  37386. var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
  37387. var saveInferTypeParameters = context.inferTypeParameters;
  37388. context.inferTypeParameters = type.root.inferTypeParameters;
  37389. var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
  37390. context.inferTypeParameters = saveInferTypeParameters;
  37391. var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
  37392. var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
  37393. context.approximateLength += 15;
  37394. return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
  37395. }
  37396. if (type.flags & 33554432 /* Substitution */) {
  37397. return typeToTypeNodeHelper(type.typeVariable, context);
  37398. }
  37399. return ts.Debug.fail("Should be unreachable.");
  37400. function createMappedTypeNodeFromType(type) {
  37401. ts.Debug.assert(!!(type.flags & 524288 /* Object */));
  37402. var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
  37403. var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
  37404. var appropriateConstraintTypeNode;
  37405. if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
  37406. // We have a { [P in keyof T]: X }
  37407. // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
  37408. appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
  37409. }
  37410. else {
  37411. appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
  37412. }
  37413. var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
  37414. var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
  37415. var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
  37416. context.approximateLength += 10;
  37417. return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
  37418. }
  37419. function createAnonymousTypeNode(type) {
  37420. var typeId = "" + type.id;
  37421. var symbol = type.symbol;
  37422. if (symbol) {
  37423. if (isJSConstructor(symbol.valueDeclaration)) {
  37424. // Instance and static types share the same symbol; only add 'typeof' for the static side.
  37425. var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
  37426. return symbolToTypeNode(symbol, context, isInstanceType);
  37427. }
  37428. // Always use 'typeof T' for type of class, enum, and module objects
  37429. else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
  37430. symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
  37431. shouldWriteTypeOfFunctionSymbol()) {
  37432. return symbolToTypeNode(symbol, context, 111551 /* Value */);
  37433. }
  37434. else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
  37435. // If type is an anonymous type literal in a type alias declaration, use type alias name
  37436. var typeAlias = getTypeAliasForTypeLiteral(type);
  37437. if (typeAlias) {
  37438. // The specified symbol flags need to be reinterpreted as type flags
  37439. return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
  37440. }
  37441. else {
  37442. return createElidedInformationPlaceholder(context);
  37443. }
  37444. }
  37445. else {
  37446. return visitAndTransformType(type, createTypeNodeFromObjectType);
  37447. }
  37448. }
  37449. else {
  37450. // Anonymous types without a symbol are never circular.
  37451. return createTypeNodeFromObjectType(type);
  37452. }
  37453. function shouldWriteTypeOfFunctionSymbol() {
  37454. var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
  37455. ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
  37456. var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
  37457. (symbol.parent || // is exported function symbol
  37458. ts.forEach(symbol.declarations, function (declaration) {
  37459. return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
  37460. }));
  37461. if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
  37462. // typeof is allowed only for static/non local functions
  37463. return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
  37464. (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed
  37465. }
  37466. }
  37467. }
  37468. function visitAndTransformType(type, transform) {
  37469. var typeId = "" + type.id;
  37470. var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
  37471. var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
  37472. type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
  37473. undefined;
  37474. // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
  37475. // of types allows us to catch circular references to instantiations of the same anonymous type
  37476. if (!context.visitedTypes) {
  37477. context.visitedTypes = ts.createMap();
  37478. }
  37479. if (id && !context.symbolDepth) {
  37480. context.symbolDepth = ts.createMap();
  37481. }
  37482. var depth;
  37483. if (id) {
  37484. depth = context.symbolDepth.get(id) || 0;
  37485. if (depth > 10) {
  37486. return createElidedInformationPlaceholder(context);
  37487. }
  37488. context.symbolDepth.set(id, depth + 1);
  37489. }
  37490. context.visitedTypes.set(typeId, true);
  37491. var result = transform(type);
  37492. context.visitedTypes.delete(typeId);
  37493. if (id) {
  37494. context.symbolDepth.set(id, depth);
  37495. }
  37496. return result;
  37497. }
  37498. function createTypeNodeFromObjectType(type) {
  37499. if (isGenericMappedType(type)) {
  37500. return createMappedTypeNodeFromType(type);
  37501. }
  37502. var resolved = resolveStructuredTypeMembers(type);
  37503. if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
  37504. if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
  37505. context.approximateLength += 2;
  37506. return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
  37507. }
  37508. if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
  37509. var signature = resolved.callSignatures[0];
  37510. var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
  37511. return signatureNode;
  37512. }
  37513. if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
  37514. var signature = resolved.constructSignatures[0];
  37515. var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
  37516. return signatureNode;
  37517. }
  37518. }
  37519. var savedFlags = context.flags;
  37520. context.flags |= 4194304 /* InObjectTypeLiteral */;
  37521. var members = createTypeNodesFromResolvedType(resolved);
  37522. context.flags = savedFlags;
  37523. var typeLiteralNode = ts.createTypeLiteralNode(members);
  37524. context.approximateLength += 2;
  37525. return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
  37526. }
  37527. function typeReferenceToTypeNode(type) {
  37528. var typeArguments = getTypeArguments(type);
  37529. if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
  37530. if (context.flags & 2 /* WriteArrayAsGenericType */) {
  37531. var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
  37532. return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
  37533. }
  37534. var elementType = typeToTypeNodeHelper(typeArguments[0], context);
  37535. var arrayType = ts.createArrayTypeNode(elementType);
  37536. return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
  37537. }
  37538. else if (type.target.objectFlags & 8 /* Tuple */) {
  37539. if (typeArguments.length > 0) {
  37540. var arity = getTypeReferenceArity(type);
  37541. var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
  37542. var hasRestElement = type.target.hasRestElement;
  37543. if (tupleConstituentNodes) {
  37544. for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
  37545. tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
  37546. ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
  37547. ts.createOptionalTypeNode(tupleConstituentNodes[i]);
  37548. }
  37549. var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
  37550. return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
  37551. }
  37552. }
  37553. if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
  37554. var tupleTypeNode = ts.createTupleTypeNode([]);
  37555. return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
  37556. }
  37557. context.encounteredError = true;
  37558. return undefined; // TODO: GH#18217
  37559. }
  37560. else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
  37561. type.symbol.valueDeclaration &&
  37562. ts.isClassLike(type.symbol.valueDeclaration) &&
  37563. !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
  37564. return createAnonymousTypeNode(type);
  37565. }
  37566. else {
  37567. var outerTypeParameters = type.target.outerTypeParameters;
  37568. var i = 0;
  37569. var resultType = void 0;
  37570. if (outerTypeParameters) {
  37571. var length_1 = outerTypeParameters.length;
  37572. while (i < length_1) {
  37573. // Find group of type arguments for type parameters with the same declaring container.
  37574. var start = i;
  37575. var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
  37576. do {
  37577. i++;
  37578. } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
  37579. // When type parameters are their own type arguments for the whole group (i.e. we have
  37580. // the default outer type arguments), we don't show the group.
  37581. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
  37582. var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
  37583. var flags_2 = context.flags;
  37584. context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
  37585. var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
  37586. context.flags = flags_2;
  37587. resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
  37588. }
  37589. }
  37590. }
  37591. var typeArgumentNodes = void 0;
  37592. if (typeArguments.length > 0) {
  37593. var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
  37594. typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
  37595. }
  37596. var flags = context.flags;
  37597. context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
  37598. var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
  37599. context.flags = flags;
  37600. return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
  37601. }
  37602. }
  37603. function appendReferenceToType(root, ref) {
  37604. if (ts.isImportTypeNode(root)) {
  37605. // first shift type arguments
  37606. var innerParams = root.typeArguments;
  37607. if (root.qualifier) {
  37608. (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
  37609. }
  37610. root.typeArguments = ref.typeArguments;
  37611. // then move qualifiers
  37612. var ids = getAccessStack(ref);
  37613. for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
  37614. var id = ids_1[_i];
  37615. root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
  37616. }
  37617. return root;
  37618. }
  37619. else {
  37620. // first shift type arguments
  37621. var innerParams = root.typeArguments;
  37622. (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
  37623. root.typeArguments = ref.typeArguments;
  37624. // then move qualifiers
  37625. var ids = getAccessStack(ref);
  37626. for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
  37627. var id = ids_2[_a];
  37628. root.typeName = ts.createQualifiedName(root.typeName, id);
  37629. }
  37630. return root;
  37631. }
  37632. }
  37633. function getAccessStack(ref) {
  37634. var state = ref.typeName;
  37635. var ids = [];
  37636. while (!ts.isIdentifier(state)) {
  37637. ids.unshift(state.right);
  37638. state = state.left;
  37639. }
  37640. ids.unshift(state);
  37641. return ids;
  37642. }
  37643. function createTypeNodesFromResolvedType(resolvedType) {
  37644. if (checkTruncationLength(context)) {
  37645. return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
  37646. }
  37647. var typeElements = [];
  37648. for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
  37649. var signature = _a[_i];
  37650. typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
  37651. }
  37652. for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
  37653. var signature = _c[_b];
  37654. typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
  37655. }
  37656. if (resolvedType.stringIndexInfo) {
  37657. var indexSignature = void 0;
  37658. if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
  37659. indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
  37660. indexSignature.type = createElidedInformationPlaceholder(context);
  37661. }
  37662. else {
  37663. indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
  37664. }
  37665. typeElements.push(indexSignature);
  37666. }
  37667. if (resolvedType.numberIndexInfo) {
  37668. typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
  37669. }
  37670. var properties = resolvedType.properties;
  37671. if (!properties) {
  37672. return typeElements;
  37673. }
  37674. var i = 0;
  37675. for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
  37676. var propertySymbol = properties_1[_d];
  37677. i++;
  37678. if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
  37679. if (propertySymbol.flags & 4194304 /* Prototype */) {
  37680. continue;
  37681. }
  37682. if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
  37683. context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
  37684. }
  37685. }
  37686. if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
  37687. typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
  37688. addPropertyToElementList(properties[properties.length - 1], context, typeElements);
  37689. break;
  37690. }
  37691. addPropertyToElementList(propertySymbol, context, typeElements);
  37692. }
  37693. return typeElements.length ? typeElements : undefined;
  37694. }
  37695. }
  37696. function createElidedInformationPlaceholder(context) {
  37697. context.approximateLength += 3;
  37698. if (!(context.flags & 1 /* NoTruncation */)) {
  37699. return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
  37700. }
  37701. return ts.createKeywordTypeNode(125 /* AnyKeyword */);
  37702. }
  37703. function addPropertyToElementList(propertySymbol, context, typeElements) {
  37704. var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
  37705. var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
  37706. anyType : getTypeOfSymbol(propertySymbol);
  37707. var saveEnclosingDeclaration = context.enclosingDeclaration;
  37708. context.enclosingDeclaration = undefined;
  37709. if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
  37710. var decl = ts.first(propertySymbol.declarations);
  37711. if (hasLateBindableName(decl)) {
  37712. if (ts.isBinaryExpression(decl)) {
  37713. var name = ts.getNameOfDeclaration(decl);
  37714. if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
  37715. trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
  37716. }
  37717. }
  37718. else {
  37719. trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
  37720. }
  37721. }
  37722. }
  37723. context.enclosingDeclaration = saveEnclosingDeclaration;
  37724. var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
  37725. context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
  37726. var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
  37727. if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
  37728. var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
  37729. for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
  37730. var signature = signatures_1[_i];
  37731. var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
  37732. methodDeclaration.name = propertyName;
  37733. methodDeclaration.questionToken = optionalToken;
  37734. typeElements.push(preserveCommentsOn(methodDeclaration));
  37735. }
  37736. }
  37737. else {
  37738. var savedFlags = context.flags;
  37739. context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
  37740. var propertyTypeNode = void 0;
  37741. if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
  37742. propertyTypeNode = createElidedInformationPlaceholder(context);
  37743. }
  37744. else {
  37745. propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
  37746. }
  37747. context.flags = savedFlags;
  37748. var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
  37749. if (modifiers) {
  37750. context.approximateLength += 9;
  37751. }
  37752. var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode,
  37753. /*initializer*/ undefined);
  37754. typeElements.push(preserveCommentsOn(propertySignature));
  37755. }
  37756. function preserveCommentsOn(node) {
  37757. if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 322 /* JSDocPropertyTag */; })) {
  37758. var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 322 /* JSDocPropertyTag */; });
  37759. var commentText = d.comment;
  37760. if (commentText) {
  37761. ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
  37762. }
  37763. }
  37764. else if (propertySymbol.valueDeclaration) {
  37765. // Copy comments to node for declaration emit
  37766. ts.setCommentRange(node, propertySymbol.valueDeclaration);
  37767. }
  37768. return node;
  37769. }
  37770. }
  37771. function mapToTypeNodes(types, context, isBareList) {
  37772. if (ts.some(types)) {
  37773. if (checkTruncationLength(context)) {
  37774. if (!isBareList) {
  37775. return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
  37776. }
  37777. else if (types.length > 2) {
  37778. return [
  37779. typeToTypeNodeHelper(types[0], context),
  37780. ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
  37781. typeToTypeNodeHelper(types[types.length - 1], context)
  37782. ];
  37783. }
  37784. }
  37785. var result = [];
  37786. var i = 0;
  37787. for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
  37788. var type = types_1[_i];
  37789. i++;
  37790. if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
  37791. result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
  37792. var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
  37793. if (typeNode_1) {
  37794. result.push(typeNode_1);
  37795. }
  37796. break;
  37797. }
  37798. context.approximateLength += 2; // Account for whitespace + separator
  37799. var typeNode = typeToTypeNodeHelper(type, context);
  37800. if (typeNode) {
  37801. result.push(typeNode);
  37802. }
  37803. }
  37804. return result;
  37805. }
  37806. }
  37807. function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
  37808. var name = ts.getNameFromIndexInfo(indexInfo) || "x";
  37809. var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
  37810. var indexingParameter = ts.createParameter(
  37811. /*decorators*/ undefined,
  37812. /*modifiers*/ undefined,
  37813. /*dotDotDotToken*/ undefined, name,
  37814. /*questionToken*/ undefined, indexerTypeNode,
  37815. /*initializer*/ undefined);
  37816. var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
  37817. if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
  37818. context.encounteredError = true;
  37819. }
  37820. context.approximateLength += (name.length + 4);
  37821. return ts.createIndexSignature(
  37822. /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
  37823. }
  37824. function signatureToSignatureDeclarationHelper(signature, kind, context) {
  37825. var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
  37826. if (suppressAny)
  37827. context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
  37828. var typeParameters;
  37829. var typeArguments;
  37830. if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
  37831. typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
  37832. }
  37833. else {
  37834. typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
  37835. }
  37836. var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); });
  37837. if (signature.thisParameter) {
  37838. var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
  37839. parameters.unshift(thisParameter);
  37840. }
  37841. var returnTypeNode;
  37842. var typePredicate = getTypePredicateOfSignature(signature);
  37843. if (typePredicate) {
  37844. var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
  37845. ts.createToken(124 /* AssertsKeyword */) :
  37846. undefined;
  37847. var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
  37848. ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
  37849. ts.createThisTypeNode();
  37850. var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
  37851. returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
  37852. }
  37853. else {
  37854. var returnType = getReturnTypeOfSignature(signature);
  37855. if (returnType && !(suppressAny && isTypeAny(returnType))) {
  37856. returnTypeNode = typeToTypeNodeHelper(returnType, context);
  37857. }
  37858. else if (!suppressAny) {
  37859. returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
  37860. }
  37861. }
  37862. context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
  37863. return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
  37864. }
  37865. function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
  37866. var savedContextFlags = context.flags;
  37867. context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
  37868. var name = typeParameterToName(type, context);
  37869. var defaultParameter = getDefaultFromTypeParameter(type);
  37870. var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
  37871. context.flags = savedContextFlags;
  37872. return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
  37873. }
  37874. function typeParameterToDeclaration(type, context, constraint) {
  37875. if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
  37876. var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
  37877. return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
  37878. }
  37879. function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
  37880. var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
  37881. if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
  37882. parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 316 /* JSDocParameterTag */);
  37883. }
  37884. var parameterType = getTypeOfSymbol(parameterSymbol);
  37885. if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
  37886. parameterType = getOptionalType(parameterType);
  37887. }
  37888. var parameterTypeNode = typeToTypeNodeHelper(parameterType, context);
  37889. var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
  37890. var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
  37891. var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
  37892. var name = parameterDeclaration ? parameterDeclaration.name ?
  37893. parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
  37894. parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
  37895. cloneBindingName(parameterDeclaration.name) :
  37896. ts.symbolName(parameterSymbol) :
  37897. ts.symbolName(parameterSymbol);
  37898. var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
  37899. var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
  37900. var parameterNode = ts.createParameter(
  37901. /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode,
  37902. /*initializer*/ undefined);
  37903. context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
  37904. return parameterNode;
  37905. function cloneBindingName(node) {
  37906. return elideInitializerAndSetEmitFlags(node);
  37907. function elideInitializerAndSetEmitFlags(node) {
  37908. if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
  37909. trackComputedName(node.expression, context.enclosingDeclaration, context);
  37910. }
  37911. var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
  37912. var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
  37913. if (clone.kind === 191 /* BindingElement */) {
  37914. clone.initializer = undefined;
  37915. }
  37916. return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
  37917. }
  37918. }
  37919. }
  37920. function trackComputedName(accessExpression, enclosingDeclaration, context) {
  37921. if (!context.tracker.trackSymbol)
  37922. return;
  37923. // get symbol of the first identifier of the entityName
  37924. var firstIdentifier = ts.getFirstIdentifier(accessExpression);
  37925. var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
  37926. if (name) {
  37927. context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
  37928. }
  37929. }
  37930. function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
  37931. context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
  37932. return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
  37933. }
  37934. function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
  37935. // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
  37936. var chain;
  37937. var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
  37938. if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
  37939. chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
  37940. ts.Debug.assert(chain && chain.length > 0);
  37941. }
  37942. else {
  37943. chain = [symbol];
  37944. }
  37945. return chain;
  37946. /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
  37947. function getSymbolChain(symbol, meaning, endOfChain) {
  37948. var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
  37949. var parentSpecifiers;
  37950. if (!accessibleSymbolChain ||
  37951. needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
  37952. // Go up and add our parent.
  37953. var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
  37954. if (ts.length(parents_1)) {
  37955. parentSpecifiers = parents_1.map(function (symbol) {
  37956. return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
  37957. ? getSpecifierForModuleSymbol(symbol, context)
  37958. : undefined;
  37959. });
  37960. var indices = parents_1.map(function (_, i) { return i; });
  37961. indices.sort(sortByBestName);
  37962. var sortedParents = indices.map(function (i) { return parents_1[i]; });
  37963. for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
  37964. var parent = sortedParents_1[_i];
  37965. var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
  37966. if (parentChain) {
  37967. if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
  37968. getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
  37969. // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
  37970. // No need to lookup an alias for the symbol in itself
  37971. accessibleSymbolChain = parentChain;
  37972. break;
  37973. }
  37974. accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
  37975. break;
  37976. }
  37977. }
  37978. }
  37979. }
  37980. if (accessibleSymbolChain) {
  37981. return accessibleSymbolChain;
  37982. }
  37983. if (
  37984. // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
  37985. endOfChain ||
  37986. // If a parent symbol is an anonymous type, don't write it.
  37987. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
  37988. // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
  37989. if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
  37990. return;
  37991. }
  37992. return [symbol];
  37993. }
  37994. function sortByBestName(a, b) {
  37995. var specifierA = parentSpecifiers[a];
  37996. var specifierB = parentSpecifiers[b];
  37997. if (specifierA && specifierB) {
  37998. var isBRelative = ts.pathIsRelative(specifierB);
  37999. if (ts.pathIsRelative(specifierA) === isBRelative) {
  38000. // Both relative or both non-relative, sort by number of parts
  38001. return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
  38002. }
  38003. if (isBRelative) {
  38004. // A is non-relative, B is relative: prefer A
  38005. return -1;
  38006. }
  38007. // A is relative, B is non-relative: prefer B
  38008. return 1;
  38009. }
  38010. return 0;
  38011. }
  38012. }
  38013. }
  38014. function typeParametersToTypeParameterDeclarations(symbol, context) {
  38015. var typeParameterNodes;
  38016. var targetSymbol = getTargetSymbol(symbol);
  38017. if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
  38018. typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
  38019. }
  38020. return typeParameterNodes;
  38021. }
  38022. function lookupTypeParameterNodes(chain, index, context) {
  38023. ts.Debug.assert(chain && 0 <= index && index < chain.length);
  38024. var symbol = chain[index];
  38025. var symbolId = "" + getSymbolId(symbol);
  38026. if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
  38027. return undefined;
  38028. }
  38029. (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
  38030. var typeParameterNodes;
  38031. if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
  38032. var parentSymbol = symbol;
  38033. var nextSymbol = chain[index + 1];
  38034. if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) {
  38035. var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
  38036. typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context);
  38037. }
  38038. else {
  38039. typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
  38040. }
  38041. }
  38042. return typeParameterNodes;
  38043. }
  38044. /**
  38045. * Given A[B][C][D], finds A[B]
  38046. */
  38047. function getTopmostIndexedAccessType(top) {
  38048. if (ts.isIndexedAccessTypeNode(top.objectType)) {
  38049. return getTopmostIndexedAccessType(top.objectType);
  38050. }
  38051. return top;
  38052. }
  38053. function getSpecifierForModuleSymbol(symbol, context) {
  38054. var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
  38055. if (file && file.moduleName !== undefined) {
  38056. // Use the amd name if it is available
  38057. return file.moduleName;
  38058. }
  38059. if (!file) {
  38060. if (context.tracker.trackReferencedAmbientModule) {
  38061. var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
  38062. if (ts.length(ambientDecls)) {
  38063. for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
  38064. var decl = ambientDecls_1[_i];
  38065. context.tracker.trackReferencedAmbientModule(decl, symbol);
  38066. }
  38067. }
  38068. }
  38069. if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
  38070. return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
  38071. }
  38072. }
  38073. if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
  38074. // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
  38075. if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
  38076. return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
  38077. }
  38078. return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full
  38079. }
  38080. var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
  38081. var links = getSymbolLinks(symbol);
  38082. var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
  38083. if (!specifier) {
  38084. var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
  38085. // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
  38086. // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
  38087. // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
  38088. // specifier preference
  38089. var moduleResolverHost = context.tracker.moduleResolverHost;
  38090. var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
  38091. specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap));
  38092. links.specifierCache = links.specifierCache || ts.createMap();
  38093. links.specifierCache.set(contextFile.path, specifier);
  38094. }
  38095. return specifier;
  38096. }
  38097. function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
  38098. var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
  38099. var isTypeOf = meaning === 111551 /* Value */;
  38100. if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
  38101. // module is root, must use `ImportTypeNode`
  38102. var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
  38103. var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
  38104. var specifier = getSpecifierForModuleSymbol(chain[0], context);
  38105. if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
  38106. // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
  38107. // since declaration files with these kinds of references are liable to fail when published :(
  38108. context.encounteredError = true;
  38109. if (context.tracker.reportLikelyUnsafeImportRequiredError) {
  38110. context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
  38111. }
  38112. }
  38113. var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
  38114. if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
  38115. context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
  38116. context.approximateLength += specifier.length + 10; // specifier + import("")
  38117. if (!nonRootParts || ts.isEntityName(nonRootParts)) {
  38118. if (nonRootParts) {
  38119. var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
  38120. lastId.typeArguments = undefined;
  38121. }
  38122. return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
  38123. }
  38124. else {
  38125. var splitNode = getTopmostIndexedAccessType(nonRootParts);
  38126. var qualifier = splitNode.objectType.typeName;
  38127. return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
  38128. }
  38129. }
  38130. var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
  38131. if (ts.isIndexedAccessTypeNode(entityName)) {
  38132. return entityName; // Indexed accesses can never be `typeof`
  38133. }
  38134. if (isTypeOf) {
  38135. return ts.createTypeQueryNode(entityName);
  38136. }
  38137. else {
  38138. var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
  38139. var lastTypeArgs = lastId.typeArguments;
  38140. lastId.typeArguments = undefined;
  38141. return ts.createTypeReferenceNode(entityName, lastTypeArgs);
  38142. }
  38143. function createAccessFromSymbolChain(chain, index, stopper) {
  38144. var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
  38145. var symbol = chain[index];
  38146. var parent = chain[index - 1];
  38147. var symbolName;
  38148. if (index === 0) {
  38149. context.flags |= 16777216 /* InInitialEntityName */;
  38150. symbolName = getNameOfSymbolAsWritten(symbol, context);
  38151. context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
  38152. context.flags ^= 16777216 /* InInitialEntityName */;
  38153. }
  38154. else {
  38155. if (parent && getExportsOfSymbol(parent)) {
  38156. var exports_1 = getExportsOfSymbol(parent);
  38157. ts.forEachEntry(exports_1, function (ex, name) {
  38158. if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
  38159. symbolName = ts.unescapeLeadingUnderscores(name);
  38160. return true;
  38161. }
  38162. });
  38163. }
  38164. }
  38165. if (!symbolName) {
  38166. symbolName = getNameOfSymbolAsWritten(symbol, context);
  38167. }
  38168. context.approximateLength += symbolName.length + 1;
  38169. if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
  38170. getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
  38171. getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
  38172. // Should use an indexed access
  38173. var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
  38174. if (ts.isIndexedAccessTypeNode(LHS)) {
  38175. return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
  38176. }
  38177. else {
  38178. return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
  38179. }
  38180. }
  38181. var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
  38182. identifier.symbol = symbol;
  38183. if (index > stopper) {
  38184. var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
  38185. if (!ts.isEntityName(LHS)) {
  38186. return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
  38187. }
  38188. return ts.createQualifiedName(LHS, identifier);
  38189. }
  38190. return identifier;
  38191. }
  38192. }
  38193. function typeParameterShadowsNameInScope(escapedName, context) {
  38194. return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
  38195. }
  38196. function typeParameterToName(type, context) {
  38197. if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
  38198. var cached = context.typeParameterNames.get("" + getTypeId(type));
  38199. if (cached) {
  38200. return cached;
  38201. }
  38202. }
  38203. var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
  38204. if (!(result.kind & 75 /* Identifier */)) {
  38205. return ts.createIdentifier("(Missing type parameter)");
  38206. }
  38207. if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
  38208. var rawtext = result.escapedText;
  38209. var i = 0;
  38210. var text = rawtext;
  38211. while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) {
  38212. i++;
  38213. text = rawtext + "_" + i;
  38214. }
  38215. if (text !== rawtext) {
  38216. result = ts.createIdentifier(text, result.typeArguments);
  38217. }
  38218. (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
  38219. (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
  38220. }
  38221. return result;
  38222. }
  38223. function symbolToName(symbol, context, meaning, expectsIdentifier) {
  38224. var chain = lookupSymbolChain(symbol, context, meaning);
  38225. if (expectsIdentifier && chain.length !== 1
  38226. && !context.encounteredError
  38227. && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
  38228. context.encounteredError = true;
  38229. }
  38230. return createEntityNameFromSymbolChain(chain, chain.length - 1);
  38231. function createEntityNameFromSymbolChain(chain, index) {
  38232. var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
  38233. var symbol = chain[index];
  38234. if (index === 0) {
  38235. context.flags |= 16777216 /* InInitialEntityName */;
  38236. }
  38237. var symbolName = getNameOfSymbolAsWritten(symbol, context);
  38238. if (index === 0) {
  38239. context.flags ^= 16777216 /* InInitialEntityName */;
  38240. }
  38241. var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
  38242. identifier.symbol = symbol;
  38243. return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
  38244. }
  38245. }
  38246. function symbolToExpression(symbol, context, meaning) {
  38247. var chain = lookupSymbolChain(symbol, context, meaning);
  38248. return createExpressionFromSymbolChain(chain, chain.length - 1);
  38249. function createExpressionFromSymbolChain(chain, index) {
  38250. var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
  38251. var symbol = chain[index];
  38252. if (index === 0) {
  38253. context.flags |= 16777216 /* InInitialEntityName */;
  38254. }
  38255. var symbolName = getNameOfSymbolAsWritten(symbol, context);
  38256. if (index === 0) {
  38257. context.flags ^= 16777216 /* InInitialEntityName */;
  38258. }
  38259. var firstChar = symbolName.charCodeAt(0);
  38260. if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
  38261. return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
  38262. }
  38263. var canUsePropertyAccess = firstChar === 35 /* hash */ ?
  38264. symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
  38265. ts.isIdentifierStart(firstChar, languageVersion);
  38266. if (index === 0 || canUsePropertyAccess) {
  38267. var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
  38268. identifier.symbol = symbol;
  38269. return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
  38270. }
  38271. else {
  38272. if (firstChar === 91 /* openBracket */) {
  38273. symbolName = symbolName.substring(1, symbolName.length - 1);
  38274. firstChar = symbolName.charCodeAt(0);
  38275. }
  38276. var expression = void 0;
  38277. if (ts.isSingleOrDoubleQuote(firstChar)) {
  38278. expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
  38279. expression.singleQuote = firstChar === 39 /* singleQuote */;
  38280. }
  38281. else if (("" + +symbolName) === symbolName) {
  38282. expression = ts.createLiteral(+symbolName);
  38283. }
  38284. if (!expression) {
  38285. expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
  38286. expression.symbol = symbol;
  38287. }
  38288. return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
  38289. }
  38290. }
  38291. }
  38292. function isSingleQuotedStringNamed(d) {
  38293. var name = ts.getNameOfDeclaration(d);
  38294. if (name && ts.isStringLiteral(name) && (name.singleQuote ||
  38295. (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
  38296. return true;
  38297. }
  38298. return false;
  38299. }
  38300. function getPropertyNameNodeForSymbol(symbol, context) {
  38301. var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
  38302. var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
  38303. if (fromNameType) {
  38304. return fromNameType;
  38305. }
  38306. if (ts.isKnownSymbol(symbol)) {
  38307. return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
  38308. }
  38309. var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
  38310. return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
  38311. }
  38312. // See getNameForSymbolFromNameType for a stringy equivalent
  38313. function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
  38314. var nameType = getSymbolLinks(symbol).nameType;
  38315. if (nameType) {
  38316. if (nameType.flags & 384 /* StringOrNumberLiteral */) {
  38317. var name = "" + nameType.value;
  38318. if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
  38319. return ts.createLiteral(name, !!singleQuote);
  38320. }
  38321. if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
  38322. return ts.createComputedPropertyName(ts.createLiteral(+name));
  38323. }
  38324. return createPropertyNameNodeForIdentifierOrLiteral(name);
  38325. }
  38326. if (nameType.flags & 8192 /* UniqueESSymbol */) {
  38327. return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
  38328. }
  38329. }
  38330. }
  38331. function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
  38332. return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote);
  38333. }
  38334. function cloneNodeBuilderContext(context) {
  38335. var initial = __assign({}, context);
  38336. // Make type parameters created within this context not consume the name outside this context
  38337. // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
  38338. // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
  38339. // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
  38340. // were multiple generic overloads with similar generated type parameter names
  38341. // The effect:
  38342. // When we write out
  38343. // export const x: <T>(x: T) => T
  38344. // export const y: <T>(x: T) => T
  38345. // we write it out like that, rather than as
  38346. // export const x: <T>(x: T) => T
  38347. // export const y: <T_1>(x: T_1) => T_1
  38348. if (initial.typeParameterNames) {
  38349. initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
  38350. }
  38351. if (initial.typeParameterNamesByText) {
  38352. initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
  38353. }
  38354. if (initial.typeParameterSymbolList) {
  38355. initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
  38356. }
  38357. return initial;
  38358. }
  38359. function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
  38360. var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
  38361. var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
  38362. // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
  38363. // declaration mapping
  38364. // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
  38365. // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
  38366. // we're trying to emit from later on)
  38367. var enclosingDeclaration = context.enclosingDeclaration;
  38368. var results = [];
  38369. var visitedSymbols = ts.createMap();
  38370. var deferredPrivates;
  38371. var oldcontext = context;
  38372. context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
  38373. var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
  38374. if (accessibleResult.accessibility === 0 /* Accessible */) {
  38375. // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
  38376. var chain = lookupSymbolChainWorker(sym, context, meaning);
  38377. if (!(sym.flags & 4 /* Property */)) {
  38378. includePrivateSymbol(chain[0]);
  38379. }
  38380. }
  38381. else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
  38382. oldcontext.tracker.trackSymbol(sym, decl, meaning);
  38383. }
  38384. } }) });
  38385. if (oldcontext.usedSymbolNames) {
  38386. oldcontext.usedSymbolNames.forEach(function (_, name) {
  38387. context.usedSymbolNames.set(name, true);
  38388. });
  38389. }
  38390. ts.forEachEntry(symbolTable, function (symbol, name) {
  38391. var baseName = ts.unescapeLeadingUnderscores(name);
  38392. void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
  38393. });
  38394. var addingDeclare = !bundled;
  38395. var exportEquals = symbolTable.get("export=" /* ExportEquals */);
  38396. if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
  38397. symbolTable = ts.createSymbolTable();
  38398. // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
  38399. symbolTable.set("export=" /* ExportEquals */, exportEquals);
  38400. }
  38401. visitSymbolTable(symbolTable);
  38402. return mergeRedundantStatements(results);
  38403. function isIdentifierAndNotUndefined(node) {
  38404. return !!node && node.kind === 75 /* Identifier */;
  38405. }
  38406. function getNamesOfDeclaration(statement) {
  38407. if (ts.isVariableStatement(statement)) {
  38408. return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
  38409. }
  38410. return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
  38411. }
  38412. function flattenExportAssignedNamespace(statements) {
  38413. var exportAssignment = ts.find(statements, ts.isExportAssignment);
  38414. var ns = ts.find(statements, ts.isModuleDeclaration);
  38415. if (ns && exportAssignment && exportAssignment.isExportEquals &&
  38416. ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
  38417. ns.body && ts.isModuleBlock(ns.body)) {
  38418. // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
  38419. // the top-level exports and exporting them in the targeted ns, as can occur when a js file has both typedefs and `module.export` assignments
  38420. var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
  38421. if (ts.length(excessExports)) {
  38422. ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
  38423. /*decorators*/ undefined,
  38424. /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })),
  38425. /*moduleSpecifier*/ undefined)]));
  38426. }
  38427. // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
  38428. if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
  38429. results = [];
  38430. ts.forEach(ns.body.statements, function (s) {
  38431. addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
  38432. });
  38433. statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
  38434. }
  38435. }
  38436. return statements;
  38437. }
  38438. function mergeExportDeclarations(statements) {
  38439. // Pass 2: Combine all `export {}` declarations
  38440. var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
  38441. if (ts.length(exports) > 1) {
  38442. var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
  38443. statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
  38444. /*decorators*/ undefined,
  38445. /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })),
  38446. /*moduleSpecifier*/ undefined)]);
  38447. }
  38448. // Pass 2b: Also combine all `export {} from "..."` declarations as needed
  38449. var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
  38450. if (ts.length(reexports) > 1) {
  38451. var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
  38452. if (groups.length !== reexports.length) {
  38453. var _loop_7 = function (group_1) {
  38454. if (group_1.length > 1) {
  38455. // remove group members from statements and then merge group members and add back to statements
  38456. statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
  38457. ts.createExportDeclaration(
  38458. /*decorators*/ undefined,
  38459. /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
  38460. ]);
  38461. }
  38462. };
  38463. for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
  38464. var group_1 = groups_1[_i];
  38465. _loop_7(group_1);
  38466. }
  38467. }
  38468. }
  38469. return statements;
  38470. }
  38471. function inlineExportModifiers(statements) {
  38472. // Pass 3: Move all `export {}`'s to `export` modifiers where possible
  38473. var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
  38474. if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
  38475. var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
  38476. if (!e.propertyName) {
  38477. // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
  38478. var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
  38479. if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
  38480. ts.forEach(associated, addExportModifier);
  38481. return undefined;
  38482. }
  38483. }
  38484. return e;
  38485. });
  38486. if (!ts.length(replacements)) {
  38487. // all clauses removed, filter the export declaration
  38488. statements = ts.filter(statements, function (s) { return s !== exportDecl; });
  38489. }
  38490. else {
  38491. // some items filtered, others not - update the export declaration
  38492. // (mutating because why not, we're building a whole new tree here anyway)
  38493. exportDecl.exportClause.elements = ts.createNodeArray(replacements);
  38494. }
  38495. }
  38496. return statements;
  38497. }
  38498. function mergeRedundantStatements(statements) {
  38499. statements = flattenExportAssignedNamespace(statements);
  38500. statements = mergeExportDeclarations(statements);
  38501. statements = inlineExportModifiers(statements);
  38502. // Not a cleanup, but as a final step: If there is a mix of `export` and non-`export` declarations, but no `export =` or `export {}` add a `export {};` so
  38503. // declaration privacy is respected.
  38504. if (enclosingDeclaration &&
  38505. ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
  38506. (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
  38507. statements.push(ts.createEmptyExports());
  38508. }
  38509. return statements;
  38510. }
  38511. function canHaveExportModifier(node) {
  38512. return ts.isEnumDeclaration(node) ||
  38513. ts.isVariableStatement(node) ||
  38514. ts.isFunctionDeclaration(node) ||
  38515. ts.isClassDeclaration(node) ||
  38516. (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
  38517. ts.isInterfaceDeclaration(node) ||
  38518. isTypeDeclaration(node);
  38519. }
  38520. function addExportModifier(statement) {
  38521. var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
  38522. statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
  38523. statement.modifierFlagsCache = 0;
  38524. }
  38525. function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
  38526. var oldDeferredPrivates = deferredPrivates;
  38527. if (!suppressNewPrivateContext) {
  38528. deferredPrivates = ts.createMap();
  38529. }
  38530. symbolTable.forEach(function (symbol) {
  38531. serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
  38532. });
  38533. if (!suppressNewPrivateContext) {
  38534. // deferredPrivates will be filled up by visiting the symbol table
  38535. // And will continue to iterate as elements are added while visited `deferredPrivates`
  38536. // (As that's how a map iterator is defined to work)
  38537. deferredPrivates.forEach(function (symbol) {
  38538. serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
  38539. });
  38540. }
  38541. deferredPrivates = oldDeferredPrivates;
  38542. }
  38543. function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
  38544. // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
  38545. // still skip reserializing it if we encounter the merged product later on
  38546. var visitedSym = getMergedSymbol(symbol);
  38547. if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
  38548. return; // Already printed
  38549. }
  38550. visitedSymbols.set("" + getSymbolId(visitedSym), true);
  38551. // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
  38552. var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
  38553. if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
  38554. var oldContext = context;
  38555. context = cloneNodeBuilderContext(context);
  38556. var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
  38557. context = oldContext;
  38558. return result;
  38559. }
  38560. }
  38561. // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
  38562. // or a merge of some number of those.
  38563. // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
  38564. // each symbol in only one of the representations
  38565. // Also, synthesizing a default export of some kind
  38566. // If it's an alias: emit `export default ref`
  38567. // If it's a property: emit `export default _default` with a `_default` prop
  38568. // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
  38569. // These forms can merge, eg (`export default 12; export default interface A {}`)
  38570. function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
  38571. var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
  38572. var isDefault = symbol.escapedName === "default" /* Default */;
  38573. if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
  38574. // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :(
  38575. context.encounteredError = true;
  38576. // TODO: Issue error via symbol tracker?
  38577. return; // If we need to emit a private with a keyword name, we're done for, since something else will try to refer to it by that name
  38578. }
  38579. var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
  38580. || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
  38581. if (needsPostExportDefault) {
  38582. isPrivate = true;
  38583. }
  38584. var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
  38585. var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
  38586. symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
  38587. symbol.escapedName !== "export=" /* ExportEquals */;
  38588. var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
  38589. if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
  38590. serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
  38591. }
  38592. if (symbol.flags & 524288 /* TypeAlias */) {
  38593. serializeTypeAlias(symbol, symbolName, modifierFlags);
  38594. }
  38595. // Need to skip over export= symbols below - json source files get a single `Property` flagged
  38596. // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
  38597. if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
  38598. && symbol.escapedName !== "export=" /* ExportEquals */
  38599. && !(symbol.flags & 4194304 /* Prototype */)
  38600. && !(symbol.flags & 32 /* Class */)
  38601. && !isConstMergedWithNSPrintableAsSignatureMerge) {
  38602. serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
  38603. }
  38604. if (symbol.flags & 384 /* Enum */) {
  38605. serializeEnum(symbol, symbolName, modifierFlags);
  38606. }
  38607. if (symbol.flags & 32 /* Class */) {
  38608. if (symbol.flags & 4 /* Property */) {
  38609. // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
  38610. // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
  38611. // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
  38612. serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
  38613. }
  38614. else {
  38615. serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
  38616. }
  38617. }
  38618. if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
  38619. serializeModule(symbol, symbolName, modifierFlags);
  38620. }
  38621. if (symbol.flags & 64 /* Interface */) {
  38622. serializeInterface(symbol, symbolName, modifierFlags);
  38623. }
  38624. if (symbol.flags & 2097152 /* Alias */) {
  38625. serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
  38626. }
  38627. if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
  38628. serializeMaybeAliasAssignment(symbol);
  38629. }
  38630. if (symbol.flags & 8388608 /* ExportStar */) {
  38631. // synthesize export * from "moduleReference"
  38632. // Straightforward - only one thing to do - make an export declaration
  38633. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  38634. var node = _a[_i];
  38635. var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
  38636. if (!resolvedModule)
  38637. continue;
  38638. addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
  38639. }
  38640. }
  38641. if (needsPostExportDefault) {
  38642. addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
  38643. }
  38644. }
  38645. function includePrivateSymbol(symbol) {
  38646. if (ts.some(symbol.declarations, ts.isParameterDeclaration))
  38647. return;
  38648. ts.Debug.assertDefined(deferredPrivates);
  38649. getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
  38650. deferredPrivates.set("" + getSymbolId(symbol), symbol);
  38651. }
  38652. function isExportingScope(enclosingDeclaration) {
  38653. return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
  38654. (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
  38655. }
  38656. // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
  38657. // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
  38658. function addResult(node, additionalModifierFlags) {
  38659. var newModifierFlags = 0 /* None */;
  38660. if (additionalModifierFlags & 1 /* Export */ &&
  38661. enclosingDeclaration &&
  38662. isExportingScope(enclosingDeclaration) &&
  38663. canHaveExportModifier(node)) {
  38664. // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
  38665. newModifierFlags |= 1 /* Export */;
  38666. }
  38667. if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
  38668. (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
  38669. (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
  38670. // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
  38671. newModifierFlags |= 2 /* Ambient */;
  38672. }
  38673. if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
  38674. newModifierFlags |= 512 /* Default */;
  38675. }
  38676. if (newModifierFlags) {
  38677. node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
  38678. node.modifierFlagsCache = 0; // Reset computed flags cache
  38679. }
  38680. results.push(node);
  38681. }
  38682. function serializeTypeAlias(symbol, symbolName, modifierFlags) {
  38683. var aliasType = getDeclaredTypeOfTypeAlias(symbol);
  38684. var typeParams = getSymbolLinks(symbol).typeParameters;
  38685. var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
  38686. var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
  38687. var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
  38688. var oldFlags = context.flags;
  38689. context.flags |= 8388608 /* InTypeAlias */;
  38690. addResult(ts.setSyntheticLeadingComments(ts.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeToTypeNodeHelper(aliasType, context)), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags);
  38691. context.flags = oldFlags;
  38692. }
  38693. function serializeInterface(symbol, symbolName, modifierFlags) {
  38694. var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
  38695. var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  38696. var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
  38697. var baseTypes = getBaseTypes(interfaceType);
  38698. var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
  38699. var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
  38700. var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
  38701. var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
  38702. var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
  38703. var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
  38704. addResult(ts.createInterfaceDeclaration(
  38705. /*decorators*/ undefined,
  38706. /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
  38707. }
  38708. function getNamespaceMembersForSerialization(symbol) {
  38709. return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); });
  38710. }
  38711. function isTypeOnlyNamespace(symbol) {
  38712. return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
  38713. }
  38714. function serializeModule(symbol, symbolName, modifierFlags) {
  38715. var members = getNamespaceMembersForSerialization(symbol);
  38716. // Split NS members up by declaration - members whose parent symbol is the ns symbol vs those whose is not (but were added in later via merging)
  38717. var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
  38718. var realMembers = locationMap.get("real") || ts.emptyArray;
  38719. var mergedMembers = locationMap.get("merged") || ts.emptyArray;
  38720. // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
  38721. // than whatever scope we traverse to them in. That's a bit of a complex rewrite, since we're not _actually_ tracking privates at all in advance,
  38722. // so we don't even have placeholders to fill in.
  38723. if (ts.length(realMembers)) {
  38724. var localName = getInternalSymbolName(symbol, symbolName);
  38725. serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
  38726. }
  38727. if (ts.length(mergedMembers)) {
  38728. var localName = getInternalSymbolName(symbol, symbolName);
  38729. var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
  38730. /*decorators*/ undefined,
  38731. /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
  38732. var name = ts.unescapeLeadingUnderscores(s.escapedName);
  38733. var localName = getInternalSymbolName(s, name);
  38734. var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
  38735. var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
  38736. includePrivateSymbol(target || s);
  38737. var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
  38738. return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
  38739. })))]);
  38740. addResult(ts.createModuleDeclaration(
  38741. /*decorators*/ undefined,
  38742. /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
  38743. }
  38744. }
  38745. function serializeEnum(symbol, symbolName, modifierFlags) {
  38746. addResult(ts.createEnumDeclaration(
  38747. /*decorators*/ undefined, ts.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* EnumMember */); }), function (p) {
  38748. // TODO: Handle computed names
  38749. // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
  38750. // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
  38751. // _on the declaration_, not on the declaration's symbol...
  38752. var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
  38753. return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
  38754. })), modifierFlags);
  38755. }
  38756. function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
  38757. if (propertyAsAlias) {
  38758. serializeMaybeAliasAssignment(symbol);
  38759. }
  38760. else {
  38761. var type = getTypeOfSymbol(symbol);
  38762. var localName = getInternalSymbolName(symbol, symbolName);
  38763. if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
  38764. // If the type looks like a function declaration + ns could represent it, and it's type is sourced locally, rewrite it into a function declaration + ns
  38765. serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
  38766. }
  38767. else {
  38768. // A Class + Property merge is made for a `module.exports.Member = class {}`, and it doesn't serialize well as either a class _or_ a property symbol - in fact, _it behaves like an alias!_
  38769. // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
  38770. var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
  38771. : isConstVariable(symbol) ? 2 /* Const */
  38772. : 1 /* Let */;
  38773. var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
  38774. var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
  38775. if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
  38776. textRange = textRange.parent.parent;
  38777. }
  38778. var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
  38779. ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol))
  38780. ], flags)), textRange);
  38781. addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
  38782. if (name !== localName && !isPrivate) {
  38783. // We rename the variable declaration we generate for Property symbols since they may have a name which
  38784. // conflicts with a local declaration. For example, given input:
  38785. // ```
  38786. // function g() {}
  38787. // module.exports.g = g
  38788. // ```
  38789. // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
  38790. // Naively, we would emit
  38791. // ```
  38792. // function g() {}
  38793. // export const g: typeof g;
  38794. // ```
  38795. // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
  38796. // the export declaration shadows it.
  38797. // To work around that, we instead write
  38798. // ```
  38799. // function g() {}
  38800. // const g_1: typeof g;
  38801. // export { g_1 as g };
  38802. // ```
  38803. // To create an export named `g` that does _not_ shadow the local `g`
  38804. addResult(ts.createExportDeclaration(
  38805. /*decorators*/ undefined,
  38806. /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
  38807. }
  38808. }
  38809. }
  38810. }
  38811. function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
  38812. var signatures = getSignaturesOfType(type, 0 /* Call */);
  38813. for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
  38814. var sig = signatures_2[_i];
  38815. // Each overload becomes a separate function declaration, in order
  38816. var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context);
  38817. decl.name = ts.createIdentifier(localName);
  38818. addResult(ts.setTextRange(decl, sig.declaration), modifierFlags);
  38819. }
  38820. // Module symbol emit will take care of module-y members, provided it has exports
  38821. if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
  38822. var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); });
  38823. serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
  38824. }
  38825. }
  38826. function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
  38827. if (ts.length(props)) {
  38828. var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
  38829. return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
  38830. return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
  38831. }) ? "local" : "remote";
  38832. });
  38833. var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
  38834. // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
  38835. // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
  38836. // Example:
  38837. // import Foo_1 = require("./exporter");
  38838. // export namespace ns {
  38839. // import Foo = Foo_1.Foo;
  38840. // export { Foo };
  38841. // export const c: number;
  38842. // }
  38843. // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
  38844. // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
  38845. // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
  38846. // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
  38847. // emit akin to the above would be needed.
  38848. // Add a namespace
  38849. var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
  38850. fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
  38851. fakespace.parent = enclosingDeclaration;
  38852. fakespace.locals = ts.createSymbolTable(props);
  38853. fakespace.symbol = props[0].parent;
  38854. var oldResults = results;
  38855. results = [];
  38856. var oldAddingDeclare = addingDeclare;
  38857. addingDeclare = false;
  38858. var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
  38859. var oldContext = context;
  38860. context = subcontext;
  38861. // TODO: implement handling for the localVsRemoteMap.get("remote") - should be difficult to trigger (see comment above), as only interesting cross-file js merges should make this possible
  38862. visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
  38863. context = oldContext;
  38864. addingDeclare = oldAddingDeclare;
  38865. var declarations = results;
  38866. results = oldResults;
  38867. fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
  38868. fakespace.parent = undefined;
  38869. fakespace.locals = undefined;
  38870. fakespace.symbol = undefined;
  38871. fakespace.body = ts.createModuleBlock(declarations);
  38872. addResult(fakespace, modifierFlags); // namespaces can never be default exported
  38873. }
  38874. }
  38875. function serializeAsClass(symbol, localName, modifierFlags) {
  38876. var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  38877. var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
  38878. var classType = getDeclaredTypeOfClassOrInterface(symbol);
  38879. var baseTypes = getBaseTypes(classType);
  38880. var staticType = getTypeOfSymbol(symbol);
  38881. var staticBaseType = getBaseConstructorTypeOfClass(staticType);
  38882. var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))];
  38883. var symbolProps = getPropertiesOfType(classType);
  38884. var publicSymbolProps = ts.filter(symbolProps, function (s) {
  38885. var valueDecl = s.valueDeclaration;
  38886. ts.Debug.assertDefined(valueDecl);
  38887. return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
  38888. });
  38889. var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
  38890. var valueDecl = s.valueDeclaration;
  38891. ts.Debug.assertDefined(valueDecl);
  38892. return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
  38893. });
  38894. // Boil down all private properties into a single one.
  38895. var privateProperties = hasPrivateIdentifier ?
  38896. [ts.createProperty(
  38897. /*decorators*/ undefined,
  38898. /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"),
  38899. /*questionOrExclamationToken*/ undefined,
  38900. /*type*/ undefined,
  38901. /*initializer*/ undefined)] :
  38902. ts.emptyArray;
  38903. var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
  38904. // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
  38905. var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */)
  38906. ? []
  38907. : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); });
  38908. var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
  38909. for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
  38910. var c = constructors_1[_i];
  38911. // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
  38912. // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
  38913. c.type = undefined;
  38914. c.typeParameters = undefined;
  38915. }
  38916. var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
  38917. addResult(ts.setTextRange(ts.createClassDeclaration(
  38918. /*decorators*/ undefined,
  38919. /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, staticMembers, constructors, publicProperties, privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
  38920. }
  38921. function serializeAsAlias(symbol, localName, modifierFlags) {
  38922. // synthesize an alias, eg `export { symbolName as Name }`
  38923. // need to mark the alias `symbol` points at
  38924. // as something we need to serialize as a private declaration as well
  38925. var node = getDeclarationOfAliasSymbol(symbol);
  38926. if (!node)
  38927. return ts.Debug.fail();
  38928. var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
  38929. if (!target) {
  38930. return;
  38931. }
  38932. var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
  38933. if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
  38934. // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
  38935. verbatimTargetName = "default" /* Default */;
  38936. }
  38937. var targetName = getInternalSymbolName(target, verbatimTargetName);
  38938. includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
  38939. switch (node.kind) {
  38940. case 253 /* ImportEqualsDeclaration */:
  38941. // Could be a local `import localName = ns.member` or
  38942. // an external `import localName = require("whatever")`
  38943. var isLocalImport = !(target.flags & 512 /* ValueModule */);
  38944. addResult(ts.createImportEqualsDeclaration(
  38945. /*decorators*/ undefined,
  38946. /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
  38947. ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
  38948. : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
  38949. break;
  38950. case 252 /* NamespaceExportDeclaration */:
  38951. // export as namespace foo
  38952. // TODO: Not part of a file's local or export symbol tables
  38953. // Is bound into file.symbol.globalExports instead, which we don't currently traverse
  38954. addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
  38955. break;
  38956. case 255 /* ImportClause */:
  38957. addResult(ts.createImportDeclaration(
  38958. /*decorators*/ undefined,
  38959. /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined),
  38960. // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
  38961. // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
  38962. // In such cases, the `target` refers to the module itself already
  38963. ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
  38964. break;
  38965. case 256 /* NamespaceImport */:
  38966. addResult(ts.createImportDeclaration(
  38967. /*decorators*/ undefined,
  38968. /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
  38969. break;
  38970. case 262 /* NamespaceExport */:
  38971. addResult(ts.createExportDeclaration(
  38972. /*decorators*/ undefined,
  38973. /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
  38974. break;
  38975. case 258 /* ImportSpecifier */:
  38976. addResult(ts.createImportDeclaration(
  38977. /*decorators*/ undefined,
  38978. /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
  38979. ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
  38980. ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
  38981. break;
  38982. case 263 /* ExportSpecifier */:
  38983. // does not use localName because the symbol name in this case refers to the name in the exports table,
  38984. // which we must exactly preserve
  38985. var specifier = node.parent.parent.moduleSpecifier;
  38986. // targetName is only used when the target is local, as otherwise the target is an alias that points at
  38987. // another file
  38988. serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
  38989. break;
  38990. case 259 /* ExportAssignment */:
  38991. serializeMaybeAliasAssignment(symbol);
  38992. break;
  38993. case 209 /* BinaryExpression */:
  38994. case 194 /* PropertyAccessExpression */:
  38995. // Could be best encoded as though an export specifier or as though an export assignment
  38996. // If name is default or export=, do an export assignment
  38997. // Otherwise do an export specifier
  38998. if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
  38999. serializeMaybeAliasAssignment(symbol);
  39000. }
  39001. else {
  39002. serializeExportSpecifier(localName, targetName);
  39003. }
  39004. break;
  39005. default:
  39006. return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
  39007. }
  39008. }
  39009. function serializeExportSpecifier(localName, targetName, specifier) {
  39010. addResult(ts.createExportDeclaration(
  39011. /*decorators*/ undefined,
  39012. /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
  39013. }
  39014. function serializeMaybeAliasAssignment(symbol) {
  39015. if (symbol.flags & 4194304 /* Prototype */) {
  39016. return;
  39017. }
  39018. var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
  39019. var isExportEquals = name === "export=" /* ExportEquals */;
  39020. var isDefault = name === "default" /* Default */;
  39021. var isExportAssignment = isExportEquals || isDefault;
  39022. // synthesize export = ref
  39023. // ref should refer to either be a locally scoped symbol which we need to emit, or
  39024. // a reference to another namespace/module which we may need to emit an `import` statement for
  39025. var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
  39026. // serialize what the alias points to, preserve the declaration's initializer
  39027. var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
  39028. // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
  39029. if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
  39030. // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
  39031. // eg, `namespace A { export class B {} }; exports = A.B;`
  39032. // Technically, this is all that's required in the case where the assignment is an entity name expression
  39033. var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
  39034. var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
  39035. var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
  39036. if (referenced || target) {
  39037. includePrivateSymbol(referenced || target);
  39038. }
  39039. // We disable the context's symbol traker for the duration of this name serialization
  39040. // as, by virtue of being here, the name is required to print something, and we don't want to
  39041. // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
  39042. // a visibility error here (as they're not visible within any scope), but we want to hoist them
  39043. // into the containing scope anyway, so we want to skip the visibility checks.
  39044. var oldTrack = context.tracker.trackSymbol;
  39045. context.tracker.trackSymbol = ts.noop;
  39046. if (isExportAssignment) {
  39047. results.push(ts.createExportAssignment(
  39048. /*decorators*/ undefined,
  39049. /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
  39050. }
  39051. else {
  39052. if (first_1 === expr) {
  39053. // serialize as `export {target as name}`
  39054. serializeExportSpecifier(name, ts.idText(first_1));
  39055. }
  39056. else if (ts.isClassExpression(expr)) {
  39057. serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
  39058. }
  39059. else {
  39060. // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
  39061. var varName = getUnusedName(name, symbol);
  39062. addResult(ts.createImportEqualsDeclaration(
  39063. /*decorators*/ undefined,
  39064. /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
  39065. serializeExportSpecifier(name, varName);
  39066. }
  39067. }
  39068. context.tracker.trackSymbol = oldTrack;
  39069. }
  39070. else {
  39071. // serialize as an anonymous property declaration
  39072. var varName = getUnusedName(name, symbol);
  39073. // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
  39074. // (Unwidened types can only exist in expression contexts and should never be serialized)
  39075. var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol));
  39076. if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
  39077. // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
  39078. serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
  39079. }
  39080. else {
  39081. var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
  39082. ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol))
  39083. ], 2 /* Const */));
  39084. addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
  39085. }
  39086. if (isExportAssignment) {
  39087. results.push(ts.createExportAssignment(
  39088. /*decorators*/ undefined,
  39089. /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
  39090. }
  39091. else if (name !== varName) {
  39092. serializeExportSpecifier(name, varName);
  39093. }
  39094. }
  39095. }
  39096. function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
  39097. // Only object types which are not constructable, or indexable, whose members all come from the
  39098. // context source file, and whose property names are all valid identifiers and not late-bound, _and_
  39099. // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
  39100. var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
  39101. return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
  39102. !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
  39103. !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
  39104. !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
  39105. !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
  39106. !getDeclarationWithTypeAnnotation(hostSymbol) &&
  39107. !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
  39108. !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
  39109. !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
  39110. ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
  39111. }
  39112. function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
  39113. return function serializePropertySymbol(p, isStatic, baseType) {
  39114. var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
  39115. var isPrivate = !!(modifierFlags & 8 /* Private */);
  39116. if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
  39117. // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
  39118. // need to be merged namespace members
  39119. return [];
  39120. }
  39121. if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName)
  39122. && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
  39123. && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
  39124. && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
  39125. return [];
  39126. }
  39127. var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
  39128. var name = getPropertyNameNodeForSymbol(p, context);
  39129. var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
  39130. if (p.flags & 98304 /* Accessor */ && useAccessors) {
  39131. var result = [];
  39132. if (p.flags & 65536 /* SetAccessor */) {
  39133. result.push(ts.setTextRange(ts.createSetAccessor(
  39134. /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
  39135. /*decorators*/ undefined,
  39136. /*modifiers*/ undefined,
  39137. /*dotDotDotToken*/ undefined, "arg",
  39138. /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))],
  39139. /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
  39140. }
  39141. if (p.flags & 32768 /* GetAccessor */) {
  39142. var isPrivate_1 = modifierFlags & 8 /* Private */;
  39143. result.push(ts.setTextRange(ts.createGetAccessor(
  39144. /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p),
  39145. /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
  39146. }
  39147. return result;
  39148. }
  39149. // This is an else/if as accessors and properties can't merge in TS, but might in JS
  39150. // If this happens, we assume the accessor takes priority, as it imposes more constraints
  39151. else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
  39152. return ts.setTextRange(createProperty(
  39153. /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p),
  39154. // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
  39155. // interface members can't have initializers, however class members _can_
  39156. /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
  39157. }
  39158. if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
  39159. var type = getTypeOfSymbol(p);
  39160. var signatures = getSignaturesOfType(type, 0 /* Call */);
  39161. if (flag & 8 /* Private */) {
  39162. return ts.setTextRange(createProperty(
  39163. /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined,
  39164. /*type*/ undefined,
  39165. /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
  39166. }
  39167. var results_1 = [];
  39168. for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
  39169. var sig = signatures_3[_i];
  39170. // Each overload becomes a separate method declaration, in order
  39171. var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
  39172. decl.name = name; // TODO: Clone
  39173. if (flag) {
  39174. decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
  39175. }
  39176. if (p.flags & 16777216 /* Optional */) {
  39177. decl.questionToken = ts.createToken(57 /* QuestionToken */);
  39178. }
  39179. results_1.push(ts.setTextRange(decl, sig.declaration));
  39180. }
  39181. return results_1;
  39182. }
  39183. // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
  39184. return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
  39185. };
  39186. }
  39187. function serializePropertySymbolForInterface(p, baseType) {
  39188. return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
  39189. }
  39190. function getDeclarationWithTypeAnnotation(symbol) {
  39191. return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); });
  39192. }
  39193. /**
  39194. * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
  39195. * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
  39196. */
  39197. function serializeTypeForDeclaration(type, symbol) {
  39198. var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol);
  39199. if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
  39200. // try to reuse the existing annotation
  39201. var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
  39202. var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
  39203. return transformed === existing ? ts.getMutableClone(existing) : transformed;
  39204. }
  39205. var oldFlags = context.flags;
  39206. if (type.flags & 8192 /* UniqueESSymbol */ &&
  39207. type.symbol === symbol) {
  39208. context.flags |= 1048576 /* AllowUniqueESSymbolType */;
  39209. }
  39210. var result = typeToTypeNodeHelper(type, context);
  39211. context.flags = oldFlags;
  39212. return result;
  39213. function visitExistingNodeTreeSymbols(node) {
  39214. if (ts.isJSDocAllType(node)) {
  39215. return ts.createKeywordTypeNode(125 /* AnyKeyword */);
  39216. }
  39217. if (ts.isJSDocUnknownType(node)) {
  39218. return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
  39219. }
  39220. if (ts.isJSDocNullableType(node)) {
  39221. return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
  39222. }
  39223. if (ts.isJSDocOptionalType(node)) {
  39224. return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
  39225. }
  39226. if (ts.isJSDocNonNullableType(node)) {
  39227. return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
  39228. }
  39229. if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
  39230. return ts.createTypeLiteralNode([ts.createIndexSignature(
  39231. /*decorators*/ undefined,
  39232. /*modifiers*/ undefined, [ts.createParameter(
  39233. /*decorators*/ undefined,
  39234. /*modifiers*/ undefined,
  39235. /*dotdotdotToken*/ undefined, "x",
  39236. /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
  39237. }
  39238. if (ts.isJSDocFunctionType(node)) {
  39239. if (ts.isJSDocConstructSignature(node)) {
  39240. var newTypeNode_1;
  39241. return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter(
  39242. /*decorators*/ undefined,
  39243. /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols),
  39244. /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
  39245. }
  39246. else {
  39247. return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
  39248. /*decorators*/ undefined,
  39249. /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols),
  39250. /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
  39251. }
  39252. }
  39253. if (ts.isLiteralImportTypeNode(node)) {
  39254. return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
  39255. }
  39256. if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
  39257. var leftmost = ts.getFirstIdentifier(node);
  39258. var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
  39259. if (sym) {
  39260. includePrivateSymbol(sym);
  39261. if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) {
  39262. var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context);
  39263. if (ts.idText(name) !== ts.idText(node)) {
  39264. return name;
  39265. }
  39266. return node;
  39267. }
  39268. }
  39269. }
  39270. return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
  39271. }
  39272. function rewriteModuleSpecifier(parent, lit) {
  39273. if (bundled) {
  39274. if (context.tracker && context.tracker.moduleResolverHost) {
  39275. var targetFile = getExternalModuleFileFromDeclaration(parent);
  39276. if (targetFile) {
  39277. var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
  39278. var resolverHost = {
  39279. getCanonicalFileName: getCanonicalFileName,
  39280. getCurrentDirectory: context.tracker.moduleResolverHost.getCurrentDirectory ? function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); } : function () { return ""; },
  39281. getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
  39282. };
  39283. var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
  39284. return ts.createLiteral(newName);
  39285. }
  39286. }
  39287. }
  39288. else {
  39289. if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
  39290. var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
  39291. if (moduleSym) {
  39292. context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
  39293. }
  39294. }
  39295. }
  39296. return lit;
  39297. }
  39298. }
  39299. function serializeSignatures(kind, input, baseType, outputKind) {
  39300. var signatures = getSignaturesOfType(input, kind);
  39301. if (kind === 1 /* Construct */) {
  39302. if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
  39303. return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
  39304. }
  39305. if (baseType) {
  39306. // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
  39307. var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
  39308. if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
  39309. return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
  39310. }
  39311. if (baseSigs.length === signatures.length) {
  39312. var failed = false;
  39313. for (var i = 0; i < baseSigs.length; i++) {
  39314. if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
  39315. failed = true;
  39316. break;
  39317. }
  39318. }
  39319. if (!failed) {
  39320. return []; // Every signature was identical - elide constructor list as it is inherited
  39321. }
  39322. }
  39323. }
  39324. var privateProtected = 0;
  39325. for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
  39326. var s = signatures_4[_i];
  39327. if (s.declaration) {
  39328. privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
  39329. }
  39330. }
  39331. if (privateProtected) {
  39332. return [ts.setTextRange(ts.createConstructor(
  39333. /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected),
  39334. /*parameters*/ [],
  39335. /*body*/ undefined), signatures[0].declaration)];
  39336. }
  39337. }
  39338. var results = [];
  39339. for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
  39340. var sig = signatures_5[_a];
  39341. // Each overload becomes a separate constructor declaration, in order
  39342. var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
  39343. results.push(ts.setTextRange(decl, sig.declaration));
  39344. }
  39345. return results;
  39346. }
  39347. function serializeIndexSignatures(input, baseType) {
  39348. var results = [];
  39349. for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
  39350. var type = _a[_i];
  39351. var info = getIndexInfoOfType(input, type);
  39352. if (info) {
  39353. if (baseType) {
  39354. var baseInfo = getIndexInfoOfType(baseType, type);
  39355. if (baseInfo) {
  39356. if (isTypeIdenticalTo(info.type, baseInfo.type)) {
  39357. continue; // elide identical index signatures
  39358. }
  39359. }
  39360. }
  39361. results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
  39362. }
  39363. }
  39364. return results;
  39365. }
  39366. function serializeBaseType(t, staticType, rootName) {
  39367. var ref = trySerializeAsTypeReference(t);
  39368. if (ref) {
  39369. return ref;
  39370. }
  39371. var tempName = getUnusedName(rootName + "_base");
  39372. var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
  39373. ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
  39374. ], 2 /* Const */));
  39375. addResult(statement, 0 /* None */);
  39376. return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
  39377. }
  39378. function trySerializeAsTypeReference(t) {
  39379. var typeArgs;
  39380. var reference;
  39381. // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
  39382. // which we can't write out in a syntactically valid way as an expression
  39383. if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
  39384. typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
  39385. reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
  39386. }
  39387. else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
  39388. reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
  39389. }
  39390. if (reference) {
  39391. return ts.createExpressionWithTypeArguments(typeArgs, reference);
  39392. }
  39393. }
  39394. function getUnusedName(input, symbol) {
  39395. if (symbol) {
  39396. if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
  39397. return context.remappedSymbolNames.get("" + getSymbolId(symbol));
  39398. }
  39399. }
  39400. if (symbol) {
  39401. input = getNameCandidateWorker(symbol, input);
  39402. }
  39403. var i = 0;
  39404. var original = input;
  39405. while (context.usedSymbolNames.has(input)) {
  39406. i++;
  39407. input = original + "_" + i;
  39408. }
  39409. context.usedSymbolNames.set(input, true);
  39410. if (symbol) {
  39411. context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
  39412. }
  39413. return input;
  39414. }
  39415. function getNameCandidateWorker(symbol, localName) {
  39416. if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
  39417. var flags = context.flags;
  39418. context.flags |= 16777216 /* InInitialEntityName */;
  39419. var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
  39420. context.flags = flags;
  39421. localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
  39422. }
  39423. if (localName === "default" /* Default */) {
  39424. localName = "_default";
  39425. }
  39426. else if (localName === "export=" /* ExportEquals */) {
  39427. localName = "_exports";
  39428. }
  39429. localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
  39430. return localName;
  39431. }
  39432. function getInternalSymbolName(symbol, localName) {
  39433. if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
  39434. return context.remappedSymbolNames.get("" + getSymbolId(symbol));
  39435. }
  39436. localName = getNameCandidateWorker(symbol, localName);
  39437. // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
  39438. context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
  39439. return localName;
  39440. }
  39441. }
  39442. }
  39443. function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
  39444. if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
  39445. return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
  39446. function typePredicateToStringWorker(writer) {
  39447. var predicate = ts.createTypePredicateNodeWithModifier(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.createToken(124 /* AssertsKeyword */) : undefined, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217
  39448. );
  39449. var printer = ts.createPrinter({ removeComments: true });
  39450. var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
  39451. printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
  39452. return writer;
  39453. }
  39454. }
  39455. function formatUnionTypes(types) {
  39456. var result = [];
  39457. var flags = 0;
  39458. for (var i = 0; i < types.length; i++) {
  39459. var t = types[i];
  39460. flags |= t.flags;
  39461. if (!(t.flags & 98304 /* Nullable */)) {
  39462. if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
  39463. var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
  39464. if (baseType.flags & 1048576 /* Union */) {
  39465. var count = baseType.types.length;
  39466. if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
  39467. result.push(baseType);
  39468. i += count - 1;
  39469. continue;
  39470. }
  39471. }
  39472. }
  39473. result.push(t);
  39474. }
  39475. }
  39476. if (flags & 65536 /* Null */)
  39477. result.push(nullType);
  39478. if (flags & 32768 /* Undefined */)
  39479. result.push(undefinedType);
  39480. return result || types;
  39481. }
  39482. function visibilityToString(flags) {
  39483. if (flags === 8 /* Private */) {
  39484. return "private";
  39485. }
  39486. if (flags === 16 /* Protected */) {
  39487. return "protected";
  39488. }
  39489. return "public";
  39490. }
  39491. function getTypeAliasForTypeLiteral(type) {
  39492. if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
  39493. var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
  39494. if (node.kind === 247 /* TypeAliasDeclaration */) {
  39495. return getSymbolOfNode(node);
  39496. }
  39497. }
  39498. return undefined;
  39499. }
  39500. function isTopLevelInExternalModuleAugmentation(node) {
  39501. return node && node.parent &&
  39502. node.parent.kind === 250 /* ModuleBlock */ &&
  39503. ts.isExternalModuleAugmentation(node.parent.parent);
  39504. }
  39505. function isDefaultBindingContext(location) {
  39506. return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
  39507. }
  39508. function getNameOfSymbolFromNameType(symbol, context) {
  39509. var nameType = getSymbolLinks(symbol).nameType;
  39510. if (nameType) {
  39511. if (nameType.flags & 384 /* StringOrNumberLiteral */) {
  39512. var name = "" + nameType.value;
  39513. if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
  39514. return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
  39515. }
  39516. if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
  39517. return "[" + name + "]";
  39518. }
  39519. return name;
  39520. }
  39521. if (nameType.flags & 8192 /* UniqueESSymbol */) {
  39522. return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
  39523. }
  39524. }
  39525. }
  39526. /**
  39527. * Gets a human-readable name for a symbol.
  39528. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
  39529. *
  39530. * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
  39531. * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
  39532. */
  39533. function getNameOfSymbolAsWritten(symbol, context) {
  39534. if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
  39535. // If it's not the first part of an entity name, it must print as `default`
  39536. (!(context.flags & 16777216 /* InInitialEntityName */) ||
  39537. // if the symbol is synthesized, it will only be referenced externally it must print as `default`
  39538. !symbol.declarations ||
  39539. // if not in the same binding context (source file, module declaration), it must print as `default`
  39540. (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
  39541. return "default";
  39542. }
  39543. if (symbol.declarations && symbol.declarations.length) {
  39544. var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
  39545. var name_2 = declaration && ts.getNameOfDeclaration(declaration);
  39546. if (declaration && name_2) {
  39547. if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
  39548. return ts.symbolName(symbol);
  39549. }
  39550. if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
  39551. var nameType = getSymbolLinks(symbol).nameType;
  39552. if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
  39553. // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
  39554. var result = getNameOfSymbolFromNameType(symbol, context);
  39555. if (result !== undefined) {
  39556. return result;
  39557. }
  39558. }
  39559. }
  39560. return ts.declarationNameToString(name_2);
  39561. }
  39562. if (!declaration) {
  39563. declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
  39564. }
  39565. if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
  39566. return ts.declarationNameToString(declaration.parent.name);
  39567. }
  39568. switch (declaration.kind) {
  39569. case 214 /* ClassExpression */:
  39570. case 201 /* FunctionExpression */:
  39571. case 202 /* ArrowFunction */:
  39572. if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
  39573. context.encounteredError = true;
  39574. }
  39575. return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
  39576. }
  39577. }
  39578. var name = getNameOfSymbolFromNameType(symbol, context);
  39579. return name !== undefined ? name : ts.symbolName(symbol);
  39580. }
  39581. function isDeclarationVisible(node) {
  39582. if (node) {
  39583. var links = getNodeLinks(node);
  39584. if (links.isVisible === undefined) {
  39585. links.isVisible = !!determineIfDeclarationIsVisible();
  39586. }
  39587. return links.isVisible;
  39588. }
  39589. return false;
  39590. function determineIfDeclarationIsVisible() {
  39591. switch (node.kind) {
  39592. case 314 /* JSDocCallbackTag */:
  39593. case 321 /* JSDocTypedefTag */:
  39594. case 315 /* JSDocEnumTag */:
  39595. // Top-level jsdoc type aliases are considered exported
  39596. // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
  39597. return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
  39598. case 191 /* BindingElement */:
  39599. return isDeclarationVisible(node.parent.parent);
  39600. case 242 /* VariableDeclaration */:
  39601. if (ts.isBindingPattern(node.name) &&
  39602. !node.name.elements.length) {
  39603. // If the binding pattern is empty, this variable declaration is not visible
  39604. return false;
  39605. }
  39606. // falls through
  39607. case 249 /* ModuleDeclaration */:
  39608. case 245 /* ClassDeclaration */:
  39609. case 246 /* InterfaceDeclaration */:
  39610. case 247 /* TypeAliasDeclaration */:
  39611. case 244 /* FunctionDeclaration */:
  39612. case 248 /* EnumDeclaration */:
  39613. case 253 /* ImportEqualsDeclaration */:
  39614. // external module augmentation is always visible
  39615. if (ts.isExternalModuleAugmentation(node)) {
  39616. return true;
  39617. }
  39618. var parent = getDeclarationContainer(node);
  39619. // If the node is not exported or it is not ambient module element (except import declaration)
  39620. if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
  39621. !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
  39622. return isGlobalSourceFile(parent);
  39623. }
  39624. // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
  39625. return isDeclarationVisible(parent);
  39626. case 159 /* PropertyDeclaration */:
  39627. case 158 /* PropertySignature */:
  39628. case 163 /* GetAccessor */:
  39629. case 164 /* SetAccessor */:
  39630. case 161 /* MethodDeclaration */:
  39631. case 160 /* MethodSignature */:
  39632. if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
  39633. // Private/protected properties/methods are not visible
  39634. return false;
  39635. }
  39636. // Public properties/methods are visible if its parents are visible, so:
  39637. // falls through
  39638. case 162 /* Constructor */:
  39639. case 166 /* ConstructSignature */:
  39640. case 165 /* CallSignature */:
  39641. case 167 /* IndexSignature */:
  39642. case 156 /* Parameter */:
  39643. case 250 /* ModuleBlock */:
  39644. case 170 /* FunctionType */:
  39645. case 171 /* ConstructorType */:
  39646. case 173 /* TypeLiteral */:
  39647. case 169 /* TypeReference */:
  39648. case 174 /* ArrayType */:
  39649. case 175 /* TupleType */:
  39650. case 178 /* UnionType */:
  39651. case 179 /* IntersectionType */:
  39652. case 182 /* ParenthesizedType */:
  39653. return isDeclarationVisible(node.parent);
  39654. // Default binding, import specifier and namespace import is visible
  39655. // only on demand so by default it is not visible
  39656. case 255 /* ImportClause */:
  39657. case 256 /* NamespaceImport */:
  39658. case 258 /* ImportSpecifier */:
  39659. return false;
  39660. // Type parameters are always visible
  39661. case 155 /* TypeParameter */:
  39662. // Source file and namespace export are always visible
  39663. // falls through
  39664. case 290 /* SourceFile */:
  39665. case 252 /* NamespaceExportDeclaration */:
  39666. return true;
  39667. // Export assignments do not create name bindings outside the module
  39668. case 259 /* ExportAssignment */:
  39669. return false;
  39670. default:
  39671. return false;
  39672. }
  39673. }
  39674. }
  39675. function collectLinkedAliases(node, setVisibility) {
  39676. var exportSymbol;
  39677. if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
  39678. exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
  39679. }
  39680. else if (node.parent.kind === 263 /* ExportSpecifier */) {
  39681. exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
  39682. }
  39683. var result;
  39684. var visited;
  39685. if (exportSymbol) {
  39686. visited = ts.createMap();
  39687. visited.set("" + getSymbolId(exportSymbol), true);
  39688. buildVisibleNodeList(exportSymbol.declarations);
  39689. }
  39690. return result;
  39691. function buildVisibleNodeList(declarations) {
  39692. ts.forEach(declarations, function (declaration) {
  39693. var resultNode = getAnyImportSyntax(declaration) || declaration;
  39694. if (setVisibility) {
  39695. getNodeLinks(declaration).isVisible = true;
  39696. }
  39697. else {
  39698. result = result || [];
  39699. ts.pushIfUnique(result, resultNode);
  39700. }
  39701. if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
  39702. // Add the referenced top container visible
  39703. var internalModuleReference = declaration.moduleReference;
  39704. var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
  39705. var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
  39706. var id = importSymbol && "" + getSymbolId(importSymbol);
  39707. if (importSymbol && !visited.has(id)) {
  39708. visited.set(id, true);
  39709. buildVisibleNodeList(importSymbol.declarations);
  39710. }
  39711. }
  39712. });
  39713. }
  39714. }
  39715. /**
  39716. * Push an entry on the type resolution stack. If an entry with the given target and the given property name
  39717. * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
  39718. * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
  39719. * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
  39720. * In order to see if the same query has already been done before, the target object and the propertyName both
  39721. * must match the one passed in.
  39722. *
  39723. * @param target The symbol, type, or signature whose type is being queried
  39724. * @param propertyName The property name that should be used to query the target for its type
  39725. */
  39726. function pushTypeResolution(target, propertyName) {
  39727. var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
  39728. if (resolutionCycleStartIndex >= 0) {
  39729. // A cycle was found
  39730. var length_2 = resolutionTargets.length;
  39731. for (var i = resolutionCycleStartIndex; i < length_2; i++) {
  39732. resolutionResults[i] = false;
  39733. }
  39734. return false;
  39735. }
  39736. resolutionTargets.push(target);
  39737. resolutionResults.push(/*items*/ true);
  39738. resolutionPropertyNames.push(propertyName);
  39739. return true;
  39740. }
  39741. function findResolutionCycleStartIndex(target, propertyName) {
  39742. for (var i = resolutionTargets.length - 1; i >= 0; i--) {
  39743. if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
  39744. return -1;
  39745. }
  39746. if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
  39747. return i;
  39748. }
  39749. }
  39750. return -1;
  39751. }
  39752. function hasType(target, propertyName) {
  39753. switch (propertyName) {
  39754. case 0 /* Type */:
  39755. return !!getSymbolLinks(target).type;
  39756. case 5 /* EnumTagType */:
  39757. return !!(getNodeLinks(target).resolvedEnumType);
  39758. case 2 /* DeclaredType */:
  39759. return !!getSymbolLinks(target).declaredType;
  39760. case 1 /* ResolvedBaseConstructorType */:
  39761. return !!target.resolvedBaseConstructorType;
  39762. case 3 /* ResolvedReturnType */:
  39763. return !!target.resolvedReturnType;
  39764. case 4 /* ImmediateBaseConstraint */:
  39765. return !!target.immediateBaseConstraint;
  39766. case 6 /* ResolvedTypeArguments */:
  39767. return !!target.resolvedTypeArguments;
  39768. }
  39769. return ts.Debug.assertNever(propertyName);
  39770. }
  39771. /**
  39772. * Pop an entry from the type resolution stack and return its associated result value. The result value will
  39773. * be true if no circularities were detected, or false if a circularity was found.
  39774. */
  39775. function popTypeResolution() {
  39776. resolutionTargets.pop();
  39777. resolutionPropertyNames.pop();
  39778. return resolutionResults.pop();
  39779. }
  39780. function getDeclarationContainer(node) {
  39781. return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
  39782. switch (node.kind) {
  39783. case 242 /* VariableDeclaration */:
  39784. case 243 /* VariableDeclarationList */:
  39785. case 258 /* ImportSpecifier */:
  39786. case 257 /* NamedImports */:
  39787. case 256 /* NamespaceImport */:
  39788. case 255 /* ImportClause */:
  39789. return false;
  39790. default:
  39791. return true;
  39792. }
  39793. }).parent;
  39794. }
  39795. function getTypeOfPrototypeProperty(prototype) {
  39796. // TypeScript 1.0 spec (April 2014): 8.4
  39797. // Every class automatically contains a static property member named 'prototype',
  39798. // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
  39799. // It is an error to explicitly declare a static property member with the name 'prototype'.
  39800. var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
  39801. return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
  39802. }
  39803. // Return the type of the given property in the given type, or undefined if no such property exists
  39804. function getTypeOfPropertyOfType(type, name) {
  39805. var prop = getPropertyOfType(type, name);
  39806. return prop ? getTypeOfSymbol(prop) : undefined;
  39807. }
  39808. function getTypeOfPropertyOrIndexSignature(type, name) {
  39809. return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
  39810. }
  39811. function isTypeAny(type) {
  39812. return type && (type.flags & 1 /* Any */) !== 0;
  39813. }
  39814. // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
  39815. // assigned by contextual typing.
  39816. function getTypeForBindingElementParent(node) {
  39817. var symbol = getSymbolOfNode(node);
  39818. return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
  39819. }
  39820. function isComputedNonLiteralName(name) {
  39821. return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression);
  39822. }
  39823. function getRestType(source, properties, symbol) {
  39824. source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
  39825. if (source.flags & 131072 /* Never */) {
  39826. return emptyObjectType;
  39827. }
  39828. if (source.flags & 1048576 /* Union */) {
  39829. return mapType(source, function (t) { return getRestType(t, properties, symbol); });
  39830. }
  39831. var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
  39832. if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
  39833. if (omitKeyType.flags & 131072 /* Never */) {
  39834. return source;
  39835. }
  39836. var omitTypeAlias = getGlobalOmitSymbol();
  39837. if (!omitTypeAlias) {
  39838. return errorType;
  39839. }
  39840. return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
  39841. }
  39842. var members = ts.createSymbolTable();
  39843. for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
  39844. var prop = _a[_i];
  39845. if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
  39846. && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
  39847. && isSpreadableProperty(prop)) {
  39848. members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
  39849. }
  39850. }
  39851. var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
  39852. var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
  39853. var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
  39854. result.objectFlags |= 131072 /* ObjectRestType */;
  39855. return result;
  39856. }
  39857. // Determine the control flow type associated with a destructuring declaration or assignment. The following
  39858. // forms of destructuring are possible:
  39859. // let { x } = obj; // BindingElement
  39860. // let [ x ] = obj; // BindingElement
  39861. // { x } = obj; // ShorthandPropertyAssignment
  39862. // { x: v } = obj; // PropertyAssignment
  39863. // [ x ] = obj; // Expression
  39864. // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
  39865. // flow analyzer doesn't have to handle all the different syntactic forms.
  39866. function getFlowTypeOfDestructuring(node, declaredType) {
  39867. var reference = getSyntheticElementAccess(node);
  39868. return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
  39869. }
  39870. function getSyntheticElementAccess(node) {
  39871. var parentAccess = getParentElementAccess(node);
  39872. if (parentAccess && parentAccess.flowNode) {
  39873. var propName = getDestructuringPropertyName(node);
  39874. if (propName) {
  39875. var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
  39876. result.parent = node;
  39877. result.expression = parentAccess;
  39878. var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
  39879. literal.parent = result;
  39880. literal.text = propName;
  39881. result.argumentExpression = literal;
  39882. result.flowNode = parentAccess.flowNode;
  39883. return result;
  39884. }
  39885. }
  39886. }
  39887. function getParentElementAccess(node) {
  39888. var ancestor = node.parent.parent;
  39889. switch (ancestor.kind) {
  39890. case 191 /* BindingElement */:
  39891. case 281 /* PropertyAssignment */:
  39892. return getSyntheticElementAccess(ancestor);
  39893. case 192 /* ArrayLiteralExpression */:
  39894. return getSyntheticElementAccess(node.parent);
  39895. case 242 /* VariableDeclaration */:
  39896. return ancestor.initializer;
  39897. case 209 /* BinaryExpression */:
  39898. return ancestor.right;
  39899. }
  39900. }
  39901. function getDestructuringPropertyName(node) {
  39902. var parent = node.parent;
  39903. if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
  39904. return getLiteralPropertyNameText(node.propertyName || node.name);
  39905. }
  39906. if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
  39907. return getLiteralPropertyNameText(node.name);
  39908. }
  39909. return "" + parent.elements.indexOf(node);
  39910. }
  39911. function getLiteralPropertyNameText(name) {
  39912. var type = getLiteralTypeFromPropertyName(name);
  39913. return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
  39914. }
  39915. /** Return the inferred type for a binding element */
  39916. function getTypeForBindingElement(declaration) {
  39917. var pattern = declaration.parent;
  39918. var parentType = getTypeForBindingElementParent(pattern.parent);
  39919. // If no type or an any type was inferred for parent, infer that for the binding element
  39920. if (!parentType || isTypeAny(parentType)) {
  39921. return parentType;
  39922. }
  39923. // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
  39924. if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
  39925. parentType = getNonNullableType(parentType);
  39926. }
  39927. var type;
  39928. if (pattern.kind === 189 /* ObjectBindingPattern */) {
  39929. if (declaration.dotDotDotToken) {
  39930. if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
  39931. error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
  39932. return errorType;
  39933. }
  39934. var literalMembers = [];
  39935. for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
  39936. var element = _a[_i];
  39937. if (!element.dotDotDotToken) {
  39938. literalMembers.push(element.propertyName || element.name);
  39939. }
  39940. }
  39941. type = getRestType(parentType, literalMembers, declaration.symbol);
  39942. }
  39943. else {
  39944. // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
  39945. var name = declaration.propertyName || declaration.name;
  39946. var indexType = getLiteralTypeFromPropertyName(name);
  39947. var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
  39948. type = getFlowTypeOfDestructuring(declaration, declaredType);
  39949. }
  39950. }
  39951. else {
  39952. // This elementType will be used if the specific property corresponding to this index is not
  39953. // present (aka the tuple element property). This call also checks that the parentType is in
  39954. // fact an iterable or array (depending on target language).
  39955. var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
  39956. var index_1 = pattern.elements.indexOf(declaration);
  39957. if (declaration.dotDotDotToken) {
  39958. // If the parent is a tuple type, the rest element has a tuple type of the
  39959. // remaining tuple element types. Otherwise, the rest element has an array type with same
  39960. // element type as the parent type.
  39961. type = everyType(parentType, isTupleType) ?
  39962. mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
  39963. createArrayType(elementType);
  39964. }
  39965. else if (isArrayLikeType(parentType)) {
  39966. var indexType = getLiteralType(index_1);
  39967. var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
  39968. var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
  39969. type = getFlowTypeOfDestructuring(declaration, declaredType);
  39970. }
  39971. else {
  39972. type = elementType;
  39973. }
  39974. }
  39975. if (!declaration.initializer) {
  39976. return type;
  39977. }
  39978. if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
  39979. // In strict null checking mode, if a default value of a non-undefined type is specified, remove
  39980. // undefined from the final type.
  39981. return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
  39982. getTypeWithFacts(type, 524288 /* NEUndefined */) :
  39983. type;
  39984. }
  39985. return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
  39986. }
  39987. function getTypeForDeclarationFromJSDocComment(declaration) {
  39988. var jsdocType = ts.getJSDocType(declaration);
  39989. if (jsdocType) {
  39990. return getTypeFromTypeNode(jsdocType);
  39991. }
  39992. return undefined;
  39993. }
  39994. function isNullOrUndefined(node) {
  39995. var expr = ts.skipParentheses(node);
  39996. return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
  39997. }
  39998. function isEmptyArrayLiteral(node) {
  39999. var expr = ts.skipParentheses(node);
  40000. return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
  40001. }
  40002. function addOptionality(type, optional) {
  40003. if (optional === void 0) { optional = true; }
  40004. return strictNullChecks && optional ? getOptionalType(type) : type;
  40005. }
  40006. // Return the inferred type for a variable, parameter, or property declaration
  40007. function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
  40008. // A variable declared in a for..in statement is of type string, or of type keyof T when the
  40009. // right hand expression is of a type parameter type.
  40010. if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
  40011. var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
  40012. return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
  40013. }
  40014. if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
  40015. // checkRightHandSideOfForOf will return undefined if the for-of expression type was
  40016. // missing properties/signatures required to get its iteratedType (like
  40017. // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
  40018. // or it may have led to an error inside getElementTypeOfIterable.
  40019. var forOfStatement = declaration.parent.parent;
  40020. return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType;
  40021. }
  40022. if (ts.isBindingPattern(declaration.parent)) {
  40023. return getTypeForBindingElement(declaration);
  40024. }
  40025. var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
  40026. || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
  40027. // Use type from type annotation if one is present
  40028. var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
  40029. if (declaredType) {
  40030. return addOptionality(declaredType, isOptional);
  40031. }
  40032. if ((noImplicitAny || ts.isInJSFile(declaration)) &&
  40033. declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
  40034. !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
  40035. // If --noImplicitAny is on or the declaration is in a Javascript file,
  40036. // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
  40037. // initializer or a 'null' or 'undefined' initializer.
  40038. if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
  40039. return autoType;
  40040. }
  40041. // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
  40042. // literal initializer.
  40043. if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
  40044. return autoArrayType;
  40045. }
  40046. }
  40047. if (declaration.kind === 156 /* Parameter */) {
  40048. var func = declaration.parent;
  40049. // For a parameter of a set accessor, use the type of the get accessor if one is present
  40050. if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
  40051. var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
  40052. if (getter) {
  40053. var getterSignature = getSignatureFromDeclaration(getter);
  40054. var thisParameter = getAccessorThisParameter(func);
  40055. if (thisParameter && declaration === thisParameter) {
  40056. // Use the type from the *getter*
  40057. ts.Debug.assert(!thisParameter.type);
  40058. return getTypeOfSymbol(getterSignature.thisParameter);
  40059. }
  40060. return getReturnTypeOfSignature(getterSignature);
  40061. }
  40062. }
  40063. if (ts.isInJSFile(declaration)) {
  40064. var typeTag = ts.getJSDocType(func);
  40065. if (typeTag && ts.isFunctionTypeNode(typeTag)) {
  40066. return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
  40067. }
  40068. }
  40069. // Use contextual parameter type if one is available
  40070. var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
  40071. if (type) {
  40072. return addOptionality(type, isOptional);
  40073. }
  40074. }
  40075. else if (ts.isInJSFile(declaration)) {
  40076. var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
  40077. if (containerObjectType) {
  40078. return containerObjectType;
  40079. }
  40080. }
  40081. // Use the type of the initializer expression if one is present and the declaration is
  40082. // not a parameter of a contextually typed function
  40083. if (declaration.initializer) {
  40084. var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
  40085. return addOptionality(type, isOptional);
  40086. }
  40087. if (ts.isJsxAttribute(declaration)) {
  40088. // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
  40089. // I.e <Elem attr /> is sugar for <Elem attr={true} />
  40090. return trueType;
  40091. }
  40092. // If the declaration specifies a binding pattern and is not a parameter of a contextually
  40093. // typed function, use the type implied by the binding pattern
  40094. if (ts.isBindingPattern(declaration.name)) {
  40095. return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
  40096. }
  40097. // No type specified and nothing can be inferred
  40098. return undefined;
  40099. }
  40100. function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
  40101. // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
  40102. var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
  40103. if (container) {
  40104. var tag = ts.getJSDocTypeTag(container);
  40105. if (tag && tag.typeExpression) {
  40106. return getTypeFromTypeNode(tag.typeExpression);
  40107. }
  40108. var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
  40109. return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
  40110. }
  40111. var definedInConstructor = false;
  40112. var definedInMethod = false;
  40113. var jsdocType;
  40114. var types;
  40115. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  40116. var declaration = _a[_i];
  40117. var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
  40118. ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
  40119. undefined;
  40120. if (!expression) {
  40121. continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere
  40122. }
  40123. var kind = ts.isAccessExpression(expression)
  40124. ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
  40125. : ts.getAssignmentDeclarationKind(expression);
  40126. if (kind === 4 /* ThisProperty */) {
  40127. if (isDeclarationInConstructor(expression)) {
  40128. definedInConstructor = true;
  40129. }
  40130. else {
  40131. definedInMethod = true;
  40132. }
  40133. }
  40134. if (!ts.isCallExpression(expression)) {
  40135. jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
  40136. }
  40137. if (!jsdocType) {
  40138. (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
  40139. }
  40140. }
  40141. var type = jsdocType;
  40142. if (!type) {
  40143. if (!ts.length(types)) {
  40144. return errorType; // No types from any declarations :(
  40145. }
  40146. var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
  40147. // use only the constructor types unless they were only assigned null | undefined (including widening variants)
  40148. if (definedInMethod) {
  40149. var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
  40150. if (propType) {
  40151. (constructorTypes || (constructorTypes = [])).push(propType);
  40152. definedInConstructor = true;
  40153. }
  40154. }
  40155. var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
  40156. type = getUnionType(sourceTypes, 2 /* Subtype */);
  40157. }
  40158. var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
  40159. if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
  40160. reportImplicitAny(symbol.valueDeclaration, anyType);
  40161. return anyType;
  40162. }
  40163. return widened;
  40164. }
  40165. function getJSContainerObjectType(decl, symbol, init) {
  40166. if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
  40167. return undefined;
  40168. }
  40169. var exports = ts.createSymbolTable();
  40170. while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
  40171. var s_2 = getSymbolOfNode(decl);
  40172. if (s_2 && ts.hasEntries(s_2.exports)) {
  40173. mergeSymbolTable(exports, s_2.exports);
  40174. }
  40175. decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
  40176. }
  40177. var s = getSymbolOfNode(decl);
  40178. if (s && ts.hasEntries(s.exports)) {
  40179. mergeSymbolTable(exports, s.exports);
  40180. }
  40181. var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
  40182. type.objectFlags |= 16384 /* JSLiteral */;
  40183. return type;
  40184. }
  40185. function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
  40186. var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
  40187. if (typeNode) {
  40188. var type = getWidenedType(getTypeFromTypeNode(typeNode));
  40189. if (!declaredType) {
  40190. return type;
  40191. }
  40192. else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
  40193. errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
  40194. }
  40195. }
  40196. if (symbol.parent) {
  40197. var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
  40198. if (typeNode_2) {
  40199. return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
  40200. }
  40201. }
  40202. return declaredType;
  40203. }
  40204. /** If we don't have an explicit JSDoc type, get the type from the initializer. */
  40205. function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
  40206. if (ts.isCallExpression(expression)) {
  40207. if (resolvedSymbol) {
  40208. return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
  40209. }
  40210. var objectLitType = checkExpressionCached(expression.arguments[2]);
  40211. var valueType = getTypeOfPropertyOfType(objectLitType, "value");
  40212. if (valueType) {
  40213. return valueType;
  40214. }
  40215. var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
  40216. if (getFunc) {
  40217. var getSig = getSingleCallSignature(getFunc);
  40218. if (getSig) {
  40219. return getReturnTypeOfSignature(getSig);
  40220. }
  40221. }
  40222. var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
  40223. if (setFunc) {
  40224. var setSig = getSingleCallSignature(setFunc);
  40225. if (setSig) {
  40226. return getTypeOfFirstParameterOfSignature(setSig);
  40227. }
  40228. }
  40229. return anyType;
  40230. }
  40231. var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
  40232. if (type.flags & 524288 /* Object */ &&
  40233. kind === 2 /* ModuleExports */ &&
  40234. symbol.escapedName === "export=" /* ExportEquals */) {
  40235. var exportedType_1 = resolveStructuredTypeMembers(type);
  40236. var members_4 = ts.createSymbolTable();
  40237. ts.copyEntries(exportedType_1.members, members_4);
  40238. if (resolvedSymbol && !resolvedSymbol.exports) {
  40239. resolvedSymbol.exports = ts.createSymbolTable();
  40240. }
  40241. (resolvedSymbol || symbol).exports.forEach(function (s, name) {
  40242. if (members_4.has(name)) {
  40243. var exportedMember = exportedType_1.members.get(name);
  40244. var union = createSymbol(s.flags | exportedMember.flags, name);
  40245. union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
  40246. members_4.set(name, union);
  40247. }
  40248. else {
  40249. members_4.set(name, s);
  40250. }
  40251. });
  40252. var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo);
  40253. result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
  40254. return result;
  40255. }
  40256. if (isEmptyArrayLiteralType(type)) {
  40257. reportImplicitAny(expression, anyArrayType);
  40258. return anyArrayType;
  40259. }
  40260. return type;
  40261. }
  40262. function isDeclarationInConstructor(expression) {
  40263. var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
  40264. // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
  40265. // Function expressions that are assigned to the prototype count as methods.
  40266. return thisContainer.kind === 162 /* Constructor */ ||
  40267. thisContainer.kind === 244 /* FunctionDeclaration */ ||
  40268. (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
  40269. }
  40270. function getConstructorDefinedThisAssignmentTypes(types, declarations) {
  40271. ts.Debug.assert(types.length === declarations.length);
  40272. return types.filter(function (_, i) {
  40273. var declaration = declarations[i];
  40274. var expression = ts.isBinaryExpression(declaration) ? declaration :
  40275. ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
  40276. return expression && isDeclarationInConstructor(expression);
  40277. });
  40278. }
  40279. /** check for definition in base class if any declaration is in a class */
  40280. function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
  40281. var parentDeclaration = ts.forEach(property.declarations, function (d) {
  40282. var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
  40283. return ts.isClassLike(parent) && parent;
  40284. });
  40285. if (parentDeclaration) {
  40286. var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
  40287. var baseClassType = classType && getBaseTypes(classType)[0];
  40288. if (baseClassType) {
  40289. return getTypeOfPropertyOfType(baseClassType, property.escapedName);
  40290. }
  40291. }
  40292. }
  40293. // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
  40294. // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
  40295. // pattern. Otherwise, it is the type any.
  40296. function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
  40297. if (element.initializer) {
  40298. // The type implied by a binding pattern is independent of context, so we check the initializer with no
  40299. // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
  40300. // pattern.
  40301. var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
  40302. return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
  40303. }
  40304. if (ts.isBindingPattern(element.name)) {
  40305. return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
  40306. }
  40307. if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
  40308. reportImplicitAny(element, anyType);
  40309. }
  40310. // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
  40311. // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
  40312. // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
  40313. // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
  40314. return includePatternInType ? nonInferrableAnyType : anyType;
  40315. }
  40316. // Return the type implied by an object binding pattern
  40317. function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
  40318. var members = ts.createSymbolTable();
  40319. var stringIndexInfo;
  40320. var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
  40321. ts.forEach(pattern.elements, function (e) {
  40322. var name = e.propertyName || e.name;
  40323. if (e.dotDotDotToken) {
  40324. stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
  40325. return;
  40326. }
  40327. var exprType = getLiteralTypeFromPropertyName(name);
  40328. if (!isTypeUsableAsPropertyName(exprType)) {
  40329. // do not include computed properties in the implied type
  40330. objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
  40331. return;
  40332. }
  40333. var text = getPropertyNameFromType(exprType);
  40334. var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
  40335. var symbol = createSymbol(flags, text);
  40336. symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
  40337. symbol.bindingElement = e;
  40338. members.set(symbol.escapedName, symbol);
  40339. });
  40340. var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
  40341. result.objectFlags |= objectFlags;
  40342. if (includePatternInType) {
  40343. result.pattern = pattern;
  40344. result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
  40345. }
  40346. return result;
  40347. }
  40348. // Return the type implied by an array binding pattern
  40349. function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
  40350. var elements = pattern.elements;
  40351. var lastElement = ts.lastOrUndefined(elements);
  40352. var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
  40353. if (elements.length === 0 || elements.length === 1 && hasRestElement) {
  40354. return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
  40355. }
  40356. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
  40357. var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
  40358. var result = createTupleType(elementTypes, minLength, hasRestElement);
  40359. if (includePatternInType) {
  40360. result = cloneTypeReference(result);
  40361. result.pattern = pattern;
  40362. result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
  40363. }
  40364. return result;
  40365. }
  40366. // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
  40367. // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
  40368. // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
  40369. // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
  40370. // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
  40371. // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
  40372. // the parameter.
  40373. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
  40374. if (includePatternInType === void 0) { includePatternInType = false; }
  40375. if (reportErrors === void 0) { reportErrors = false; }
  40376. return pattern.kind === 189 /* ObjectBindingPattern */
  40377. ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
  40378. : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
  40379. }
  40380. // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
  40381. // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
  40382. // is a bit more involved. For example:
  40383. //
  40384. // var [x, s = ""] = [1, "one"];
  40385. //
  40386. // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
  40387. // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
  40388. // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
  40389. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
  40390. return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
  40391. }
  40392. function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
  40393. if (type) {
  40394. if (reportErrors) {
  40395. reportErrorsFromWidening(declaration, type);
  40396. }
  40397. // always widen a 'unique symbol' type if the type was created for a different declaration.
  40398. if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
  40399. type = esSymbolType;
  40400. }
  40401. return getWidenedType(type);
  40402. }
  40403. // Rest parameters default to type any[], other parameters default to type any
  40404. type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
  40405. // Report implicit any errors unless this is a private property within an ambient declaration
  40406. if (reportErrors) {
  40407. if (!declarationBelongsToPrivateAmbientMember(declaration)) {
  40408. reportImplicitAny(declaration, type);
  40409. }
  40410. }
  40411. return type;
  40412. }
  40413. function declarationBelongsToPrivateAmbientMember(declaration) {
  40414. var root = ts.getRootDeclaration(declaration);
  40415. var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
  40416. return isPrivateWithinAmbient(memberDeclaration);
  40417. }
  40418. function tryGetTypeFromEffectiveTypeNode(declaration) {
  40419. var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
  40420. if (typeNode) {
  40421. return getTypeFromTypeNode(typeNode);
  40422. }
  40423. }
  40424. function getTypeOfVariableOrParameterOrProperty(symbol) {
  40425. var links = getSymbolLinks(symbol);
  40426. if (!links.type) {
  40427. var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
  40428. // For a contextually typed parameter it is possible that a type has already
  40429. // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
  40430. // to preserve this type.
  40431. if (!links.type) {
  40432. links.type = type;
  40433. }
  40434. }
  40435. return links.type;
  40436. }
  40437. function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
  40438. // Handle prototype property
  40439. if (symbol.flags & 4194304 /* Prototype */) {
  40440. return getTypeOfPrototypeProperty(symbol);
  40441. }
  40442. // CommonsJS require and module both have type any.
  40443. if (symbol === requireSymbol) {
  40444. return anyType;
  40445. }
  40446. if (symbol.flags & 134217728 /* ModuleExports */) {
  40447. var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
  40448. var members = ts.createSymbolTable();
  40449. members.set("exports", fileSymbol);
  40450. return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
  40451. }
  40452. // Handle catch clause variables
  40453. var declaration = symbol.valueDeclaration;
  40454. if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
  40455. return anyType;
  40456. }
  40457. // Handle export default expressions
  40458. if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
  40459. if (!declaration.statements.length) {
  40460. return emptyObjectType;
  40461. }
  40462. return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
  40463. }
  40464. // Handle variable, parameter or property
  40465. if (!pushTypeResolution(symbol, 0 /* Type */)) {
  40466. // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
  40467. if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
  40468. return getTypeOfFuncClassEnumModule(symbol);
  40469. }
  40470. return reportCircularityError(symbol);
  40471. }
  40472. var type;
  40473. if (declaration.kind === 259 /* ExportAssignment */) {
  40474. type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
  40475. }
  40476. else if (ts.isBinaryExpression(declaration) ||
  40477. (ts.isInJSFile(declaration) &&
  40478. (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
  40479. type = getWidenedTypeForAssignmentDeclaration(symbol);
  40480. }
  40481. else if (ts.isJSDocPropertyLikeTag(declaration)
  40482. || ts.isPropertyAccessExpression(declaration)
  40483. || ts.isElementAccessExpression(declaration)
  40484. || ts.isIdentifier(declaration)
  40485. || ts.isStringLiteralLike(declaration)
  40486. || ts.isNumericLiteral(declaration)
  40487. || ts.isClassDeclaration(declaration)
  40488. || ts.isFunctionDeclaration(declaration)
  40489. || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
  40490. || ts.isMethodSignature(declaration)
  40491. || ts.isSourceFile(declaration)) {
  40492. // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
  40493. if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
  40494. return getTypeOfFuncClassEnumModule(symbol);
  40495. }
  40496. type = ts.isBinaryExpression(declaration.parent) ?
  40497. getWidenedTypeForAssignmentDeclaration(symbol) :
  40498. tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
  40499. }
  40500. else if (ts.isPropertyAssignment(declaration)) {
  40501. type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
  40502. }
  40503. else if (ts.isJsxAttribute(declaration)) {
  40504. type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
  40505. }
  40506. else if (ts.isShorthandPropertyAssignment(declaration)) {
  40507. type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
  40508. }
  40509. else if (ts.isObjectLiteralMethod(declaration)) {
  40510. type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
  40511. }
  40512. else if (ts.isParameter(declaration)
  40513. || ts.isPropertyDeclaration(declaration)
  40514. || ts.isPropertySignature(declaration)
  40515. || ts.isVariableDeclaration(declaration)
  40516. || ts.isBindingElement(declaration)) {
  40517. type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
  40518. }
  40519. // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
  40520. // Re-dispatch based on valueDeclaration.kind instead.
  40521. else if (ts.isEnumDeclaration(declaration)) {
  40522. type = getTypeOfFuncClassEnumModule(symbol);
  40523. }
  40524. else if (ts.isEnumMember(declaration)) {
  40525. type = getTypeOfEnumMember(symbol);
  40526. }
  40527. else if (ts.isAccessor(declaration)) {
  40528. type = resolveTypeOfAccessors(symbol);
  40529. }
  40530. else {
  40531. return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
  40532. }
  40533. if (!popTypeResolution()) {
  40534. // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
  40535. if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
  40536. return getTypeOfFuncClassEnumModule(symbol);
  40537. }
  40538. return reportCircularityError(symbol);
  40539. }
  40540. return type;
  40541. }
  40542. function getAnnotatedAccessorTypeNode(accessor) {
  40543. if (accessor) {
  40544. if (accessor.kind === 163 /* GetAccessor */) {
  40545. var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
  40546. return getterTypeAnnotation;
  40547. }
  40548. else {
  40549. var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
  40550. return setterTypeAnnotation;
  40551. }
  40552. }
  40553. return undefined;
  40554. }
  40555. function getAnnotatedAccessorType(accessor) {
  40556. var node = getAnnotatedAccessorTypeNode(accessor);
  40557. return node && getTypeFromTypeNode(node);
  40558. }
  40559. function getAnnotatedAccessorThisParameter(accessor) {
  40560. var parameter = getAccessorThisParameter(accessor);
  40561. return parameter && parameter.symbol;
  40562. }
  40563. function getThisTypeOfDeclaration(declaration) {
  40564. return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
  40565. }
  40566. function getTypeOfAccessors(symbol) {
  40567. var links = getSymbolLinks(symbol);
  40568. return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
  40569. }
  40570. function getTypeOfAccessorsWorker(symbol) {
  40571. if (!pushTypeResolution(symbol, 0 /* Type */)) {
  40572. return errorType;
  40573. }
  40574. var type = resolveTypeOfAccessors(symbol);
  40575. if (!popTypeResolution()) {
  40576. type = anyType;
  40577. if (noImplicitAny) {
  40578. var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
  40579. error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol));
  40580. }
  40581. }
  40582. return type;
  40583. }
  40584. function resolveTypeOfAccessors(symbol) {
  40585. var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
  40586. var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
  40587. if (getter && ts.isInJSFile(getter)) {
  40588. var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
  40589. if (jsDocType) {
  40590. return jsDocType;
  40591. }
  40592. }
  40593. // First try to see if the user specified a return type on the get-accessor.
  40594. var getterReturnType = getAnnotatedAccessorType(getter);
  40595. if (getterReturnType) {
  40596. return getterReturnType;
  40597. }
  40598. else {
  40599. // If the user didn't specify a return type, try to use the set-accessor's parameter type.
  40600. var setterParameterType = getAnnotatedAccessorType(setter);
  40601. if (setterParameterType) {
  40602. return setterParameterType;
  40603. }
  40604. else {
  40605. // If there are no specified types, try to infer it from the body of the get accessor if it exists.
  40606. if (getter && getter.body) {
  40607. return getReturnTypeFromBody(getter);
  40608. }
  40609. // Otherwise, fall back to 'any'.
  40610. else {
  40611. if (setter) {
  40612. if (!isPrivateWithinAmbient(setter)) {
  40613. errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
  40614. }
  40615. }
  40616. else {
  40617. ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
  40618. if (!isPrivateWithinAmbient(getter)) {
  40619. errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
  40620. }
  40621. }
  40622. return anyType;
  40623. }
  40624. }
  40625. }
  40626. }
  40627. function getBaseTypeVariableOfClass(symbol) {
  40628. var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
  40629. return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
  40630. baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
  40631. undefined;
  40632. }
  40633. function getTypeOfFuncClassEnumModule(symbol) {
  40634. var links = getSymbolLinks(symbol);
  40635. var originalLinks = links;
  40636. if (!links.type) {
  40637. var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration);
  40638. if (jsDeclaration) {
  40639. var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
  40640. if (merged) {
  40641. // note:we overwrite links because we just cloned the symbol
  40642. symbol = links = merged;
  40643. }
  40644. }
  40645. originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
  40646. }
  40647. return links.type;
  40648. }
  40649. function getTypeOfFuncClassEnumModuleWorker(symbol) {
  40650. var declaration = symbol.valueDeclaration;
  40651. if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
  40652. return anyType;
  40653. }
  40654. else if (declaration.kind === 209 /* BinaryExpression */ ||
  40655. ts.isAccessExpression(declaration) &&
  40656. declaration.parent.kind === 209 /* BinaryExpression */) {
  40657. return getWidenedTypeForAssignmentDeclaration(symbol);
  40658. }
  40659. else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
  40660. var resolvedModule = resolveExternalModuleSymbol(symbol);
  40661. if (resolvedModule !== symbol) {
  40662. if (!pushTypeResolution(symbol, 0 /* Type */)) {
  40663. return errorType;
  40664. }
  40665. var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
  40666. var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
  40667. if (!popTypeResolution()) {
  40668. return reportCircularityError(symbol);
  40669. }
  40670. return type_1;
  40671. }
  40672. }
  40673. var type = createObjectType(16 /* Anonymous */, symbol);
  40674. if (symbol.flags & 32 /* Class */) {
  40675. var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
  40676. return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
  40677. }
  40678. else {
  40679. return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
  40680. }
  40681. }
  40682. function getTypeOfEnumMember(symbol) {
  40683. var links = getSymbolLinks(symbol);
  40684. return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
  40685. }
  40686. function getTypeOfAlias(symbol) {
  40687. var links = getSymbolLinks(symbol);
  40688. if (!links.type) {
  40689. var targetSymbol = resolveAlias(symbol);
  40690. // It only makes sense to get the type of a value symbol. If the result of resolving
  40691. // the alias is not a value, then it has no type. To get the type associated with a
  40692. // type symbol, call getDeclaredTypeOfSymbol.
  40693. // This check is important because without it, a call to getTypeOfSymbol could end
  40694. // up recursively calling getTypeOfAlias, causing a stack overflow.
  40695. links.type = targetSymbol.flags & 111551 /* Value */
  40696. ? getTypeOfSymbol(targetSymbol)
  40697. : errorType;
  40698. }
  40699. return links.type;
  40700. }
  40701. function getTypeOfInstantiatedSymbol(symbol) {
  40702. var links = getSymbolLinks(symbol);
  40703. if (!links.type) {
  40704. if (!pushTypeResolution(symbol, 0 /* Type */)) {
  40705. return links.type = errorType;
  40706. }
  40707. var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
  40708. if (!popTypeResolution()) {
  40709. type = reportCircularityError(symbol);
  40710. }
  40711. links.type = type;
  40712. }
  40713. return links.type;
  40714. }
  40715. function reportCircularityError(symbol) {
  40716. var declaration = symbol.valueDeclaration;
  40717. // Check if variable has type annotation that circularly references the variable itself
  40718. if (ts.getEffectiveTypeAnnotationNode(declaration)) {
  40719. error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
  40720. return errorType;
  40721. }
  40722. // Check if variable has initializer that circularly references the variable itself
  40723. if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
  40724. error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
  40725. }
  40726. // Circularities could also result from parameters in function expressions that end up
  40727. // having themselves as contextual types following type argument inference. In those cases
  40728. // we have already reported an implicit any error so we don't report anything here.
  40729. return anyType;
  40730. }
  40731. function getTypeOfSymbolWithDeferredType(symbol) {
  40732. var links = getSymbolLinks(symbol);
  40733. if (!links.type) {
  40734. ts.Debug.assertDefined(links.deferralParent);
  40735. ts.Debug.assertDefined(links.deferralConstituents);
  40736. links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
  40737. }
  40738. return links.type;
  40739. }
  40740. function getTypeOfSymbol(symbol) {
  40741. if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) {
  40742. return getTypeOfSymbolWithDeferredType(symbol);
  40743. }
  40744. if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
  40745. return getTypeOfInstantiatedSymbol(symbol);
  40746. }
  40747. if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) {
  40748. return getTypeOfReverseMappedSymbol(symbol);
  40749. }
  40750. if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
  40751. return getTypeOfVariableOrParameterOrProperty(symbol);
  40752. }
  40753. if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
  40754. return getTypeOfFuncClassEnumModule(symbol);
  40755. }
  40756. if (symbol.flags & 8 /* EnumMember */) {
  40757. return getTypeOfEnumMember(symbol);
  40758. }
  40759. if (symbol.flags & 98304 /* Accessor */) {
  40760. return getTypeOfAccessors(symbol);
  40761. }
  40762. if (symbol.flags & 2097152 /* Alias */) {
  40763. return getTypeOfAlias(symbol);
  40764. }
  40765. return errorType;
  40766. }
  40767. function isReferenceToType(type, target) {
  40768. return type !== undefined
  40769. && target !== undefined
  40770. && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
  40771. && type.target === target;
  40772. }
  40773. function getTargetType(type) {
  40774. return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
  40775. }
  40776. // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
  40777. function hasBaseType(type, checkBase) {
  40778. return check(type);
  40779. function check(type) {
  40780. if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
  40781. var target = getTargetType(type);
  40782. return target === checkBase || ts.some(getBaseTypes(target), check);
  40783. }
  40784. else if (type.flags & 2097152 /* Intersection */) {
  40785. return ts.some(type.types, check);
  40786. }
  40787. return false;
  40788. }
  40789. }
  40790. // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
  40791. // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
  40792. // in-place and returns the same array.
  40793. function appendTypeParameters(typeParameters, declarations) {
  40794. for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
  40795. var declaration = declarations_2[_i];
  40796. typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
  40797. }
  40798. return typeParameters;
  40799. }
  40800. // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
  40801. function getOuterTypeParameters(node, includeThisTypes) {
  40802. while (true) {
  40803. node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
  40804. if (node && ts.isBinaryExpression(node)) {
  40805. // prototype assignments get the outer type parameters of their constructor function
  40806. var assignmentKind = ts.getAssignmentDeclarationKind(node);
  40807. if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
  40808. var symbol = getSymbolOfNode(node.left);
  40809. if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
  40810. node = symbol.parent.valueDeclaration;
  40811. }
  40812. }
  40813. }
  40814. if (!node) {
  40815. return undefined;
  40816. }
  40817. switch (node.kind) {
  40818. case 245 /* ClassDeclaration */:
  40819. case 214 /* ClassExpression */:
  40820. case 246 /* InterfaceDeclaration */:
  40821. case 165 /* CallSignature */:
  40822. case 166 /* ConstructSignature */:
  40823. case 160 /* MethodSignature */:
  40824. case 170 /* FunctionType */:
  40825. case 171 /* ConstructorType */:
  40826. case 300 /* JSDocFunctionType */:
  40827. case 244 /* FunctionDeclaration */:
  40828. case 161 /* MethodDeclaration */:
  40829. case 201 /* FunctionExpression */:
  40830. case 202 /* ArrowFunction */:
  40831. case 247 /* TypeAliasDeclaration */:
  40832. case 320 /* JSDocTemplateTag */:
  40833. case 321 /* JSDocTypedefTag */:
  40834. case 315 /* JSDocEnumTag */:
  40835. case 314 /* JSDocCallbackTag */:
  40836. case 186 /* MappedType */:
  40837. case 180 /* ConditionalType */:
  40838. var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
  40839. if (node.kind === 186 /* MappedType */) {
  40840. return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
  40841. }
  40842. else if (node.kind === 180 /* ConditionalType */) {
  40843. return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
  40844. }
  40845. var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
  40846. var thisType = includeThisTypes &&
  40847. (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
  40848. getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
  40849. return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
  40850. }
  40851. }
  40852. }
  40853. // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
  40854. function getOuterTypeParametersOfClassOrInterface(symbol) {
  40855. var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
  40856. ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
  40857. return getOuterTypeParameters(declaration);
  40858. }
  40859. // The local type parameters are the combined set of type parameters from all declarations of the class,
  40860. // interface, or type alias.
  40861. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
  40862. var result;
  40863. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  40864. var node = _a[_i];
  40865. if (node.kind === 246 /* InterfaceDeclaration */ ||
  40866. node.kind === 245 /* ClassDeclaration */ ||
  40867. node.kind === 214 /* ClassExpression */ ||
  40868. isJSConstructor(node) ||
  40869. ts.isTypeAlias(node)) {
  40870. var declaration = node;
  40871. result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
  40872. }
  40873. }
  40874. return result;
  40875. }
  40876. // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
  40877. // its locally declared type parameters.
  40878. function getTypeParametersOfClassOrInterface(symbol) {
  40879. return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
  40880. }
  40881. // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
  40882. // rest parameter of type any[].
  40883. function isMixinConstructorType(type) {
  40884. var signatures = getSignaturesOfType(type, 1 /* Construct */);
  40885. if (signatures.length === 1) {
  40886. var s = signatures[0];
  40887. return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
  40888. }
  40889. return false;
  40890. }
  40891. function isConstructorType(type) {
  40892. if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
  40893. return true;
  40894. }
  40895. if (type.flags & 8650752 /* TypeVariable */) {
  40896. var constraint = getBaseConstraintOfType(type);
  40897. return !!constraint && isMixinConstructorType(constraint);
  40898. }
  40899. return false;
  40900. }
  40901. function getBaseTypeNodeOfClass(type) {
  40902. return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
  40903. }
  40904. function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
  40905. var typeArgCount = ts.length(typeArgumentNodes);
  40906. var isJavascript = ts.isInJSFile(location);
  40907. return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
  40908. }
  40909. function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
  40910. var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
  40911. var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
  40912. return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
  40913. }
  40914. /**
  40915. * The base constructor of a class can resolve to
  40916. * * undefinedType if the class has no extends clause,
  40917. * * unknownType if an error occurred during resolution of the extends expression,
  40918. * * nullType if the extends expression is the null value,
  40919. * * anyType if the extends expression has type any, or
  40920. * * an object type with at least one construct signature.
  40921. */
  40922. function getBaseConstructorTypeOfClass(type) {
  40923. if (!type.resolvedBaseConstructorType) {
  40924. var decl = type.symbol.valueDeclaration;
  40925. var extended = ts.getEffectiveBaseTypeNode(decl);
  40926. var baseTypeNode = getBaseTypeNodeOfClass(type);
  40927. if (!baseTypeNode) {
  40928. return type.resolvedBaseConstructorType = undefinedType;
  40929. }
  40930. if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
  40931. return errorType;
  40932. }
  40933. var baseConstructorType = checkExpression(baseTypeNode.expression);
  40934. if (extended && baseTypeNode !== extended) {
  40935. ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
  40936. checkExpression(extended.expression);
  40937. }
  40938. if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
  40939. // Resolving the members of a class requires us to resolve the base class of that class.
  40940. // We force resolution here such that we catch circularities now.
  40941. resolveStructuredTypeMembers(baseConstructorType);
  40942. }
  40943. if (!popTypeResolution()) {
  40944. error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
  40945. return type.resolvedBaseConstructorType = errorType;
  40946. }
  40947. if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
  40948. var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
  40949. if (baseConstructorType.flags & 262144 /* TypeParameter */) {
  40950. var constraint = getConstraintFromTypeParameter(baseConstructorType);
  40951. var ctorReturn = unknownType;
  40952. if (constraint) {
  40953. var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
  40954. if (ctorSig[0]) {
  40955. ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
  40956. }
  40957. }
  40958. ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
  40959. }
  40960. return type.resolvedBaseConstructorType = errorType;
  40961. }
  40962. type.resolvedBaseConstructorType = baseConstructorType;
  40963. }
  40964. return type.resolvedBaseConstructorType;
  40965. }
  40966. function getBaseTypes(type) {
  40967. if (!type.resolvedBaseTypes) {
  40968. if (type.objectFlags & 8 /* Tuple */) {
  40969. type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
  40970. }
  40971. else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
  40972. if (type.symbol.flags & 32 /* Class */) {
  40973. resolveBaseTypesOfClass(type);
  40974. }
  40975. if (type.symbol.flags & 64 /* Interface */) {
  40976. resolveBaseTypesOfInterface(type);
  40977. }
  40978. }
  40979. else {
  40980. ts.Debug.fail("type must be class or interface");
  40981. }
  40982. }
  40983. return type.resolvedBaseTypes;
  40984. }
  40985. function resolveBaseTypesOfClass(type) {
  40986. type.resolvedBaseTypes = ts.resolvingEmptyArray;
  40987. var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
  40988. if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
  40989. return type.resolvedBaseTypes = ts.emptyArray;
  40990. }
  40991. var baseTypeNode = getBaseTypeNodeOfClass(type);
  40992. var baseType;
  40993. var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
  40994. if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
  40995. areAllOuterTypeParametersApplied(originalBaseType)) {
  40996. // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the
  40997. // class and all return the instance type of the class. There is no need for further checks and we can apply the
  40998. // type arguments in the same manner as a type reference to get the same error reporting experience.
  40999. baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
  41000. }
  41001. else if (baseConstructorType.flags & 1 /* Any */) {
  41002. baseType = baseConstructorType;
  41003. }
  41004. else {
  41005. // The class derives from a "class-like" constructor function, check that we have at least one construct signature
  41006. // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
  41007. // we check that all instantiated signatures return the same type.
  41008. var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
  41009. if (!constructors.length) {
  41010. error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
  41011. return type.resolvedBaseTypes = ts.emptyArray;
  41012. }
  41013. baseType = getReturnTypeOfSignature(constructors[0]);
  41014. }
  41015. if (baseType === errorType) {
  41016. return type.resolvedBaseTypes = ts.emptyArray;
  41017. }
  41018. if (!isValidBaseType(baseType)) {
  41019. error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
  41020. return type.resolvedBaseTypes = ts.emptyArray;
  41021. }
  41022. if (type === baseType || hasBaseType(baseType, type)) {
  41023. error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
  41024. return type.resolvedBaseTypes = ts.emptyArray;
  41025. }
  41026. if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
  41027. // Circular reference, likely through instantiation of default parameters
  41028. // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
  41029. // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
  41030. // partial instantiation of the members without the base types fully resolved
  41031. type.members = undefined;
  41032. }
  41033. return type.resolvedBaseTypes = [baseType];
  41034. }
  41035. function areAllOuterTypeParametersApplied(type) {
  41036. // An unapplied type parameter has its symbol still the same as the matching argument symbol.
  41037. // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
  41038. var outerTypeParameters = type.outerTypeParameters;
  41039. if (outerTypeParameters) {
  41040. var last_1 = outerTypeParameters.length - 1;
  41041. var typeArguments = getTypeArguments(type);
  41042. return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
  41043. }
  41044. return true;
  41045. }
  41046. // A valid base type is `any`, an object type or intersection of object types.
  41047. function isValidBaseType(type) {
  41048. if (type.flags & 262144 /* TypeParameter */) {
  41049. var constraint = getBaseConstraintOfType(type);
  41050. if (constraint) {
  41051. return isValidBaseType(constraint);
  41052. }
  41053. }
  41054. // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
  41055. // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
  41056. return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) ||
  41057. !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType);
  41058. }
  41059. function resolveBaseTypesOfInterface(type) {
  41060. type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
  41061. for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
  41062. var declaration = _a[_i];
  41063. if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
  41064. for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
  41065. var node = _c[_b];
  41066. var baseType = getTypeFromTypeNode(node);
  41067. if (baseType !== errorType) {
  41068. if (isValidBaseType(baseType)) {
  41069. if (type !== baseType && !hasBaseType(baseType, type)) {
  41070. if (type.resolvedBaseTypes === ts.emptyArray) {
  41071. type.resolvedBaseTypes = [baseType];
  41072. }
  41073. else {
  41074. type.resolvedBaseTypes.push(baseType);
  41075. }
  41076. }
  41077. else {
  41078. error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
  41079. }
  41080. }
  41081. else {
  41082. error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
  41083. }
  41084. }
  41085. }
  41086. }
  41087. }
  41088. }
  41089. /**
  41090. * Returns true if the interface given by the symbol is free of "this" references.
  41091. *
  41092. * Specifically, the result is true if the interface itself contains no references
  41093. * to "this" in its body, if all base types are interfaces,
  41094. * and if none of the base interfaces have a "this" type.
  41095. */
  41096. function isThislessInterface(symbol) {
  41097. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  41098. var declaration = _a[_i];
  41099. if (declaration.kind === 246 /* InterfaceDeclaration */) {
  41100. if (declaration.flags & 128 /* ContainsThis */) {
  41101. return false;
  41102. }
  41103. var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
  41104. if (baseTypeNodes) {
  41105. for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
  41106. var node = baseTypeNodes_1[_b];
  41107. if (ts.isEntityNameExpression(node.expression)) {
  41108. var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
  41109. if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
  41110. return false;
  41111. }
  41112. }
  41113. }
  41114. }
  41115. }
  41116. }
  41117. return true;
  41118. }
  41119. function getDeclaredTypeOfClassOrInterface(symbol) {
  41120. var links = getSymbolLinks(symbol);
  41121. var originalLinks = links;
  41122. if (!links.declaredType) {
  41123. var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
  41124. var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
  41125. if (merged) {
  41126. // note:we overwrite links because we just cloned the symbol
  41127. symbol = links = merged;
  41128. }
  41129. var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
  41130. var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
  41131. var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  41132. // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
  41133. // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
  41134. // property types inferred from initializers and method return types inferred from return statements are very hard
  41135. // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
  41136. // "this" references.
  41137. if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
  41138. type.objectFlags |= 4 /* Reference */;
  41139. type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
  41140. type.outerTypeParameters = outerTypeParameters;
  41141. type.localTypeParameters = localTypeParameters;
  41142. type.instantiations = ts.createMap();
  41143. type.instantiations.set(getTypeListId(type.typeParameters), type);
  41144. type.target = type;
  41145. type.resolvedTypeArguments = type.typeParameters;
  41146. type.thisType = createTypeParameter(symbol);
  41147. type.thisType.isThisType = true;
  41148. type.thisType.constraint = type;
  41149. }
  41150. }
  41151. return links.declaredType;
  41152. }
  41153. function getDeclaredTypeOfTypeAlias(symbol) {
  41154. var links = getSymbolLinks(symbol);
  41155. if (!links.declaredType) {
  41156. // Note that we use the links object as the target here because the symbol object is used as the unique
  41157. // identity for resolution of the 'type' property in SymbolLinks.
  41158. if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
  41159. return errorType;
  41160. }
  41161. var declaration = ts.Debug.assertDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
  41162. var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
  41163. // If typeNode is missing, we will error in checkJSDocTypedefTag.
  41164. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
  41165. if (popTypeResolution()) {
  41166. var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  41167. if (typeParameters) {
  41168. // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
  41169. // an instantiation of the type alias with the type parameters supplied as type arguments.
  41170. links.typeParameters = typeParameters;
  41171. links.instantiations = ts.createMap();
  41172. links.instantiations.set(getTypeListId(typeParameters), type);
  41173. }
  41174. }
  41175. else {
  41176. type = errorType;
  41177. error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
  41178. }
  41179. links.declaredType = type;
  41180. }
  41181. return links.declaredType;
  41182. }
  41183. function isStringConcatExpression(expr) {
  41184. if (ts.isStringLiteralLike(expr)) {
  41185. return true;
  41186. }
  41187. else if (expr.kind === 209 /* BinaryExpression */) {
  41188. return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
  41189. }
  41190. return false;
  41191. }
  41192. function isLiteralEnumMember(member) {
  41193. var expr = member.initializer;
  41194. if (!expr) {
  41195. return !(member.flags & 8388608 /* Ambient */);
  41196. }
  41197. switch (expr.kind) {
  41198. case 10 /* StringLiteral */:
  41199. case 8 /* NumericLiteral */:
  41200. case 14 /* NoSubstitutionTemplateLiteral */:
  41201. return true;
  41202. case 207 /* PrefixUnaryExpression */:
  41203. return expr.operator === 40 /* MinusToken */ &&
  41204. expr.operand.kind === 8 /* NumericLiteral */;
  41205. case 75 /* Identifier */:
  41206. return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
  41207. case 209 /* BinaryExpression */:
  41208. return isStringConcatExpression(expr);
  41209. default:
  41210. return false;
  41211. }
  41212. }
  41213. function getEnumKind(symbol) {
  41214. var links = getSymbolLinks(symbol);
  41215. if (links.enumKind !== undefined) {
  41216. return links.enumKind;
  41217. }
  41218. var hasNonLiteralMember = false;
  41219. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  41220. var declaration = _a[_i];
  41221. if (declaration.kind === 248 /* EnumDeclaration */) {
  41222. for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
  41223. var member = _c[_b];
  41224. if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
  41225. return links.enumKind = 1 /* Literal */;
  41226. }
  41227. if (!isLiteralEnumMember(member)) {
  41228. hasNonLiteralMember = true;
  41229. }
  41230. }
  41231. }
  41232. }
  41233. return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
  41234. }
  41235. function getBaseTypeOfEnumLiteralType(type) {
  41236. return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
  41237. }
  41238. function getDeclaredTypeOfEnum(symbol) {
  41239. var links = getSymbolLinks(symbol);
  41240. if (links.declaredType) {
  41241. return links.declaredType;
  41242. }
  41243. if (getEnumKind(symbol) === 1 /* Literal */) {
  41244. enumCount++;
  41245. var memberTypeList = [];
  41246. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  41247. var declaration = _a[_i];
  41248. if (declaration.kind === 248 /* EnumDeclaration */) {
  41249. for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
  41250. var member = _c[_b];
  41251. var value = getEnumMemberValue(member);
  41252. var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
  41253. getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
  41254. memberTypeList.push(getRegularTypeOfLiteralType(memberType));
  41255. }
  41256. }
  41257. }
  41258. if (memberTypeList.length) {
  41259. var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
  41260. if (enumType_1.flags & 1048576 /* Union */) {
  41261. enumType_1.flags |= 1024 /* EnumLiteral */;
  41262. enumType_1.symbol = symbol;
  41263. }
  41264. return links.declaredType = enumType_1;
  41265. }
  41266. }
  41267. var enumType = createType(32 /* Enum */);
  41268. enumType.symbol = symbol;
  41269. return links.declaredType = enumType;
  41270. }
  41271. function getDeclaredTypeOfEnumMember(symbol) {
  41272. var links = getSymbolLinks(symbol);
  41273. if (!links.declaredType) {
  41274. var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
  41275. if (!links.declaredType) {
  41276. links.declaredType = enumType;
  41277. }
  41278. }
  41279. return links.declaredType;
  41280. }
  41281. function getDeclaredTypeOfTypeParameter(symbol) {
  41282. var links = getSymbolLinks(symbol);
  41283. return links.declaredType || (links.declaredType = createTypeParameter(symbol));
  41284. }
  41285. function getDeclaredTypeOfAlias(symbol) {
  41286. var links = getSymbolLinks(symbol);
  41287. return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
  41288. }
  41289. function getDeclaredTypeOfSymbol(symbol) {
  41290. return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
  41291. }
  41292. function tryGetDeclaredTypeOfSymbol(symbol) {
  41293. if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
  41294. return getDeclaredTypeOfClassOrInterface(symbol);
  41295. }
  41296. if (symbol.flags & 524288 /* TypeAlias */) {
  41297. return getDeclaredTypeOfTypeAlias(symbol);
  41298. }
  41299. if (symbol.flags & 262144 /* TypeParameter */) {
  41300. return getDeclaredTypeOfTypeParameter(symbol);
  41301. }
  41302. if (symbol.flags & 384 /* Enum */) {
  41303. return getDeclaredTypeOfEnum(symbol);
  41304. }
  41305. if (symbol.flags & 8 /* EnumMember */) {
  41306. return getDeclaredTypeOfEnumMember(symbol);
  41307. }
  41308. if (symbol.flags & 2097152 /* Alias */) {
  41309. return getDeclaredTypeOfAlias(symbol);
  41310. }
  41311. return undefined;
  41312. }
  41313. /**
  41314. * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
  41315. * literal type, an array with an element type that is free of this references, or a type reference that is
  41316. * free of this references.
  41317. */
  41318. function isThislessType(node) {
  41319. switch (node.kind) {
  41320. case 125 /* AnyKeyword */:
  41321. case 148 /* UnknownKeyword */:
  41322. case 143 /* StringKeyword */:
  41323. case 140 /* NumberKeyword */:
  41324. case 151 /* BigIntKeyword */:
  41325. case 128 /* BooleanKeyword */:
  41326. case 144 /* SymbolKeyword */:
  41327. case 141 /* ObjectKeyword */:
  41328. case 110 /* VoidKeyword */:
  41329. case 146 /* UndefinedKeyword */:
  41330. case 100 /* NullKeyword */:
  41331. case 137 /* NeverKeyword */:
  41332. case 187 /* LiteralType */:
  41333. return true;
  41334. case 174 /* ArrayType */:
  41335. return isThislessType(node.elementType);
  41336. case 169 /* TypeReference */:
  41337. return !node.typeArguments || node.typeArguments.every(isThislessType);
  41338. }
  41339. return false;
  41340. }
  41341. /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
  41342. function isThislessTypeParameter(node) {
  41343. var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
  41344. return !constraint || isThislessType(constraint);
  41345. }
  41346. /**
  41347. * A variable-like declaration is free of this references if it has a type annotation
  41348. * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
  41349. */
  41350. function isThislessVariableLikeDeclaration(node) {
  41351. var typeNode = ts.getEffectiveTypeAnnotationNode(node);
  41352. return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
  41353. }
  41354. /**
  41355. * A function-like declaration is considered free of `this` references if it has a return type
  41356. * annotation that is free of this references and if each parameter is thisless and if
  41357. * each type parameter (if present) is thisless.
  41358. */
  41359. function isThislessFunctionLikeDeclaration(node) {
  41360. var returnType = ts.getEffectiveReturnTypeNode(node);
  41361. var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
  41362. return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
  41363. node.parameters.every(isThislessVariableLikeDeclaration) &&
  41364. typeParameters.every(isThislessTypeParameter);
  41365. }
  41366. /**
  41367. * Returns true if the class or interface member given by the symbol is free of "this" references. The
  41368. * function may return false for symbols that are actually free of "this" references because it is not
  41369. * feasible to perform a complete analysis in all cases. In particular, property members with types
  41370. * inferred from their initializers and function members with inferred return types are conservatively
  41371. * assumed not to be free of "this" references.
  41372. */
  41373. function isThisless(symbol) {
  41374. if (symbol.declarations && symbol.declarations.length === 1) {
  41375. var declaration = symbol.declarations[0];
  41376. if (declaration) {
  41377. switch (declaration.kind) {
  41378. case 159 /* PropertyDeclaration */:
  41379. case 158 /* PropertySignature */:
  41380. return isThislessVariableLikeDeclaration(declaration);
  41381. case 161 /* MethodDeclaration */:
  41382. case 160 /* MethodSignature */:
  41383. case 162 /* Constructor */:
  41384. case 163 /* GetAccessor */:
  41385. case 164 /* SetAccessor */:
  41386. return isThislessFunctionLikeDeclaration(declaration);
  41387. }
  41388. }
  41389. }
  41390. return false;
  41391. }
  41392. // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
  41393. // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
  41394. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
  41395. var result = ts.createSymbolTable();
  41396. for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
  41397. var symbol = symbols_2[_i];
  41398. result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
  41399. }
  41400. return result;
  41401. }
  41402. function addInheritedMembers(symbols, baseSymbols) {
  41403. for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
  41404. var s = baseSymbols_1[_i];
  41405. if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
  41406. symbols.set(s.escapedName, s);
  41407. }
  41408. }
  41409. }
  41410. function isStaticPrivateIdentifierProperty(s) {
  41411. return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
  41412. }
  41413. function resolveDeclaredMembers(type) {
  41414. if (!type.declaredProperties) {
  41415. var symbol = type.symbol;
  41416. var members = getMembersOfSymbol(symbol);
  41417. type.declaredProperties = getNamedMembers(members);
  41418. // Start with signatures at empty array in case of recursive types
  41419. type.declaredCallSignatures = ts.emptyArray;
  41420. type.declaredConstructSignatures = ts.emptyArray;
  41421. type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
  41422. type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
  41423. type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
  41424. type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
  41425. }
  41426. return type;
  41427. }
  41428. /**
  41429. * Indicates whether a type can be used as a property name.
  41430. */
  41431. function isTypeUsableAsPropertyName(type) {
  41432. return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
  41433. }
  41434. /**
  41435. * Indicates whether a declaration name is definitely late-bindable.
  41436. * A declaration name is only late-bindable if:
  41437. * - It is a `ComputedPropertyName`.
  41438. * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
  41439. * `ElementAccessExpression` consisting only of these same three types of nodes.
  41440. * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
  41441. */
  41442. function isLateBindableName(node) {
  41443. if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
  41444. return false;
  41445. }
  41446. var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
  41447. return ts.isEntityNameExpression(expr)
  41448. && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
  41449. }
  41450. function isLateBoundName(name) {
  41451. return name.charCodeAt(0) === 95 /* _ */ &&
  41452. name.charCodeAt(1) === 95 /* _ */ &&
  41453. name.charCodeAt(2) === 64 /* at */;
  41454. }
  41455. /**
  41456. * Indicates whether a declaration has a late-bindable dynamic name.
  41457. */
  41458. function hasLateBindableName(node) {
  41459. var name = ts.getNameOfDeclaration(node);
  41460. return !!name && isLateBindableName(name);
  41461. }
  41462. /**
  41463. * Indicates whether a declaration has a dynamic name that cannot be late-bound.
  41464. */
  41465. function hasNonBindableDynamicName(node) {
  41466. return ts.hasDynamicName(node) && !hasLateBindableName(node);
  41467. }
  41468. /**
  41469. * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
  41470. */
  41471. function isNonBindableDynamicName(node) {
  41472. return ts.isDynamicName(node) && !isLateBindableName(node);
  41473. }
  41474. /**
  41475. * Gets the symbolic name for a member from its type.
  41476. */
  41477. function getPropertyNameFromType(type) {
  41478. if (type.flags & 8192 /* UniqueESSymbol */) {
  41479. return type.escapedName;
  41480. }
  41481. if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
  41482. return ts.escapeLeadingUnderscores("" + type.value);
  41483. }
  41484. return ts.Debug.fail();
  41485. }
  41486. /**
  41487. * Adds a declaration to a late-bound dynamic member. This performs the same function for
  41488. * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
  41489. * members.
  41490. */
  41491. function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
  41492. ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
  41493. symbol.flags |= symbolFlags;
  41494. getSymbolLinks(member.symbol).lateSymbol = symbol;
  41495. if (!symbol.declarations) {
  41496. symbol.declarations = [member];
  41497. }
  41498. else {
  41499. symbol.declarations.push(member);
  41500. }
  41501. if (symbolFlags & 111551 /* Value */) {
  41502. if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
  41503. symbol.valueDeclaration = member;
  41504. }
  41505. }
  41506. }
  41507. /**
  41508. * Performs late-binding of a dynamic member. This performs the same function for
  41509. * late-bound members that `declareSymbol` in binder.ts performs for early-bound
  41510. * members.
  41511. *
  41512. * If a symbol is a dynamic name from a computed property, we perform an additional "late"
  41513. * binding phase to attempt to resolve the name for the symbol from the type of the computed
  41514. * property's expression. If the type of the expression is a string-literal, numeric-literal,
  41515. * or unique symbol type, we can use that type as the name of the symbol.
  41516. *
  41517. * For example, given:
  41518. *
  41519. * const x = Symbol();
  41520. *
  41521. * interface I {
  41522. * [x]: number;
  41523. * }
  41524. *
  41525. * The binder gives the property `[x]: number` a special symbol with the name "__computed".
  41526. * In the late-binding phase we can type-check the expression `x` and see that it has a
  41527. * unique symbol type which we can then use as the name of the member. This allows users
  41528. * to define custom symbols that can be used in the members of an object type.
  41529. *
  41530. * @param parent The containing symbol for the member.
  41531. * @param earlySymbols The early-bound symbols of the parent.
  41532. * @param lateSymbols The late-bound symbols of the parent.
  41533. * @param decl The member to bind.
  41534. */
  41535. function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
  41536. ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
  41537. var links = getNodeLinks(decl);
  41538. if (!links.resolvedSymbol) {
  41539. // In the event we attempt to resolve the late-bound name of this member recursively,
  41540. // fall back to the early-bound name of this member.
  41541. links.resolvedSymbol = decl.symbol;
  41542. var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
  41543. var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
  41544. if (isTypeUsableAsPropertyName(type)) {
  41545. var memberName = getPropertyNameFromType(type);
  41546. var symbolFlags = decl.symbol.flags;
  41547. // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
  41548. var lateSymbol = lateSymbols.get(memberName);
  41549. if (!lateSymbol)
  41550. lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
  41551. // Report an error if a late-bound member has the same name as an early-bound member,
  41552. // or if we have another early-bound symbol declaration with the same name and
  41553. // conflicting flags.
  41554. var earlySymbol = earlySymbols && earlySymbols.get(memberName);
  41555. if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
  41556. // If we have an existing early-bound member, combine its declarations so that we can
  41557. // report an error at each declaration.
  41558. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
  41559. var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
  41560. ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
  41561. error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
  41562. lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
  41563. }
  41564. lateSymbol.nameType = type;
  41565. addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
  41566. if (lateSymbol.parent) {
  41567. ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
  41568. }
  41569. else {
  41570. lateSymbol.parent = parent;
  41571. }
  41572. return links.resolvedSymbol = lateSymbol;
  41573. }
  41574. }
  41575. return links.resolvedSymbol;
  41576. }
  41577. function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
  41578. var links = getSymbolLinks(symbol);
  41579. if (!links[resolutionKind]) {
  41580. var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
  41581. var earlySymbols = !isStatic ? symbol.members :
  41582. symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
  41583. symbol.exports;
  41584. // In the event we recursively resolve the members/exports of the symbol, we
  41585. // set the initial value of resolvedMembers/resolvedExports to the early-bound
  41586. // members/exports of the symbol.
  41587. links[resolutionKind] = earlySymbols || emptySymbols;
  41588. // fill in any as-yet-unresolved late-bound members.
  41589. var lateSymbols = ts.createSymbolTable();
  41590. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  41591. var decl = _a[_i];
  41592. var members = ts.getMembersOfDeclaration(decl);
  41593. if (members) {
  41594. for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
  41595. var member = members_5[_b];
  41596. if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
  41597. lateBindMember(symbol, earlySymbols, lateSymbols, member);
  41598. }
  41599. }
  41600. }
  41601. }
  41602. var assignments = symbol.assignmentDeclarationMembers;
  41603. if (assignments) {
  41604. var decls = ts.arrayFrom(assignments.values());
  41605. for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
  41606. var member = decls_1[_c];
  41607. var assignmentKind = ts.getAssignmentDeclarationKind(member);
  41608. var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
  41609. || assignmentKind === 4 /* ThisProperty */
  41610. || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
  41611. || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
  41612. if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
  41613. lateBindMember(symbol, earlySymbols, lateSymbols, member);
  41614. }
  41615. }
  41616. }
  41617. links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
  41618. }
  41619. return links[resolutionKind];
  41620. }
  41621. /**
  41622. * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
  41623. *
  41624. * For a description of late-binding, see `lateBindMember`.
  41625. */
  41626. function getMembersOfSymbol(symbol) {
  41627. return symbol.flags & 6256 /* LateBindingContainer */
  41628. ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
  41629. : symbol.members || emptySymbols;
  41630. }
  41631. /**
  41632. * If a symbol is the dynamic name of the member of an object type, get the late-bound
  41633. * symbol of the member.
  41634. *
  41635. * For a description of late-binding, see `lateBindMember`.
  41636. */
  41637. function getLateBoundSymbol(symbol) {
  41638. if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
  41639. var links = getSymbolLinks(symbol);
  41640. if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
  41641. // force late binding of members/exports. This will set the late-bound symbol
  41642. var parent = getMergedSymbol(symbol.parent);
  41643. if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
  41644. getExportsOfSymbol(parent);
  41645. }
  41646. else {
  41647. getMembersOfSymbol(parent);
  41648. }
  41649. }
  41650. return links.lateSymbol || (links.lateSymbol = symbol);
  41651. }
  41652. return symbol;
  41653. }
  41654. function getTypeWithThisArgument(type, thisArgument, needApparentType) {
  41655. if (ts.getObjectFlags(type) & 4 /* Reference */) {
  41656. var target = type.target;
  41657. var typeArguments = getTypeArguments(type);
  41658. if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
  41659. var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
  41660. return needApparentType ? getApparentType(ref) : ref;
  41661. }
  41662. }
  41663. else if (type.flags & 2097152 /* Intersection */) {
  41664. return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
  41665. }
  41666. return needApparentType ? getApparentType(type) : type;
  41667. }
  41668. function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
  41669. var mapper;
  41670. var members;
  41671. var callSignatures;
  41672. var constructSignatures;
  41673. var stringIndexInfo;
  41674. var numberIndexInfo;
  41675. if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
  41676. mapper = identityMapper;
  41677. members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
  41678. callSignatures = source.declaredCallSignatures;
  41679. constructSignatures = source.declaredConstructSignatures;
  41680. stringIndexInfo = source.declaredStringIndexInfo;
  41681. numberIndexInfo = source.declaredNumberIndexInfo;
  41682. }
  41683. else {
  41684. mapper = createTypeMapper(typeParameters, typeArguments);
  41685. members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
  41686. callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
  41687. constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
  41688. stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
  41689. numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
  41690. }
  41691. var baseTypes = getBaseTypes(source);
  41692. if (baseTypes.length) {
  41693. if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
  41694. members = ts.createSymbolTable(source.declaredProperties);
  41695. }
  41696. setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
  41697. var thisArgument = ts.lastOrUndefined(typeArguments);
  41698. for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
  41699. var baseType = baseTypes_1[_i];
  41700. var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
  41701. addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
  41702. callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
  41703. constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
  41704. if (!stringIndexInfo) {
  41705. stringIndexInfo = instantiatedBaseType === anyType ?
  41706. createIndexInfo(anyType, /*isReadonly*/ false) :
  41707. getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
  41708. }
  41709. numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
  41710. }
  41711. }
  41712. setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
  41713. }
  41714. function resolveClassOrInterfaceMembers(type) {
  41715. resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
  41716. }
  41717. function resolveTypeReferenceMembers(type) {
  41718. var source = resolveDeclaredMembers(type.target);
  41719. var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
  41720. var typeArguments = getTypeArguments(type);
  41721. var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
  41722. resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
  41723. }
  41724. function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
  41725. var sig = new Signature(checker, flags);
  41726. sig.declaration = declaration;
  41727. sig.typeParameters = typeParameters;
  41728. sig.parameters = parameters;
  41729. sig.thisParameter = thisParameter;
  41730. sig.resolvedReturnType = resolvedReturnType;
  41731. sig.resolvedTypePredicate = resolvedTypePredicate;
  41732. sig.minArgumentCount = minArgumentCount;
  41733. sig.target = undefined;
  41734. sig.mapper = undefined;
  41735. sig.unionSignatures = undefined;
  41736. return sig;
  41737. }
  41738. function cloneSignature(sig) {
  41739. var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
  41740. /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
  41741. result.target = sig.target;
  41742. result.mapper = sig.mapper;
  41743. result.unionSignatures = sig.unionSignatures;
  41744. return result;
  41745. }
  41746. function createUnionSignature(signature, unionSignatures) {
  41747. var result = cloneSignature(signature);
  41748. result.unionSignatures = unionSignatures;
  41749. result.target = undefined;
  41750. result.mapper = undefined;
  41751. return result;
  41752. }
  41753. function getOptionalCallSignature(signature, callChainFlags) {
  41754. if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
  41755. return signature;
  41756. }
  41757. if (!signature.optionalCallSignatureCache) {
  41758. signature.optionalCallSignatureCache = {};
  41759. }
  41760. var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
  41761. return signature.optionalCallSignatureCache[key]
  41762. || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
  41763. }
  41764. function createOptionalCallSignature(signature, callChainFlags) {
  41765. ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
  41766. var result = cloneSignature(signature);
  41767. result.flags |= callChainFlags;
  41768. return result;
  41769. }
  41770. function getExpandedParameters(sig) {
  41771. if (signatureHasRestParameter(sig)) {
  41772. var restIndex_1 = sig.parameters.length - 1;
  41773. var restParameter = sig.parameters[restIndex_1];
  41774. var restType = getTypeOfSymbol(restParameter);
  41775. if (isTupleType(restType)) {
  41776. var elementTypes = getTypeArguments(restType);
  41777. var minLength_1 = restType.target.minLength;
  41778. var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
  41779. var restParams = ts.map(elementTypes, function (t, i) {
  41780. var name = getParameterNameAtPosition(sig, restIndex_1 + i);
  41781. var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
  41782. i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
  41783. var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
  41784. symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
  41785. return symbol;
  41786. });
  41787. return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
  41788. }
  41789. }
  41790. return sig.parameters;
  41791. }
  41792. function getDefaultConstructSignatures(classType) {
  41793. var baseConstructorType = getBaseConstructorTypeOfClass(classType);
  41794. var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
  41795. if (baseSignatures.length === 0) {
  41796. return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
  41797. }
  41798. var baseTypeNode = getBaseTypeNodeOfClass(classType);
  41799. var isJavaScript = ts.isInJSFile(baseTypeNode);
  41800. var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
  41801. var typeArgCount = ts.length(typeArguments);
  41802. var result = [];
  41803. for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
  41804. var baseSig = baseSignatures_1[_i];
  41805. var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
  41806. var typeParamCount = ts.length(baseSig.typeParameters);
  41807. if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
  41808. var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
  41809. sig.typeParameters = classType.localTypeParameters;
  41810. sig.resolvedReturnType = classType;
  41811. result.push(sig);
  41812. }
  41813. }
  41814. return result;
  41815. }
  41816. function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
  41817. for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
  41818. var s = signatureList_1[_i];
  41819. if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
  41820. return s;
  41821. }
  41822. }
  41823. }
  41824. function findMatchingSignatures(signatureLists, signature, listIndex) {
  41825. if (signature.typeParameters) {
  41826. // We require an exact match for generic signatures, so we only return signatures from the first
  41827. // signature list and only if they have exact matches in the other signature lists.
  41828. if (listIndex > 0) {
  41829. return undefined;
  41830. }
  41831. for (var i = 1; i < signatureLists.length; i++) {
  41832. if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
  41833. return undefined;
  41834. }
  41835. }
  41836. return [signature];
  41837. }
  41838. var result;
  41839. for (var i = 0; i < signatureLists.length; i++) {
  41840. // Allow matching non-generic signatures to have excess parameters and different return types.
  41841. // Prefer matching this types if possible.
  41842. var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
  41843. if (!match) {
  41844. return undefined;
  41845. }
  41846. result = ts.appendIfUnique(result, match);
  41847. }
  41848. return result;
  41849. }
  41850. // The signatures of a union type are those signatures that are present in each of the constituent types.
  41851. // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
  41852. // parameters and may differ in return types. When signatures differ in return types, the resulting return
  41853. // type is the union of the constituent return types.
  41854. function getUnionSignatures(signatureLists) {
  41855. var result;
  41856. var indexWithLengthOverOne;
  41857. for (var i = 0; i < signatureLists.length; i++) {
  41858. if (signatureLists[i].length === 0)
  41859. return ts.emptyArray;
  41860. if (signatureLists[i].length > 1) {
  41861. indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
  41862. }
  41863. for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
  41864. var signature = _a[_i];
  41865. // Only process signatures with parameter lists that aren't already in the result list
  41866. if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
  41867. var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
  41868. if (unionSignatures) {
  41869. var s = signature;
  41870. // Union the result types when more than one signature matches
  41871. if (unionSignatures.length > 1) {
  41872. var thisParameter = signature.thisParameter;
  41873. var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
  41874. if (firstThisParameterOfUnionSignatures) {
  41875. var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
  41876. thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
  41877. }
  41878. s = createUnionSignature(signature, unionSignatures);
  41879. s.thisParameter = thisParameter;
  41880. }
  41881. (result || (result = [])).push(s);
  41882. }
  41883. }
  41884. }
  41885. }
  41886. if (!ts.length(result) && indexWithLengthOverOne !== -1) {
  41887. // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
  41888. // signature that handles all over them. We only do this when there are overloads in only one constituent.
  41889. // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
  41890. // signatures from the type, whose ordering would be non-obvious)
  41891. var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
  41892. var results = masterList.slice();
  41893. var _loop_8 = function (signatures) {
  41894. if (signatures !== masterList) {
  41895. var signature_1 = signatures[0];
  41896. ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
  41897. results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
  41898. if (!results) {
  41899. return "break";
  41900. }
  41901. }
  41902. };
  41903. for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
  41904. var signatures = signatureLists_1[_b];
  41905. var state_3 = _loop_8(signatures);
  41906. if (state_3 === "break")
  41907. break;
  41908. }
  41909. result = results;
  41910. }
  41911. return result || ts.emptyArray;
  41912. }
  41913. function combineUnionThisParam(left, right) {
  41914. if (!left || !right) {
  41915. return left || right;
  41916. }
  41917. // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
  41918. // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
  41919. // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
  41920. var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
  41921. return createSymbolWithType(left, thisType);
  41922. }
  41923. function combineUnionParameters(left, right) {
  41924. var leftCount = getParameterCount(left);
  41925. var rightCount = getParameterCount(right);
  41926. var longest = leftCount >= rightCount ? left : right;
  41927. var shorter = longest === left ? right : left;
  41928. var longestCount = longest === left ? leftCount : rightCount;
  41929. var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
  41930. var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
  41931. var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
  41932. for (var i = 0; i < longestCount; i++) {
  41933. var longestParamType = tryGetTypeAtPosition(longest, i);
  41934. var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
  41935. var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
  41936. var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
  41937. var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
  41938. var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
  41939. var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
  41940. var paramName = leftName === rightName ? leftName :
  41941. !leftName ? rightName :
  41942. !rightName ? leftName :
  41943. undefined;
  41944. var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
  41945. paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
  41946. params[i] = paramSymbol;
  41947. }
  41948. if (needsExtraRestElement) {
  41949. var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
  41950. restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
  41951. params[longestCount] = restParamSymbol;
  41952. }
  41953. return params;
  41954. }
  41955. function combineSignaturesOfUnionMembers(left, right) {
  41956. var declaration = left.declaration;
  41957. var params = combineUnionParameters(left, right);
  41958. var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
  41959. var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
  41960. var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params,
  41961. /*resolvedReturnType*/ undefined,
  41962. /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
  41963. result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
  41964. return result;
  41965. }
  41966. function getUnionIndexInfo(types, kind) {
  41967. var indexTypes = [];
  41968. var isAnyReadonly = false;
  41969. for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
  41970. var type = types_2[_i];
  41971. var indexInfo = getIndexInfoOfType(type, kind);
  41972. if (!indexInfo) {
  41973. return undefined;
  41974. }
  41975. indexTypes.push(indexInfo.type);
  41976. isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
  41977. }
  41978. return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
  41979. }
  41980. function resolveUnionTypeMembers(type) {
  41981. // The members and properties collections are empty for union types. To get all properties of a union
  41982. // type use getPropertiesOfType (only the language service uses this).
  41983. var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
  41984. var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
  41985. var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
  41986. var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
  41987. setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
  41988. }
  41989. function intersectTypes(type1, type2) {
  41990. return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
  41991. }
  41992. function intersectIndexInfos(info1, info2) {
  41993. return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
  41994. }
  41995. function unionSpreadIndexInfos(info1, info2) {
  41996. return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
  41997. }
  41998. function findMixins(types) {
  41999. var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
  42000. var mixinFlags = ts.map(types, isMixinConstructorType);
  42001. if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
  42002. var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
  42003. mixinFlags[firstMixinIndex] = false;
  42004. }
  42005. return mixinFlags;
  42006. }
  42007. function includeMixinType(type, types, mixinFlags, index) {
  42008. var mixedTypes = [];
  42009. for (var i = 0; i < types.length; i++) {
  42010. if (i === index) {
  42011. mixedTypes.push(type);
  42012. }
  42013. else if (mixinFlags[i]) {
  42014. mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
  42015. }
  42016. }
  42017. return getIntersectionType(mixedTypes);
  42018. }
  42019. function resolveIntersectionTypeMembers(type) {
  42020. // The members and properties collections are empty for intersection types. To get all properties of an
  42021. // intersection type use getPropertiesOfType (only the language service uses this).
  42022. var callSignatures;
  42023. var constructSignatures;
  42024. var stringIndexInfo;
  42025. var numberIndexInfo;
  42026. var types = type.types;
  42027. var mixinFlags = findMixins(types);
  42028. var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
  42029. var _loop_9 = function (i) {
  42030. var t = type.types[i];
  42031. // When an intersection type contains mixin constructor types, the construct signatures from
  42032. // those types are discarded and their return types are mixed into the return types of all
  42033. // other construct signatures in the intersection type. For example, the intersection type
  42034. // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
  42035. // 'new(s: string) => A & B'.
  42036. if (!mixinFlags[i]) {
  42037. var signatures = getSignaturesOfType(t, 1 /* Construct */);
  42038. if (signatures.length && mixinCount > 0) {
  42039. signatures = ts.map(signatures, function (s) {
  42040. var clone = cloneSignature(s);
  42041. clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
  42042. return clone;
  42043. });
  42044. }
  42045. constructSignatures = appendSignatures(constructSignatures, signatures);
  42046. }
  42047. callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
  42048. stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
  42049. numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
  42050. };
  42051. for (var i = 0; i < types.length; i++) {
  42052. _loop_9(i);
  42053. }
  42054. setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
  42055. }
  42056. function appendSignatures(signatures, newSignatures) {
  42057. var _loop_10 = function (sig) {
  42058. if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
  42059. signatures = ts.append(signatures, sig);
  42060. }
  42061. };
  42062. for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
  42063. var sig = newSignatures_1[_i];
  42064. _loop_10(sig);
  42065. }
  42066. return signatures;
  42067. }
  42068. /**
  42069. * Converts an AnonymousType to a ResolvedType.
  42070. */
  42071. function resolveAnonymousTypeMembers(type) {
  42072. var symbol = getMergedSymbol(type.symbol);
  42073. if (type.target) {
  42074. setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  42075. var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
  42076. var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
  42077. var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
  42078. var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
  42079. var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
  42080. setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
  42081. }
  42082. else if (symbol.flags & 2048 /* TypeLiteral */) {
  42083. setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  42084. var members = getMembersOfSymbol(symbol);
  42085. var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
  42086. var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
  42087. var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
  42088. var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
  42089. setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
  42090. }
  42091. else {
  42092. // Combinations of function, class, enum and module
  42093. var members = emptySymbols;
  42094. var stringIndexInfo = void 0;
  42095. if (symbol.exports) {
  42096. members = getExportsOfSymbol(symbol);
  42097. if (symbol === globalThisSymbol) {
  42098. var varsOnly_1 = ts.createMap();
  42099. members.forEach(function (p) {
  42100. if (!(p.flags & 418 /* BlockScoped */)) {
  42101. varsOnly_1.set(p.escapedName, p);
  42102. }
  42103. });
  42104. members = varsOnly_1;
  42105. }
  42106. }
  42107. setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
  42108. if (symbol.flags & 32 /* Class */) {
  42109. var classType = getDeclaredTypeOfClassOrInterface(symbol);
  42110. var baseConstructorType = getBaseConstructorTypeOfClass(classType);
  42111. if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
  42112. members = ts.createSymbolTable(getNamedMembers(members));
  42113. addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
  42114. }
  42115. else if (baseConstructorType === anyType) {
  42116. stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
  42117. }
  42118. }
  42119. var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
  42120. ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
  42121. setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
  42122. // We resolve the members before computing the signatures because a signature may use
  42123. // typeof with a qualified name expression that circularly references the type we are
  42124. // in the process of resolving (see issue #6072). The temporarily empty signature list
  42125. // will never be observed because a qualified name can't reference signatures.
  42126. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
  42127. type.callSignatures = getSignaturesOfSymbol(symbol);
  42128. }
  42129. // And likewise for construct signatures for classes
  42130. if (symbol.flags & 32 /* Class */) {
  42131. var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
  42132. var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
  42133. if (symbol.flags & 16 /* Function */) {
  42134. constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
  42135. createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
  42136. undefined; }));
  42137. }
  42138. if (!constructSignatures.length) {
  42139. constructSignatures = getDefaultConstructSignatures(classType_1);
  42140. }
  42141. type.constructSignatures = constructSignatures;
  42142. }
  42143. }
  42144. }
  42145. function resolveReverseMappedTypeMembers(type) {
  42146. var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
  42147. var modifiers = getMappedTypeModifiers(type.mappedType);
  42148. var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
  42149. var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
  42150. var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
  42151. var members = ts.createSymbolTable();
  42152. for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
  42153. var prop = _a[_i];
  42154. var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
  42155. var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
  42156. inferredProp.declarations = prop.declarations;
  42157. inferredProp.nameType = getSymbolLinks(prop).nameType;
  42158. inferredProp.propertyType = getTypeOfSymbol(prop);
  42159. inferredProp.mappedType = type.mappedType;
  42160. inferredProp.constraintType = type.constraintType;
  42161. members.set(prop.escapedName, inferredProp);
  42162. }
  42163. setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
  42164. }
  42165. // Return the lower bound of the key type in a mapped type. Intuitively, the lower
  42166. // bound includes those keys that are known to always be present, for example because
  42167. // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
  42168. function getLowerBoundOfKeyType(type) {
  42169. if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
  42170. return type;
  42171. }
  42172. if (type.flags & 4194304 /* Index */) {
  42173. return getIndexType(getApparentType(type.type));
  42174. }
  42175. if (type.flags & 16777216 /* Conditional */) {
  42176. if (type.root.isDistributive) {
  42177. var checkType = type.checkType;
  42178. var constraint = getLowerBoundOfKeyType(checkType);
  42179. if (constraint !== checkType) {
  42180. var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
  42181. return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
  42182. }
  42183. }
  42184. return type;
  42185. }
  42186. if (type.flags & 1048576 /* Union */) {
  42187. return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
  42188. }
  42189. if (type.flags & 2097152 /* Intersection */) {
  42190. return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
  42191. }
  42192. return neverType;
  42193. }
  42194. /** Resolve the members of a mapped type { [P in K]: T } */
  42195. function resolveMappedTypeMembers(type) {
  42196. var members = ts.createSymbolTable();
  42197. var stringIndexInfo;
  42198. var numberIndexInfo;
  42199. // Resolve upfront such that recursive references see an empty object type.
  42200. setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  42201. // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
  42202. // and T as the template type.
  42203. var typeParameter = getTypeParameterFromMappedType(type);
  42204. var constraintType = getConstraintTypeFromMappedType(type);
  42205. var templateType = getTemplateTypeFromMappedType(type.target || type);
  42206. var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
  42207. var templateModifiers = getMappedTypeModifiers(type);
  42208. var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
  42209. if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
  42210. // We have a { [P in keyof T]: X }
  42211. for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
  42212. var prop = _a[_i];
  42213. addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
  42214. }
  42215. if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
  42216. addMemberForKeyType(stringType);
  42217. }
  42218. if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
  42219. addMemberForKeyType(numberType);
  42220. }
  42221. }
  42222. else {
  42223. forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
  42224. }
  42225. setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
  42226. function addMemberForKeyType(t) {
  42227. // Create a mapper from T to the current iteration type constituent. Then, if the
  42228. // mapped type is itself an instantiated type, combine the iteration mapper with the
  42229. // instantiation mapper.
  42230. var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
  42231. var propType = instantiateType(templateType, templateMapper);
  42232. // If the current iteration type constituent is a string literal type, create a property.
  42233. // Otherwise, for type string create a string index signature.
  42234. if (isTypeUsableAsPropertyName(t)) {
  42235. var propName = getPropertyNameFromType(t);
  42236. var modifiersProp = getPropertyOfType(modifiersType, propName);
  42237. var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
  42238. !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
  42239. var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
  42240. !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
  42241. var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0);
  42242. // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
  42243. // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
  42244. // mode, if the underlying property is optional we remove 'undefined' from the type.
  42245. prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) :
  42246. strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
  42247. propType;
  42248. if (modifiersProp) {
  42249. prop.syntheticOrigin = modifiersProp;
  42250. prop.declarations = modifiersProp.declarations;
  42251. }
  42252. prop.nameType = t;
  42253. members.set(propName, prop);
  42254. }
  42255. else if (t.flags & (1 /* Any */ | 4 /* String */)) {
  42256. stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
  42257. }
  42258. else if (t.flags & (8 /* Number */ | 32 /* Enum */)) {
  42259. numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
  42260. }
  42261. }
  42262. }
  42263. function getTypeParameterFromMappedType(type) {
  42264. return type.typeParameter ||
  42265. (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
  42266. }
  42267. function getConstraintTypeFromMappedType(type) {
  42268. return type.constraintType ||
  42269. (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
  42270. }
  42271. function getTemplateTypeFromMappedType(type) {
  42272. return type.templateType ||
  42273. (type.templateType = type.declaration.type ?
  42274. instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
  42275. errorType);
  42276. }
  42277. function getConstraintDeclarationForMappedType(type) {
  42278. return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
  42279. }
  42280. function isMappedTypeWithKeyofConstraintDeclaration(type) {
  42281. var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
  42282. return constraintDeclaration.kind === 184 /* TypeOperator */ &&
  42283. constraintDeclaration.operator === 134 /* KeyOfKeyword */;
  42284. }
  42285. function getModifiersTypeFromMappedType(type) {
  42286. if (!type.modifiersType) {
  42287. if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
  42288. // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
  42289. // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
  42290. // 'keyof T' to a literal union type and we can't recover T from that type.
  42291. type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
  42292. }
  42293. else {
  42294. // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
  42295. // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
  42296. // the modifiers type is T. Otherwise, the modifiers type is unknown.
  42297. var declaredType = getTypeFromMappedTypeNode(type.declaration);
  42298. var constraint = getConstraintTypeFromMappedType(declaredType);
  42299. var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
  42300. type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : unknownType;
  42301. }
  42302. }
  42303. return type.modifiersType;
  42304. }
  42305. function getMappedTypeModifiers(type) {
  42306. var declaration = type.declaration;
  42307. return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
  42308. (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
  42309. }
  42310. function getMappedTypeOptionality(type) {
  42311. var modifiers = getMappedTypeModifiers(type);
  42312. return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
  42313. }
  42314. function getCombinedMappedTypeOptionality(type) {
  42315. var optionality = getMappedTypeOptionality(type);
  42316. var modifiersType = getModifiersTypeFromMappedType(type);
  42317. return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
  42318. }
  42319. function isPartialMappedType(type) {
  42320. return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
  42321. }
  42322. function isGenericMappedType(type) {
  42323. return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
  42324. }
  42325. function resolveStructuredTypeMembers(type) {
  42326. if (!type.members) {
  42327. if (type.flags & 524288 /* Object */) {
  42328. if (type.objectFlags & 4 /* Reference */) {
  42329. resolveTypeReferenceMembers(type);
  42330. }
  42331. else if (type.objectFlags & 3 /* ClassOrInterface */) {
  42332. resolveClassOrInterfaceMembers(type);
  42333. }
  42334. else if (type.objectFlags & 2048 /* ReverseMapped */) {
  42335. resolveReverseMappedTypeMembers(type);
  42336. }
  42337. else if (type.objectFlags & 16 /* Anonymous */) {
  42338. resolveAnonymousTypeMembers(type);
  42339. }
  42340. else if (type.objectFlags & 32 /* Mapped */) {
  42341. resolveMappedTypeMembers(type);
  42342. }
  42343. }
  42344. else if (type.flags & 1048576 /* Union */) {
  42345. resolveUnionTypeMembers(type);
  42346. }
  42347. else if (type.flags & 2097152 /* Intersection */) {
  42348. resolveIntersectionTypeMembers(type);
  42349. }
  42350. }
  42351. return type;
  42352. }
  42353. /** Return properties of an object type or an empty array for other types */
  42354. function getPropertiesOfObjectType(type) {
  42355. if (type.flags & 524288 /* Object */) {
  42356. return resolveStructuredTypeMembers(type).properties;
  42357. }
  42358. return ts.emptyArray;
  42359. }
  42360. /** If the given type is an object type and that type has a property by the given name,
  42361. * return the symbol for that property. Otherwise return undefined.
  42362. */
  42363. function getPropertyOfObjectType(type, name) {
  42364. if (type.flags & 524288 /* Object */) {
  42365. var resolved = resolveStructuredTypeMembers(type);
  42366. var symbol = resolved.members.get(name);
  42367. if (symbol && symbolIsValue(symbol)) {
  42368. return symbol;
  42369. }
  42370. }
  42371. }
  42372. function getPropertiesOfUnionOrIntersectionType(type) {
  42373. if (!type.resolvedProperties) {
  42374. var members = ts.createSymbolTable();
  42375. for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
  42376. var current = _a[_i];
  42377. for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
  42378. var prop = _c[_b];
  42379. if (!members.has(prop.escapedName)) {
  42380. var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
  42381. if (combinedProp) {
  42382. members.set(prop.escapedName, combinedProp);
  42383. }
  42384. }
  42385. }
  42386. // The properties of a union type are those that are present in all constituent types, so
  42387. // we only need to check the properties of the first type
  42388. if (type.flags & 1048576 /* Union */) {
  42389. break;
  42390. }
  42391. }
  42392. type.resolvedProperties = getNamedMembers(members);
  42393. }
  42394. return type.resolvedProperties;
  42395. }
  42396. function getPropertiesOfType(type) {
  42397. type = getApparentType(type);
  42398. return type.flags & 3145728 /* UnionOrIntersection */ ?
  42399. getPropertiesOfUnionOrIntersectionType(type) :
  42400. getPropertiesOfObjectType(type);
  42401. }
  42402. function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
  42403. var list = obj.properties;
  42404. return list.some(function (property) {
  42405. var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
  42406. var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
  42407. var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
  42408. return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
  42409. });
  42410. }
  42411. function getAllPossiblePropertiesOfTypes(types) {
  42412. var unionType = getUnionType(types);
  42413. if (!(unionType.flags & 1048576 /* Union */)) {
  42414. return getAugmentedPropertiesOfType(unionType);
  42415. }
  42416. var props = ts.createSymbolTable();
  42417. for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
  42418. var memberType = types_3[_i];
  42419. for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
  42420. var escapedName = _b[_a].escapedName;
  42421. if (!props.has(escapedName)) {
  42422. var prop = createUnionOrIntersectionProperty(unionType, escapedName);
  42423. // May be undefined if the property is private
  42424. if (prop)
  42425. props.set(escapedName, prop);
  42426. }
  42427. }
  42428. }
  42429. return ts.arrayFrom(props.values());
  42430. }
  42431. function getConstraintOfType(type) {
  42432. return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
  42433. type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
  42434. type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
  42435. getBaseConstraintOfType(type);
  42436. }
  42437. function getConstraintOfTypeParameter(typeParameter) {
  42438. return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
  42439. }
  42440. function getConstraintOfIndexedAccess(type) {
  42441. return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
  42442. }
  42443. function getSimplifiedTypeOrConstraint(type) {
  42444. var simplified = getSimplifiedType(type, /*writing*/ false);
  42445. return simplified !== type ? simplified : getConstraintOfType(type);
  42446. }
  42447. function getConstraintFromIndexedAccess(type) {
  42448. var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
  42449. if (indexConstraint && indexConstraint !== type.indexType) {
  42450. var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
  42451. if (indexedAccess) {
  42452. return indexedAccess;
  42453. }
  42454. }
  42455. var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
  42456. if (objectConstraint && objectConstraint !== type.objectType) {
  42457. return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
  42458. }
  42459. return undefined;
  42460. }
  42461. function getDefaultConstraintOfConditionalType(type) {
  42462. if (!type.resolvedDefaultConstraint) {
  42463. // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
  42464. // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
  42465. // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
  42466. // in effect treating `any` like `never` rather than `unknown` in this location.
  42467. var trueConstraint = getInferredTrueTypeFromConditionalType(type);
  42468. var falseConstraint = getFalseTypeFromConditionalType(type);
  42469. type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
  42470. }
  42471. return type.resolvedDefaultConstraint;
  42472. }
  42473. function getConstraintOfDistributiveConditionalType(type) {
  42474. // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
  42475. // type parameter. If so, create an instantiation of the conditional type where T is replaced
  42476. // with its constraint. We do this because if the constraint is a union type it will be distributed
  42477. // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
  42478. // removes 'undefined' from T.
  42479. // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
  42480. // as the constraint for all type params (check type included) have been replace with `unknown`, which
  42481. // is going to produce even more false positive/negative results than the distribute constraint already does.
  42482. // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
  42483. // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
  42484. // likely doesn't need to exist.
  42485. if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
  42486. var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
  42487. var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
  42488. if (constraint && constraint !== type.checkType) {
  42489. var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
  42490. var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
  42491. if (!(instantiated.flags & 131072 /* Never */)) {
  42492. return instantiated;
  42493. }
  42494. }
  42495. }
  42496. return undefined;
  42497. }
  42498. function getConstraintFromConditionalType(type) {
  42499. return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
  42500. }
  42501. function getConstraintOfConditionalType(type) {
  42502. return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
  42503. }
  42504. function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
  42505. var constraints;
  42506. var hasDisjointDomainType = false;
  42507. for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
  42508. var t = types_4[_i];
  42509. if (t.flags & 63176704 /* Instantiable */) {
  42510. // We keep following constraints as long as we have an instantiable type that is known
  42511. // not to be circular or infinite (hence we stop on index access types).
  42512. var constraint = getConstraintOfType(t);
  42513. while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
  42514. constraint = getConstraintOfType(constraint);
  42515. }
  42516. if (constraint) {
  42517. constraints = ts.append(constraints, constraint);
  42518. if (targetIsUnion) {
  42519. constraints = ts.append(constraints, t);
  42520. }
  42521. }
  42522. }
  42523. else if (t.flags & 67238908 /* DisjointDomains */) {
  42524. hasDisjointDomainType = true;
  42525. }
  42526. }
  42527. // If the target is a union type or if we are intersecting with types belonging to one of the
  42528. // disjoint domains, we may end up producing a constraint that hasn't been examined before.
  42529. if (constraints && (targetIsUnion || hasDisjointDomainType)) {
  42530. if (hasDisjointDomainType) {
  42531. // We add any types belong to one of the disjoint domains because they might cause the final
  42532. // intersection operation to reduce the union constraints.
  42533. for (var _a = 0, types_5 = types; _a < types_5.length; _a++) {
  42534. var t = types_5[_a];
  42535. if (t.flags & 67238908 /* DisjointDomains */) {
  42536. constraints = ts.append(constraints, t);
  42537. }
  42538. }
  42539. }
  42540. return getIntersectionType(constraints);
  42541. }
  42542. return undefined;
  42543. }
  42544. function getBaseConstraintOfType(type) {
  42545. if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
  42546. var constraint = getResolvedBaseConstraint(type);
  42547. return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
  42548. }
  42549. return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
  42550. }
  42551. /**
  42552. * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
  42553. * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
  42554. */
  42555. function getBaseConstraintOrType(type) {
  42556. return getBaseConstraintOfType(type) || type;
  42557. }
  42558. function hasNonCircularBaseConstraint(type) {
  42559. return getResolvedBaseConstraint(type) !== circularConstraintType;
  42560. }
  42561. /**
  42562. * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
  42563. * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
  42564. * circularly references the type variable.
  42565. */
  42566. function getResolvedBaseConstraint(type) {
  42567. var nonTerminating = false;
  42568. return type.resolvedBaseConstraint ||
  42569. (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
  42570. function getImmediateBaseConstraint(t) {
  42571. if (!t.immediateBaseConstraint) {
  42572. if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
  42573. return circularConstraintType;
  42574. }
  42575. if (constraintDepth >= 50) {
  42576. // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
  42577. // very high likelihood we're dealing with an infinite generic type that perpetually generates
  42578. // new type identities as we descend into it. We stop the recursion here and mark this type
  42579. // and the outer types as having circular constraints.
  42580. error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
  42581. nonTerminating = true;
  42582. return t.immediateBaseConstraint = noConstraintType;
  42583. }
  42584. constraintDepth++;
  42585. var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
  42586. constraintDepth--;
  42587. if (!popTypeResolution()) {
  42588. if (t.flags & 262144 /* TypeParameter */) {
  42589. var errorNode = getConstraintDeclaration(t);
  42590. if (errorNode) {
  42591. var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
  42592. if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
  42593. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
  42594. }
  42595. }
  42596. }
  42597. result = circularConstraintType;
  42598. }
  42599. if (nonTerminating) {
  42600. result = circularConstraintType;
  42601. }
  42602. t.immediateBaseConstraint = result || noConstraintType;
  42603. }
  42604. return t.immediateBaseConstraint;
  42605. }
  42606. function getBaseConstraint(t) {
  42607. var c = getImmediateBaseConstraint(t);
  42608. return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
  42609. }
  42610. function computeBaseConstraint(t) {
  42611. if (t.flags & 262144 /* TypeParameter */) {
  42612. var constraint = getConstraintFromTypeParameter(t);
  42613. return t.isThisType || !constraint ?
  42614. constraint :
  42615. getBaseConstraint(constraint);
  42616. }
  42617. if (t.flags & 3145728 /* UnionOrIntersection */) {
  42618. var types = t.types;
  42619. var baseTypes = [];
  42620. for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
  42621. var type_2 = types_6[_i];
  42622. var baseType = getBaseConstraint(type_2);
  42623. if (baseType) {
  42624. baseTypes.push(baseType);
  42625. }
  42626. }
  42627. return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
  42628. t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
  42629. undefined;
  42630. }
  42631. if (t.flags & 4194304 /* Index */) {
  42632. return keyofConstraintType;
  42633. }
  42634. if (t.flags & 8388608 /* IndexedAccess */) {
  42635. var baseObjectType = getBaseConstraint(t.objectType);
  42636. var baseIndexType = getBaseConstraint(t.indexType);
  42637. var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
  42638. return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
  42639. }
  42640. if (t.flags & 16777216 /* Conditional */) {
  42641. var constraint = getConstraintFromConditionalType(t);
  42642. constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
  42643. var result = constraint && getBaseConstraint(constraint);
  42644. constraintDepth--;
  42645. return result;
  42646. }
  42647. if (t.flags & 33554432 /* Substitution */) {
  42648. return getBaseConstraint(t.substitute);
  42649. }
  42650. return t;
  42651. }
  42652. }
  42653. function getApparentTypeOfIntersectionType(type) {
  42654. return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
  42655. }
  42656. function getResolvedTypeParameterDefault(typeParameter) {
  42657. if (!typeParameter.default) {
  42658. if (typeParameter.target) {
  42659. var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
  42660. typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
  42661. }
  42662. else {
  42663. // To block recursion, set the initial value to the resolvingDefaultType.
  42664. typeParameter.default = resolvingDefaultType;
  42665. var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
  42666. var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
  42667. if (typeParameter.default === resolvingDefaultType) {
  42668. // If we have not been called recursively, set the correct default type.
  42669. typeParameter.default = defaultType;
  42670. }
  42671. }
  42672. }
  42673. else if (typeParameter.default === resolvingDefaultType) {
  42674. // If we are called recursively for this type parameter, mark the default as circular.
  42675. typeParameter.default = circularConstraintType;
  42676. }
  42677. return typeParameter.default;
  42678. }
  42679. /**
  42680. * Gets the default type for a type parameter.
  42681. *
  42682. * If the type parameter is the result of an instantiation, this gets the instantiated
  42683. * default type of its target. If the type parameter has no default type or the default is
  42684. * circular, `undefined` is returned.
  42685. */
  42686. function getDefaultFromTypeParameter(typeParameter) {
  42687. var defaultType = getResolvedTypeParameterDefault(typeParameter);
  42688. return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
  42689. }
  42690. function hasNonCircularTypeParameterDefault(typeParameter) {
  42691. return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
  42692. }
  42693. /**
  42694. * Indicates whether the declaration of a typeParameter has a default type.
  42695. */
  42696. function hasTypeParameterDefault(typeParameter) {
  42697. return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
  42698. }
  42699. function getApparentTypeOfMappedType(type) {
  42700. return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
  42701. }
  42702. function getResolvedApparentTypeOfMappedType(type) {
  42703. var typeVariable = getHomomorphicTypeVariable(type);
  42704. if (typeVariable) {
  42705. var constraint = getConstraintOfTypeParameter(typeVariable);
  42706. if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
  42707. var mapper = makeUnaryTypeMapper(typeVariable, constraint);
  42708. return instantiateType(type, combineTypeMappers(mapper, type.mapper));
  42709. }
  42710. }
  42711. return type;
  42712. }
  42713. /**
  42714. * For a type parameter, return the base constraint of the type parameter. For the string, number,
  42715. * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
  42716. * type itself. Note that the apparent type of a union type is the union type itself.
  42717. */
  42718. function getApparentType(type) {
  42719. var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
  42720. return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
  42721. t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
  42722. t.flags & 132 /* StringLike */ ? globalStringType :
  42723. t.flags & 296 /* NumberLike */ ? globalNumberType :
  42724. t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 99 /* ESNext */) :
  42725. t.flags & 528 /* BooleanLike */ ? globalBooleanType :
  42726. t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
  42727. t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
  42728. t.flags & 4194304 /* Index */ ? keyofConstraintType :
  42729. t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
  42730. t;
  42731. }
  42732. function createUnionOrIntersectionProperty(containingType, name) {
  42733. var propSet = ts.createMap();
  42734. var indexTypes;
  42735. var isUnion = containingType.flags & 1048576 /* Union */;
  42736. var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
  42737. // Flags we want to propagate to the result if they exist in all source symbols
  42738. var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
  42739. var syntheticFlag = 4 /* SyntheticMethod */;
  42740. var checkFlags = 0;
  42741. for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
  42742. var current = _a[_i];
  42743. var type = getApparentType(current);
  42744. if (type !== errorType) {
  42745. var prop = getPropertyOfType(type, name);
  42746. var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
  42747. if (prop && !(modifiers & excludeModifiers)) {
  42748. if (isUnion) {
  42749. optionalFlag |= (prop.flags & 16777216 /* Optional */);
  42750. }
  42751. else {
  42752. optionalFlag &= prop.flags;
  42753. }
  42754. var id = "" + getSymbolId(prop);
  42755. if (!propSet.has(id)) {
  42756. propSet.set(id, prop);
  42757. }
  42758. checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
  42759. (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
  42760. (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
  42761. (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
  42762. (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
  42763. if (!isPrototypeProperty(prop)) {
  42764. syntheticFlag = 2 /* SyntheticProperty */;
  42765. }
  42766. }
  42767. else if (isUnion) {
  42768. var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
  42769. if (indexInfo) {
  42770. checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
  42771. indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
  42772. }
  42773. else if (isObjectLiteralType(type)) {
  42774. checkFlags |= 32 /* WritePartial */;
  42775. indexTypes = ts.append(indexTypes, undefinedType);
  42776. }
  42777. else {
  42778. checkFlags |= 16 /* ReadPartial */;
  42779. }
  42780. }
  42781. }
  42782. }
  42783. if (!propSet.size) {
  42784. return undefined;
  42785. }
  42786. var props = ts.arrayFrom(propSet.values());
  42787. if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
  42788. return props[0];
  42789. }
  42790. var declarations;
  42791. var firstType;
  42792. var nameType;
  42793. var propTypes = [];
  42794. var firstValueDeclaration;
  42795. var hasNonUniformValueDeclaration = false;
  42796. for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
  42797. var prop = props_1[_b];
  42798. if (!firstValueDeclaration) {
  42799. firstValueDeclaration = prop.valueDeclaration;
  42800. }
  42801. else if (prop.valueDeclaration !== firstValueDeclaration) {
  42802. hasNonUniformValueDeclaration = true;
  42803. }
  42804. declarations = ts.addRange(declarations, prop.declarations);
  42805. var type = getTypeOfSymbol(prop);
  42806. if (!firstType) {
  42807. firstType = type;
  42808. nameType = getSymbolLinks(prop).nameType;
  42809. }
  42810. else if (type !== firstType) {
  42811. checkFlags |= 64 /* HasNonUniformType */;
  42812. }
  42813. if (isLiteralType(type)) {
  42814. checkFlags |= 128 /* HasLiteralType */;
  42815. }
  42816. propTypes.push(type);
  42817. }
  42818. ts.addRange(propTypes, indexTypes);
  42819. var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
  42820. result.containingType = containingType;
  42821. if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
  42822. result.valueDeclaration = firstValueDeclaration;
  42823. // Inherit information about parent type.
  42824. if (firstValueDeclaration.symbol.parent) {
  42825. result.parent = firstValueDeclaration.symbol.parent;
  42826. }
  42827. }
  42828. result.declarations = declarations;
  42829. result.nameType = nameType;
  42830. if (propTypes.length > 2) {
  42831. // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
  42832. result.checkFlags |= 65536 /* DeferredType */;
  42833. result.deferralParent = containingType;
  42834. result.deferralConstituents = propTypes;
  42835. }
  42836. else {
  42837. result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
  42838. }
  42839. return result;
  42840. }
  42841. // Return the symbol for a given property in a union or intersection type, or undefined if the property
  42842. // does not exist in any constituent type. Note that the returned property may only be present in some
  42843. // constituents, in which case the isPartial flag is set when the containing type is union type. We need
  42844. // these partial properties when identifying discriminant properties, but otherwise they are filtered out
  42845. // and do not appear to be present in the union type.
  42846. function getUnionOrIntersectionProperty(type, name) {
  42847. var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
  42848. var property = properties.get(name);
  42849. if (!property) {
  42850. property = createUnionOrIntersectionProperty(type, name);
  42851. if (property) {
  42852. properties.set(name, property);
  42853. }
  42854. }
  42855. return property;
  42856. }
  42857. function getPropertyOfUnionOrIntersectionType(type, name) {
  42858. var property = getUnionOrIntersectionProperty(type, name);
  42859. // We need to filter out partial properties in union types
  42860. return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
  42861. }
  42862. /**
  42863. * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
  42864. * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
  42865. * Object and Function as appropriate.
  42866. *
  42867. * @param type a type to look up property from
  42868. * @param name a name of property to look up in a given type
  42869. */
  42870. function getPropertyOfType(type, name) {
  42871. type = getApparentType(type);
  42872. if (type.flags & 524288 /* Object */) {
  42873. var resolved = resolveStructuredTypeMembers(type);
  42874. var symbol = resolved.members.get(name);
  42875. if (symbol && symbolIsValue(symbol)) {
  42876. return symbol;
  42877. }
  42878. var functionType = resolved === anyFunctionType ? globalFunctionType :
  42879. resolved.callSignatures.length ? globalCallableFunctionType :
  42880. resolved.constructSignatures.length ? globalNewableFunctionType :
  42881. undefined;
  42882. if (functionType) {
  42883. var symbol_1 = getPropertyOfObjectType(functionType, name);
  42884. if (symbol_1) {
  42885. return symbol_1;
  42886. }
  42887. }
  42888. return getPropertyOfObjectType(globalObjectType, name);
  42889. }
  42890. if (type.flags & 3145728 /* UnionOrIntersection */) {
  42891. return getPropertyOfUnionOrIntersectionType(type, name);
  42892. }
  42893. return undefined;
  42894. }
  42895. function getSignaturesOfStructuredType(type, kind) {
  42896. if (type.flags & 3670016 /* StructuredType */) {
  42897. var resolved = resolveStructuredTypeMembers(type);
  42898. return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
  42899. }
  42900. return ts.emptyArray;
  42901. }
  42902. /**
  42903. * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
  42904. * maps primitive types and type parameters are to their apparent types.
  42905. */
  42906. function getSignaturesOfType(type, kind) {
  42907. return getSignaturesOfStructuredType(getApparentType(type), kind);
  42908. }
  42909. function getIndexInfoOfStructuredType(type, kind) {
  42910. if (type.flags & 3670016 /* StructuredType */) {
  42911. var resolved = resolveStructuredTypeMembers(type);
  42912. return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
  42913. }
  42914. }
  42915. function getIndexTypeOfStructuredType(type, kind) {
  42916. var info = getIndexInfoOfStructuredType(type, kind);
  42917. return info && info.type;
  42918. }
  42919. // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
  42920. // maps primitive types and type parameters are to their apparent types.
  42921. function getIndexInfoOfType(type, kind) {
  42922. return getIndexInfoOfStructuredType(getApparentType(type), kind);
  42923. }
  42924. // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
  42925. // maps primitive types and type parameters are to their apparent types.
  42926. function getIndexTypeOfType(type, kind) {
  42927. return getIndexTypeOfStructuredType(getApparentType(type), kind);
  42928. }
  42929. function getImplicitIndexTypeOfType(type, kind) {
  42930. if (isObjectTypeWithInferableIndex(type)) {
  42931. var propTypes = [];
  42932. for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
  42933. var prop = _a[_i];
  42934. if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
  42935. propTypes.push(getTypeOfSymbol(prop));
  42936. }
  42937. }
  42938. if (kind === 0 /* String */) {
  42939. ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
  42940. }
  42941. if (propTypes.length) {
  42942. return getUnionType(propTypes, 2 /* Subtype */);
  42943. }
  42944. }
  42945. return undefined;
  42946. }
  42947. // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
  42948. // type checking functions).
  42949. function getTypeParametersFromDeclaration(declaration) {
  42950. var result;
  42951. for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
  42952. var node = _a[_i];
  42953. result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
  42954. }
  42955. return result;
  42956. }
  42957. function symbolsToArray(symbols) {
  42958. var result = [];
  42959. symbols.forEach(function (symbol, id) {
  42960. if (!isReservedMemberName(id)) {
  42961. result.push(symbol);
  42962. }
  42963. });
  42964. return result;
  42965. }
  42966. function isJSDocOptionalParameter(node) {
  42967. return ts.isInJSFile(node) && (
  42968. // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
  42969. node.type && node.type.kind === 299 /* JSDocOptionalType */
  42970. || ts.getJSDocParameterTags(node).some(function (_a) {
  42971. var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
  42972. return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
  42973. }));
  42974. }
  42975. function tryFindAmbientModule(moduleName, withAugmentations) {
  42976. if (ts.isExternalModuleNameRelative(moduleName)) {
  42977. return undefined;
  42978. }
  42979. var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
  42980. // merged symbol is module declaration symbol combined with all augmentations
  42981. return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
  42982. }
  42983. function isOptionalParameter(node) {
  42984. if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
  42985. return true;
  42986. }
  42987. if (node.initializer) {
  42988. var signature = getSignatureFromDeclaration(node.parent);
  42989. var parameterIndex = node.parent.parameters.indexOf(node);
  42990. ts.Debug.assert(parameterIndex >= 0);
  42991. return parameterIndex >= getMinArgumentCount(signature);
  42992. }
  42993. var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
  42994. if (iife) {
  42995. return !node.type &&
  42996. !node.dotDotDotToken &&
  42997. node.parent.parameters.indexOf(node) >= iife.arguments.length;
  42998. }
  42999. return false;
  43000. }
  43001. function isOptionalJSDocParameterTag(node) {
  43002. if (!ts.isJSDocParameterTag(node)) {
  43003. return false;
  43004. }
  43005. var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
  43006. return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
  43007. }
  43008. function createTypePredicate(kind, parameterName, parameterIndex, type) {
  43009. return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
  43010. }
  43011. /**
  43012. * Gets the minimum number of type arguments needed to satisfy all non-optional type
  43013. * parameters.
  43014. */
  43015. function getMinTypeArgumentCount(typeParameters) {
  43016. var minTypeArgumentCount = 0;
  43017. if (typeParameters) {
  43018. for (var i = 0; i < typeParameters.length; i++) {
  43019. if (!hasTypeParameterDefault(typeParameters[i])) {
  43020. minTypeArgumentCount = i + 1;
  43021. }
  43022. }
  43023. }
  43024. return minTypeArgumentCount;
  43025. }
  43026. function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
  43027. var numTypeParameters = ts.length(typeParameters);
  43028. if (!numTypeParameters) {
  43029. return [];
  43030. }
  43031. var numTypeArguments = ts.length(typeArguments);
  43032. if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
  43033. var result = typeArguments ? typeArguments.slice() : [];
  43034. // Map invalid forward references in default types to the error type
  43035. for (var i = numTypeArguments; i < numTypeParameters; i++) {
  43036. result[i] = errorType;
  43037. }
  43038. var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
  43039. for (var i = numTypeArguments; i < numTypeParameters; i++) {
  43040. var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
  43041. if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
  43042. defaultType = anyType;
  43043. }
  43044. result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
  43045. }
  43046. result.length = typeParameters.length;
  43047. return result;
  43048. }
  43049. return typeArguments && typeArguments.slice();
  43050. }
  43051. function getSignatureFromDeclaration(declaration) {
  43052. var links = getNodeLinks(declaration);
  43053. if (!links.resolvedSignature) {
  43054. var parameters = [];
  43055. var flags = 0 /* None */;
  43056. var minArgumentCount = 0;
  43057. var thisParameter = void 0;
  43058. var hasThisParameter = false;
  43059. var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
  43060. var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
  43061. var isUntypedSignatureInJSFile = !iife &&
  43062. ts.isInJSFile(declaration) &&
  43063. ts.isValueSignatureDeclaration(declaration) &&
  43064. !ts.hasJSDocParameterTags(declaration) &&
  43065. !ts.getJSDocType(declaration);
  43066. // If this is a JSDoc construct signature, then skip the first parameter in the
  43067. // parameter list. The first parameter represents the return type of the construct
  43068. // signature.
  43069. for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
  43070. var param = declaration.parameters[i];
  43071. var paramSymbol = param.symbol;
  43072. var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
  43073. // Include parameter symbol instead of property symbol in the signature
  43074. if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
  43075. var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
  43076. paramSymbol = resolvedSymbol;
  43077. }
  43078. if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
  43079. hasThisParameter = true;
  43080. thisParameter = param.symbol;
  43081. }
  43082. else {
  43083. parameters.push(paramSymbol);
  43084. }
  43085. if (type && type.kind === 187 /* LiteralType */) {
  43086. flags |= 2 /* HasLiteralTypes */;
  43087. }
  43088. // Record a new minimum argument count if this is not an optional parameter
  43089. var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
  43090. param.initializer || param.questionToken || param.dotDotDotToken ||
  43091. iife && parameters.length > iife.arguments.length && !type ||
  43092. isUntypedSignatureInJSFile ||
  43093. isJSDocOptionalParameter(param);
  43094. if (!isOptionalParameter_1) {
  43095. minArgumentCount = parameters.length;
  43096. }
  43097. }
  43098. // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
  43099. if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
  43100. !hasNonBindableDynamicName(declaration) &&
  43101. (!hasThisParameter || !thisParameter)) {
  43102. var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
  43103. var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
  43104. if (other) {
  43105. thisParameter = getAnnotatedAccessorThisParameter(other);
  43106. }
  43107. }
  43108. var classType = declaration.kind === 162 /* Constructor */ ?
  43109. getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
  43110. : undefined;
  43111. var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
  43112. if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
  43113. flags |= 1 /* HasRestParameter */;
  43114. }
  43115. links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters,
  43116. /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
  43117. }
  43118. return links.resolvedSignature;
  43119. }
  43120. /**
  43121. * A JS function gets a synthetic rest parameter if it references `arguments` AND:
  43122. * 1. It has no parameters but at least one `@param` with a type that starts with `...`
  43123. * OR
  43124. * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
  43125. */
  43126. function maybeAddJsSyntheticRestParameter(declaration, parameters) {
  43127. if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
  43128. return false;
  43129. }
  43130. var lastParam = ts.lastOrUndefined(declaration.parameters);
  43131. var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
  43132. var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
  43133. return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
  43134. });
  43135. var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
  43136. syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
  43137. if (lastParamVariadicType) {
  43138. // Replace the last parameter with a rest parameter.
  43139. parameters.pop();
  43140. }
  43141. parameters.push(syntheticArgsSymbol);
  43142. return true;
  43143. }
  43144. function getSignatureOfTypeTag(node) {
  43145. var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
  43146. var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
  43147. return signature && getErasedSignature(signature);
  43148. }
  43149. function getReturnTypeOfTypeTag(node) {
  43150. var signature = getSignatureOfTypeTag(node);
  43151. return signature && getReturnTypeOfSignature(signature);
  43152. }
  43153. function containsArgumentsReference(declaration) {
  43154. var links = getNodeLinks(declaration);
  43155. if (links.containsArgumentsReference === undefined) {
  43156. if (links.flags & 8192 /* CaptureArguments */) {
  43157. links.containsArgumentsReference = true;
  43158. }
  43159. else {
  43160. links.containsArgumentsReference = traverse(declaration.body);
  43161. }
  43162. }
  43163. return links.containsArgumentsReference;
  43164. function traverse(node) {
  43165. if (!node)
  43166. return false;
  43167. switch (node.kind) {
  43168. case 75 /* Identifier */:
  43169. return node.escapedText === "arguments" && ts.isExpressionNode(node);
  43170. case 159 /* PropertyDeclaration */:
  43171. case 161 /* MethodDeclaration */:
  43172. case 163 /* GetAccessor */:
  43173. case 164 /* SetAccessor */:
  43174. return node.name.kind === 154 /* ComputedPropertyName */
  43175. && traverse(node.name);
  43176. default:
  43177. return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
  43178. }
  43179. }
  43180. }
  43181. function getSignaturesOfSymbol(symbol) {
  43182. if (!symbol)
  43183. return ts.emptyArray;
  43184. var result = [];
  43185. for (var i = 0; i < symbol.declarations.length; i++) {
  43186. var decl = symbol.declarations[i];
  43187. if (!ts.isFunctionLike(decl))
  43188. continue;
  43189. // Don't include signature if node is the implementation of an overloaded function. A node is considered
  43190. // an implementation node if it has a body and the previous node is of the same kind and immediately
  43191. // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
  43192. if (i > 0 && decl.body) {
  43193. var previous = symbol.declarations[i - 1];
  43194. if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
  43195. continue;
  43196. }
  43197. }
  43198. result.push(getSignatureFromDeclaration(decl));
  43199. }
  43200. return result;
  43201. }
  43202. function resolveExternalModuleTypeByLiteral(name) {
  43203. var moduleSym = resolveExternalModuleName(name, name);
  43204. if (moduleSym) {
  43205. var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
  43206. if (resolvedModuleSymbol) {
  43207. return getTypeOfSymbol(resolvedModuleSymbol);
  43208. }
  43209. }
  43210. return anyType;
  43211. }
  43212. function getThisTypeOfSignature(signature) {
  43213. if (signature.thisParameter) {
  43214. return getTypeOfSymbol(signature.thisParameter);
  43215. }
  43216. }
  43217. function getTypePredicateOfSignature(signature) {
  43218. if (!signature.resolvedTypePredicate) {
  43219. if (signature.target) {
  43220. var targetTypePredicate = getTypePredicateOfSignature(signature.target);
  43221. signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
  43222. }
  43223. else if (signature.unionSignatures) {
  43224. signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
  43225. }
  43226. else {
  43227. var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
  43228. var jsdocPredicate = void 0;
  43229. if (!type && ts.isInJSFile(signature.declaration)) {
  43230. var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
  43231. if (jsdocSignature && signature !== jsdocSignature) {
  43232. jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
  43233. }
  43234. }
  43235. signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
  43236. createTypePredicateFromTypePredicateNode(type, signature) :
  43237. jsdocPredicate || noTypePredicate;
  43238. }
  43239. ts.Debug.assert(!!signature.resolvedTypePredicate);
  43240. }
  43241. return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
  43242. }
  43243. function createTypePredicateFromTypePredicateNode(node, signature) {
  43244. var parameterName = node.parameterName;
  43245. var type = node.type && getTypeFromTypeNode(node.type);
  43246. return parameterName.kind === 183 /* ThisType */ ?
  43247. createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
  43248. createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
  43249. }
  43250. function getReturnTypeOfSignature(signature) {
  43251. if (!signature.resolvedReturnType) {
  43252. if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
  43253. return errorType;
  43254. }
  43255. var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
  43256. signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
  43257. getReturnTypeFromAnnotation(signature.declaration) ||
  43258. (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
  43259. if (signature.flags & 4 /* IsInnerCallChain */) {
  43260. type = addOptionalTypeMarker(type);
  43261. }
  43262. else if (signature.flags & 8 /* IsOuterCallChain */) {
  43263. type = getOptionalType(type);
  43264. }
  43265. if (!popTypeResolution()) {
  43266. if (signature.declaration) {
  43267. var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
  43268. if (typeNode) {
  43269. error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
  43270. }
  43271. else if (noImplicitAny) {
  43272. var declaration = signature.declaration;
  43273. var name = ts.getNameOfDeclaration(declaration);
  43274. if (name) {
  43275. error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name));
  43276. }
  43277. else {
  43278. error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions);
  43279. }
  43280. }
  43281. }
  43282. type = anyType;
  43283. }
  43284. signature.resolvedReturnType = type;
  43285. }
  43286. return signature.resolvedReturnType;
  43287. }
  43288. function getReturnTypeFromAnnotation(declaration) {
  43289. if (declaration.kind === 162 /* Constructor */) {
  43290. return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
  43291. }
  43292. if (ts.isJSDocConstructSignature(declaration)) {
  43293. return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
  43294. }
  43295. var typeNode = ts.getEffectiveReturnTypeNode(declaration);
  43296. if (typeNode) {
  43297. return getTypeFromTypeNode(typeNode);
  43298. }
  43299. if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
  43300. var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
  43301. if (jsDocType) {
  43302. return jsDocType;
  43303. }
  43304. var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
  43305. var setterType = getAnnotatedAccessorType(setter);
  43306. if (setterType) {
  43307. return setterType;
  43308. }
  43309. }
  43310. return getReturnTypeOfTypeTag(declaration);
  43311. }
  43312. function isResolvingReturnTypeOfSignature(signature) {
  43313. return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
  43314. }
  43315. function getRestTypeOfSignature(signature) {
  43316. return tryGetRestTypeOfSignature(signature) || anyType;
  43317. }
  43318. function tryGetRestTypeOfSignature(signature) {
  43319. if (signatureHasRestParameter(signature)) {
  43320. var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
  43321. var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
  43322. return restType && getIndexTypeOfType(restType, 1 /* Number */);
  43323. }
  43324. return undefined;
  43325. }
  43326. function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
  43327. var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
  43328. if (inferredTypeParameters) {
  43329. var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
  43330. if (returnSignature) {
  43331. var newReturnSignature = cloneSignature(returnSignature);
  43332. newReturnSignature.typeParameters = inferredTypeParameters;
  43333. var newInstantiatedSignature = cloneSignature(instantiatedSignature);
  43334. newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
  43335. return newInstantiatedSignature;
  43336. }
  43337. }
  43338. return instantiatedSignature;
  43339. }
  43340. function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
  43341. var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
  43342. var id = getTypeListId(typeArguments);
  43343. var instantiation = instantiations.get(id);
  43344. if (!instantiation) {
  43345. instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
  43346. }
  43347. return instantiation;
  43348. }
  43349. function createSignatureInstantiation(signature, typeArguments) {
  43350. return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
  43351. }
  43352. function createSignatureTypeMapper(signature, typeArguments) {
  43353. return createTypeMapper(signature.typeParameters, typeArguments);
  43354. }
  43355. function getErasedSignature(signature) {
  43356. return signature.typeParameters ?
  43357. signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
  43358. signature;
  43359. }
  43360. function createErasedSignature(signature) {
  43361. // Create an instantiation of the signature where all type arguments are the any type.
  43362. return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
  43363. }
  43364. function getCanonicalSignature(signature) {
  43365. return signature.typeParameters ?
  43366. signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
  43367. signature;
  43368. }
  43369. function createCanonicalSignature(signature) {
  43370. // Create an instantiation of the signature where each unconstrained type parameter is replaced with
  43371. // its original. When a generic class or interface is instantiated, each generic method in the class or
  43372. // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
  43373. // where different generations of the same type parameter are in scope). This leads to a lot of new type
  43374. // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
  43375. // that uses the original type identities for all unconstrained type parameters.
  43376. return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
  43377. }
  43378. function getBaseSignature(signature) {
  43379. var typeParameters = signature.typeParameters;
  43380. if (typeParameters) {
  43381. var typeEraser_1 = createTypeEraser(typeParameters);
  43382. var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
  43383. return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
  43384. }
  43385. return signature;
  43386. }
  43387. function getOrCreateTypeFromSignature(signature) {
  43388. // There are two ways to declare a construct signature, one is by declaring a class constructor
  43389. // using the constructor keyword, and the other is declaring a bare construct signature in an
  43390. // object type literal or interface (using the new keyword). Each way of declaring a constructor
  43391. // will result in a different declaration kind.
  43392. if (!signature.isolatedSignatureType) {
  43393. var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
  43394. var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
  43395. var type = createObjectType(16 /* Anonymous */);
  43396. type.members = emptySymbols;
  43397. type.properties = ts.emptyArray;
  43398. type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
  43399. type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
  43400. signature.isolatedSignatureType = type;
  43401. }
  43402. return signature.isolatedSignatureType;
  43403. }
  43404. function getIndexSymbol(symbol) {
  43405. return symbol.members.get("__index" /* Index */);
  43406. }
  43407. function getIndexDeclarationOfSymbol(symbol, kind) {
  43408. var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
  43409. var indexSymbol = getIndexSymbol(symbol);
  43410. if (indexSymbol) {
  43411. for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
  43412. var decl = _a[_i];
  43413. var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
  43414. if (node.parameters.length === 1) {
  43415. var parameter = node.parameters[0];
  43416. if (parameter.type && parameter.type.kind === syntaxKind) {
  43417. return node;
  43418. }
  43419. }
  43420. }
  43421. }
  43422. return undefined;
  43423. }
  43424. function createIndexInfo(type, isReadonly, declaration) {
  43425. return { type: type, isReadonly: isReadonly, declaration: declaration };
  43426. }
  43427. function getIndexInfoOfSymbol(symbol, kind) {
  43428. var declaration = getIndexDeclarationOfSymbol(symbol, kind);
  43429. if (declaration) {
  43430. return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
  43431. }
  43432. return undefined;
  43433. }
  43434. function getConstraintDeclaration(type) {
  43435. return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
  43436. }
  43437. function getInferredTypeParameterConstraint(typeParameter) {
  43438. var inferences;
  43439. if (typeParameter.symbol) {
  43440. for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
  43441. var declaration = _a[_i];
  43442. if (declaration.parent.kind === 181 /* InferType */) {
  43443. // When an 'infer T' declaration is immediately contained in a type reference node
  43444. // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
  43445. // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
  43446. // present, we form an intersection of the inferred constraint types.
  43447. var grandParent = declaration.parent.parent;
  43448. if (grandParent.kind === 169 /* TypeReference */) {
  43449. var typeReference = grandParent;
  43450. var typeParameters = getTypeParametersForTypeReference(typeReference);
  43451. if (typeParameters) {
  43452. var index = typeReference.typeArguments.indexOf(declaration.parent);
  43453. if (index < typeParameters.length) {
  43454. var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
  43455. if (declaredConstraint) {
  43456. // Type parameter constraints can reference other type parameters so
  43457. // constraints need to be instantiated. If instantiation produces the
  43458. // type parameter itself, we discard that inference. For example, in
  43459. // type Foo<T extends string, U extends T> = [T, U];
  43460. // type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
  43461. // the instantiated constraint for U is X, so we discard that inference.
  43462. var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
  43463. var constraint = instantiateType(declaredConstraint, mapper);
  43464. if (constraint !== typeParameter) {
  43465. inferences = ts.append(inferences, constraint);
  43466. }
  43467. }
  43468. }
  43469. }
  43470. }
  43471. // When an 'infer T' declaration is immediately contained in a rest parameter
  43472. // declaration, we infer an 'unknown[]' constraint.
  43473. else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
  43474. inferences = ts.append(inferences, createArrayType(unknownType));
  43475. }
  43476. }
  43477. }
  43478. }
  43479. return inferences && getIntersectionType(inferences);
  43480. }
  43481. /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
  43482. function getConstraintFromTypeParameter(typeParameter) {
  43483. if (!typeParameter.constraint) {
  43484. if (typeParameter.target) {
  43485. var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
  43486. typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
  43487. }
  43488. else {
  43489. var constraintDeclaration = getConstraintDeclaration(typeParameter);
  43490. typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) :
  43491. getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
  43492. }
  43493. }
  43494. return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
  43495. }
  43496. function getParentSymbolOfTypeParameter(typeParameter) {
  43497. var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
  43498. var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
  43499. return host && getSymbolOfNode(host);
  43500. }
  43501. function getTypeListId(types) {
  43502. var result = "";
  43503. if (types) {
  43504. var length_3 = types.length;
  43505. var i = 0;
  43506. while (i < length_3) {
  43507. var startId = types[i].id;
  43508. var count = 1;
  43509. while (i + count < length_3 && types[i + count].id === startId + count) {
  43510. count++;
  43511. }
  43512. if (result.length) {
  43513. result += ",";
  43514. }
  43515. result += startId;
  43516. if (count > 1) {
  43517. result += ":" + count;
  43518. }
  43519. i += count;
  43520. }
  43521. }
  43522. return result;
  43523. }
  43524. // This function is used to propagate certain flags when creating new object type references and union types.
  43525. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
  43526. // of an object literal or the anyFunctionType. This is because there are operations in the type checker
  43527. // that care about the presence of such types at arbitrary depth in a containing type.
  43528. function getPropagatingFlagsOfTypes(types, excludeKinds) {
  43529. var result = 0;
  43530. for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
  43531. var type = types_7[_i];
  43532. if (!(type.flags & excludeKinds)) {
  43533. result |= ts.getObjectFlags(type);
  43534. }
  43535. }
  43536. return result & 3670016 /* PropagatingFlags */;
  43537. }
  43538. function createTypeReference(target, typeArguments) {
  43539. var id = getTypeListId(typeArguments);
  43540. var type = target.instantiations.get(id);
  43541. if (!type) {
  43542. type = createObjectType(4 /* Reference */, target.symbol);
  43543. target.instantiations.set(id, type);
  43544. type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
  43545. type.target = target;
  43546. type.resolvedTypeArguments = typeArguments;
  43547. }
  43548. return type;
  43549. }
  43550. function cloneTypeReference(source) {
  43551. var type = createType(source.flags);
  43552. type.symbol = source.symbol;
  43553. type.objectFlags = source.objectFlags;
  43554. type.target = source.target;
  43555. type.resolvedTypeArguments = source.resolvedTypeArguments;
  43556. return type;
  43557. }
  43558. function createDeferredTypeReference(target, node, mapper) {
  43559. var aliasSymbol = getAliasSymbolForTypeNode(node);
  43560. var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
  43561. var type = createObjectType(4 /* Reference */, target.symbol);
  43562. type.target = target;
  43563. type.node = node;
  43564. type.mapper = mapper;
  43565. type.aliasSymbol = aliasSymbol;
  43566. type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
  43567. return type;
  43568. }
  43569. function getTypeArguments(type) {
  43570. var _a, _b;
  43571. if (!type.resolvedTypeArguments) {
  43572. if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
  43573. return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
  43574. }
  43575. var node = type.node;
  43576. var typeArguments = !node ? ts.emptyArray :
  43577. node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
  43578. node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
  43579. ts.map(node.elementTypes, getTypeFromTypeNode);
  43580. if (popTypeResolution()) {
  43581. type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
  43582. }
  43583. else {
  43584. type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
  43585. error(type.node || currentNode, type.target.symbol
  43586. ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
  43587. : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
  43588. }
  43589. }
  43590. return type.resolvedTypeArguments;
  43591. }
  43592. function getTypeReferenceArity(type) {
  43593. return ts.length(type.target.typeParameters);
  43594. }
  43595. /**
  43596. * Get type from type-reference that reference to class or interface
  43597. */
  43598. function getTypeFromClassOrInterfaceReference(node, symbol) {
  43599. var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
  43600. var typeParameters = type.localTypeParameters;
  43601. if (typeParameters) {
  43602. var numTypeArguments = ts.length(node.typeArguments);
  43603. var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
  43604. var isJs = ts.isInJSFile(node);
  43605. var isJsImplicitAny = !noImplicitAny && isJs;
  43606. if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
  43607. var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
  43608. var diag = minTypeArgumentCount === typeParameters.length ?
  43609. missingAugmentsTag ?
  43610. ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
  43611. ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
  43612. missingAugmentsTag ?
  43613. ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
  43614. ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
  43615. var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
  43616. error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
  43617. if (!isJs) {
  43618. // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
  43619. return errorType;
  43620. }
  43621. }
  43622. if (node.kind === 169 /* TypeReference */ && isAliasedType(node)) {
  43623. return createDeferredTypeReference(type, node, /*mapper*/ undefined);
  43624. }
  43625. // In a type reference, the outer type parameters of the referenced class or interface are automatically
  43626. // supplied as type arguments and the type reference only specifies arguments for the local type parameters
  43627. // of the class or interface.
  43628. var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
  43629. return createTypeReference(type, typeArguments);
  43630. }
  43631. return checkNoTypeArguments(node, symbol) ? type : errorType;
  43632. }
  43633. function getTypeAliasInstantiation(symbol, typeArguments) {
  43634. var type = getDeclaredTypeOfSymbol(symbol);
  43635. var links = getSymbolLinks(symbol);
  43636. var typeParameters = links.typeParameters;
  43637. var id = getTypeListId(typeArguments);
  43638. var instantiation = links.instantiations.get(id);
  43639. if (!instantiation) {
  43640. links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
  43641. }
  43642. return instantiation;
  43643. }
  43644. /**
  43645. * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
  43646. * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
  43647. * declared type. Instantiations are cached using the type identities of the type arguments as the key.
  43648. */
  43649. function getTypeFromTypeAliasReference(node, symbol) {
  43650. var type = getDeclaredTypeOfSymbol(symbol);
  43651. var typeParameters = getSymbolLinks(symbol).typeParameters;
  43652. if (typeParameters) {
  43653. var numTypeArguments = ts.length(node.typeArguments);
  43654. var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
  43655. if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
  43656. error(node, minTypeArgumentCount === typeParameters.length ?
  43657. ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
  43658. ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
  43659. return errorType;
  43660. }
  43661. return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
  43662. }
  43663. return checkNoTypeArguments(node, symbol) ? type : errorType;
  43664. }
  43665. function getTypeReferenceName(node) {
  43666. switch (node.kind) {
  43667. case 169 /* TypeReference */:
  43668. return node.typeName;
  43669. case 216 /* ExpressionWithTypeArguments */:
  43670. // We only support expressions that are simple qualified names. For other
  43671. // expressions this produces undefined.
  43672. var expr = node.expression;
  43673. if (ts.isEntityNameExpression(expr)) {
  43674. return expr;
  43675. }
  43676. // fall through;
  43677. }
  43678. return undefined;
  43679. }
  43680. function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
  43681. if (!typeReferenceName) {
  43682. return unknownSymbol;
  43683. }
  43684. return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
  43685. }
  43686. function getTypeReferenceType(node, symbol) {
  43687. if (symbol === unknownSymbol) {
  43688. return errorType;
  43689. }
  43690. symbol = getExpandoSymbol(symbol) || symbol;
  43691. if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
  43692. return getTypeFromClassOrInterfaceReference(node, symbol);
  43693. }
  43694. if (symbol.flags & 524288 /* TypeAlias */) {
  43695. return getTypeFromTypeAliasReference(node, symbol);
  43696. }
  43697. // Get type from reference to named type that cannot be generic (enum or type parameter)
  43698. var res = tryGetDeclaredTypeOfSymbol(symbol);
  43699. if (res) {
  43700. return checkNoTypeArguments(node, symbol) ?
  43701. res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) :
  43702. errorType;
  43703. }
  43704. if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
  43705. var jsdocType = getTypeFromJSDocValueReference(node, symbol);
  43706. if (jsdocType) {
  43707. return jsdocType;
  43708. }
  43709. else {
  43710. // Resolve the type reference as a Type for the purpose of reporting errors.
  43711. resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
  43712. return getTypeOfSymbol(symbol);
  43713. }
  43714. }
  43715. return errorType;
  43716. }
  43717. /**
  43718. * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
  43719. * Note: If the value is imported from commonjs, it should really be an alias,
  43720. * but this function's special-case code fakes alias resolution as well.
  43721. */
  43722. function getTypeFromJSDocValueReference(node, symbol) {
  43723. var links = getNodeLinks(node);
  43724. if (!links.resolvedJSDocType) {
  43725. var valueType = getTypeOfSymbol(symbol);
  43726. var typeType = valueType;
  43727. if (symbol.valueDeclaration) {
  43728. var decl = ts.getRootDeclaration(symbol.valueDeclaration);
  43729. var isRequireAlias = false;
  43730. if (ts.isVariableDeclaration(decl) && decl.initializer) {
  43731. var expr = decl.initializer;
  43732. // skip past entity names, eg `require("x").a.b.c`
  43733. while (ts.isPropertyAccessExpression(expr)) {
  43734. expr = expr.expression;
  43735. }
  43736. isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
  43737. }
  43738. var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
  43739. // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
  43740. if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
  43741. typeType = getTypeReferenceType(node, valueType.symbol);
  43742. }
  43743. }
  43744. links.resolvedJSDocType = typeType;
  43745. }
  43746. return links.resolvedJSDocType;
  43747. }
  43748. function getSubstitutionType(typeVariable, substitute) {
  43749. if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) {
  43750. return typeVariable;
  43751. }
  43752. var id = getTypeId(typeVariable) + ">" + getTypeId(substitute);
  43753. var cached = substitutionTypes.get(id);
  43754. if (cached) {
  43755. return cached;
  43756. }
  43757. var result = createType(33554432 /* Substitution */);
  43758. result.typeVariable = typeVariable;
  43759. result.substitute = substitute;
  43760. substitutionTypes.set(id, result);
  43761. return result;
  43762. }
  43763. function isUnaryTupleTypeNode(node) {
  43764. return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
  43765. }
  43766. function getImpliedConstraint(typeVariable, checkNode, extendsNode) {
  43767. return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
  43768. getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) :
  43769. undefined;
  43770. }
  43771. function getConstrainedTypeVariable(typeVariable, node) {
  43772. var constraints;
  43773. while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
  43774. var parent = node.parent;
  43775. if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
  43776. var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
  43777. if (constraint) {
  43778. constraints = ts.append(constraints, constraint);
  43779. }
  43780. }
  43781. node = parent;
  43782. }
  43783. return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable;
  43784. }
  43785. function isJSDocTypeReference(node) {
  43786. return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
  43787. }
  43788. function checkNoTypeArguments(node, symbol) {
  43789. if (node.typeArguments) {
  43790. error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
  43791. return false;
  43792. }
  43793. return true;
  43794. }
  43795. function getIntendedTypeFromJSDocTypeReference(node) {
  43796. if (ts.isIdentifier(node.typeName)) {
  43797. var typeArgs = node.typeArguments;
  43798. switch (node.typeName.escapedText) {
  43799. case "String":
  43800. checkNoTypeArguments(node);
  43801. return stringType;
  43802. case "Number":
  43803. checkNoTypeArguments(node);
  43804. return numberType;
  43805. case "Boolean":
  43806. checkNoTypeArguments(node);
  43807. return booleanType;
  43808. case "Void":
  43809. checkNoTypeArguments(node);
  43810. return voidType;
  43811. case "Undefined":
  43812. checkNoTypeArguments(node);
  43813. return undefinedType;
  43814. case "Null":
  43815. checkNoTypeArguments(node);
  43816. return nullType;
  43817. case "Function":
  43818. case "function":
  43819. checkNoTypeArguments(node);
  43820. return globalFunctionType;
  43821. case "array":
  43822. return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
  43823. case "promise":
  43824. return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
  43825. case "Object":
  43826. if (typeArgs && typeArgs.length === 2) {
  43827. if (ts.isJSDocIndexSignature(node)) {
  43828. var indexed = getTypeFromTypeNode(typeArgs[0]);
  43829. var target = getTypeFromTypeNode(typeArgs[1]);
  43830. var index = createIndexInfo(target, /*isReadonly*/ false);
  43831. return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
  43832. }
  43833. return anyType;
  43834. }
  43835. checkNoTypeArguments(node);
  43836. return !noImplicitAny ? anyType : undefined;
  43837. }
  43838. }
  43839. }
  43840. function getTypeFromJSDocNullableTypeNode(node) {
  43841. var type = getTypeFromTypeNode(node.type);
  43842. return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
  43843. }
  43844. function getTypeFromTypeReference(node) {
  43845. var links = getNodeLinks(node);
  43846. if (!links.resolvedType) {
  43847. var symbol = void 0;
  43848. var type = void 0;
  43849. var meaning = 788968 /* Type */;
  43850. if (isJSDocTypeReference(node)) {
  43851. type = getIntendedTypeFromJSDocTypeReference(node);
  43852. if (!type) {
  43853. symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
  43854. if (symbol === unknownSymbol) {
  43855. symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
  43856. }
  43857. else {
  43858. resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
  43859. }
  43860. type = getTypeReferenceType(node, symbol);
  43861. }
  43862. }
  43863. if (!type) {
  43864. symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
  43865. type = getTypeReferenceType(node, symbol);
  43866. }
  43867. // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
  43868. // type reference in checkTypeReferenceNode.
  43869. links.resolvedSymbol = symbol;
  43870. links.resolvedType = type;
  43871. }
  43872. return links.resolvedType;
  43873. }
  43874. function typeArgumentsFromTypeReferenceNode(node) {
  43875. return ts.map(node.typeArguments, getTypeFromTypeNode);
  43876. }
  43877. function getTypeFromTypeQueryNode(node) {
  43878. var links = getNodeLinks(node);
  43879. if (!links.resolvedType) {
  43880. // TypeScript 1.0 spec (April 2014): 3.6.3
  43881. // The expression is processed as an identifier expression (section 4.3)
  43882. // or property access expression(section 4.10),
  43883. // the widened type(section 3.9) of which becomes the result.
  43884. links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
  43885. }
  43886. return links.resolvedType;
  43887. }
  43888. function getTypeOfGlobalSymbol(symbol, arity) {
  43889. function getTypeDeclaration(symbol) {
  43890. var declarations = symbol.declarations;
  43891. for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
  43892. var declaration = declarations_3[_i];
  43893. switch (declaration.kind) {
  43894. case 245 /* ClassDeclaration */:
  43895. case 246 /* InterfaceDeclaration */:
  43896. case 248 /* EnumDeclaration */:
  43897. return declaration;
  43898. }
  43899. }
  43900. }
  43901. if (!symbol) {
  43902. return arity ? emptyGenericType : emptyObjectType;
  43903. }
  43904. var type = getDeclaredTypeOfSymbol(symbol);
  43905. if (!(type.flags & 524288 /* Object */)) {
  43906. error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
  43907. return arity ? emptyGenericType : emptyObjectType;
  43908. }
  43909. if (ts.length(type.typeParameters) !== arity) {
  43910. error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
  43911. return arity ? emptyGenericType : emptyObjectType;
  43912. }
  43913. return type;
  43914. }
  43915. function getGlobalValueSymbol(name, reportErrors) {
  43916. return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
  43917. }
  43918. function getGlobalTypeSymbol(name, reportErrors) {
  43919. return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
  43920. }
  43921. function getGlobalSymbol(name, meaning, diagnostic) {
  43922. // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
  43923. return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
  43924. }
  43925. function getGlobalType(name, arity, reportErrors) {
  43926. var symbol = getGlobalTypeSymbol(name, reportErrors);
  43927. return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
  43928. }
  43929. function getGlobalTypedPropertyDescriptorType() {
  43930. return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
  43931. }
  43932. function getGlobalTemplateStringsArrayType() {
  43933. return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
  43934. }
  43935. function getGlobalImportMetaType() {
  43936. return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
  43937. }
  43938. function getGlobalESSymbolConstructorSymbol(reportErrors) {
  43939. return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
  43940. }
  43941. function getGlobalESSymbolType(reportErrors) {
  43942. return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
  43943. }
  43944. function getGlobalPromiseType(reportErrors) {
  43945. return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43946. }
  43947. function getGlobalPromiseLikeType(reportErrors) {
  43948. return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43949. }
  43950. function getGlobalPromiseConstructorSymbol(reportErrors) {
  43951. return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
  43952. }
  43953. function getGlobalPromiseConstructorLikeType(reportErrors) {
  43954. return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
  43955. }
  43956. function getGlobalAsyncIterableType(reportErrors) {
  43957. return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43958. }
  43959. function getGlobalAsyncIteratorType(reportErrors) {
  43960. return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
  43961. }
  43962. function getGlobalAsyncIterableIteratorType(reportErrors) {
  43963. return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43964. }
  43965. function getGlobalAsyncGeneratorType(reportErrors) {
  43966. return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
  43967. }
  43968. function getGlobalIterableType(reportErrors) {
  43969. return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43970. }
  43971. function getGlobalIteratorType(reportErrors) {
  43972. return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
  43973. }
  43974. function getGlobalIterableIteratorType(reportErrors) {
  43975. return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43976. }
  43977. function getGlobalGeneratorType(reportErrors) {
  43978. return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
  43979. }
  43980. function getGlobalIteratorYieldResultType(reportErrors) {
  43981. return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43982. }
  43983. function getGlobalIteratorReturnResultType(reportErrors) {
  43984. return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
  43985. }
  43986. function getGlobalTypeOrUndefined(name, arity) {
  43987. if (arity === void 0) { arity = 0; }
  43988. var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
  43989. return symbol && getTypeOfGlobalSymbol(symbol, arity);
  43990. }
  43991. function getGlobalExtractSymbol() {
  43992. return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
  43993. }
  43994. function getGlobalOmitSymbol() {
  43995. return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
  43996. }
  43997. function getGlobalBigIntType(reportErrors) {
  43998. return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
  43999. }
  44000. /**
  44001. * Instantiates a global type that is generic with some element type, and returns that instantiation.
  44002. */
  44003. function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
  44004. return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
  44005. }
  44006. function createTypedPropertyDescriptorType(propertyType) {
  44007. return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
  44008. }
  44009. function createIterableType(iteratedType) {
  44010. return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
  44011. }
  44012. function createArrayType(elementType, readonly) {
  44013. return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
  44014. }
  44015. function getArrayOrTupleTargetType(node) {
  44016. var readonly = isReadonlyTypeOperator(node.parent);
  44017. if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
  44018. return readonly ? globalReadonlyArrayType : globalArrayType;
  44019. }
  44020. var lastElement = ts.lastOrUndefined(node.elementTypes);
  44021. var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
  44022. var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
  44023. return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
  44024. }
  44025. // Return true when the given node is transitively contained in type constructs that eagerly
  44026. // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
  44027. // of type aliases are eagerly resolved.
  44028. function isAliasedType(node) {
  44029. var parent = node.parent;
  44030. switch (parent.kind) {
  44031. case 182 /* ParenthesizedType */:
  44032. case 169 /* TypeReference */:
  44033. case 178 /* UnionType */:
  44034. case 179 /* IntersectionType */:
  44035. case 185 /* IndexedAccessType */:
  44036. case 180 /* ConditionalType */:
  44037. case 184 /* TypeOperator */:
  44038. return isAliasedType(parent);
  44039. case 247 /* TypeAliasDeclaration */:
  44040. return true;
  44041. }
  44042. return false;
  44043. }
  44044. function getTypeFromArrayOrTupleTypeNode(node) {
  44045. var links = getNodeLinks(node);
  44046. if (!links.resolvedType) {
  44047. var target = getArrayOrTupleTargetType(node);
  44048. if (target === emptyGenericType) {
  44049. links.resolvedType = emptyObjectType;
  44050. }
  44051. else if (isAliasedType(node)) {
  44052. links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
  44053. createDeferredTypeReference(target, node, /*mapper*/ undefined);
  44054. }
  44055. else {
  44056. var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
  44057. links.resolvedType = createTypeReference(target, elementTypes);
  44058. }
  44059. }
  44060. return links.resolvedType;
  44061. }
  44062. function isReadonlyTypeOperator(node) {
  44063. return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
  44064. }
  44065. // We represent tuple types as type references to synthesized generic interface types created by
  44066. // this function. The types are of the form:
  44067. //
  44068. // interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
  44069. //
  44070. // Note that the generic type created by this function has no symbol associated with it. The same
  44071. // is true for each of the synthesized type parameters.
  44072. function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
  44073. var typeParameters;
  44074. var properties = [];
  44075. var maxLength = hasRestElement ? arity - 1 : arity;
  44076. if (arity) {
  44077. typeParameters = new Array(arity);
  44078. for (var i = 0; i < arity; i++) {
  44079. var typeParameter = typeParameters[i] = createTypeParameter();
  44080. if (i < maxLength) {
  44081. var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
  44082. property.type = typeParameter;
  44083. properties.push(property);
  44084. }
  44085. }
  44086. }
  44087. var literalTypes = [];
  44088. for (var i = minLength; i <= maxLength; i++)
  44089. literalTypes.push(getLiteralType(i));
  44090. var lengthSymbol = createSymbol(4 /* Property */, "length");
  44091. lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
  44092. properties.push(lengthSymbol);
  44093. var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
  44094. type.typeParameters = typeParameters;
  44095. type.outerTypeParameters = undefined;
  44096. type.localTypeParameters = typeParameters;
  44097. type.instantiations = ts.createMap();
  44098. type.instantiations.set(getTypeListId(type.typeParameters), type);
  44099. type.target = type;
  44100. type.resolvedTypeArguments = type.typeParameters;
  44101. type.thisType = createTypeParameter();
  44102. type.thisType.isThisType = true;
  44103. type.thisType.constraint = type;
  44104. type.declaredProperties = properties;
  44105. type.declaredCallSignatures = ts.emptyArray;
  44106. type.declaredConstructSignatures = ts.emptyArray;
  44107. type.declaredStringIndexInfo = undefined;
  44108. type.declaredNumberIndexInfo = undefined;
  44109. type.minLength = minLength;
  44110. type.hasRestElement = hasRestElement;
  44111. type.readonly = readonly;
  44112. type.associatedNames = associatedNames;
  44113. return type;
  44114. }
  44115. function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
  44116. var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
  44117. var type = tupleTypes.get(key);
  44118. if (!type) {
  44119. tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
  44120. }
  44121. return type;
  44122. }
  44123. function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
  44124. if (minLength === void 0) { minLength = elementTypes.length; }
  44125. if (hasRestElement === void 0) { hasRestElement = false; }
  44126. if (readonly === void 0) { readonly = false; }
  44127. var arity = elementTypes.length;
  44128. if (arity === 1 && hasRestElement) {
  44129. return createArrayType(elementTypes[0], readonly);
  44130. }
  44131. var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
  44132. return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
  44133. }
  44134. function sliceTupleType(type, index) {
  44135. var tuple = type.target;
  44136. if (tuple.hasRestElement) {
  44137. // don't slice off rest element
  44138. index = Math.min(index, getTypeReferenceArity(type) - 1);
  44139. }
  44140. return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
  44141. }
  44142. function getTypeFromOptionalTypeNode(node) {
  44143. var type = getTypeFromTypeNode(node.type);
  44144. return strictNullChecks ? getOptionalType(type) : type;
  44145. }
  44146. function getTypeId(type) {
  44147. return type.id;
  44148. }
  44149. function containsType(types, type) {
  44150. return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
  44151. }
  44152. function insertType(types, type) {
  44153. var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
  44154. if (index < 0) {
  44155. types.splice(~index, 0, type);
  44156. return true;
  44157. }
  44158. return false;
  44159. }
  44160. function addTypeToUnion(typeSet, includes, type) {
  44161. var flags = type.flags;
  44162. if (flags & 1048576 /* Union */) {
  44163. return addTypesToUnion(typeSet, includes, type.types);
  44164. }
  44165. // We ignore 'never' types in unions
  44166. if (!(flags & 131072 /* Never */)) {
  44167. includes |= flags & 68943871 /* IncludesMask */;
  44168. if (flags & 66846720 /* StructuredOrInstantiable */)
  44169. includes |= 262144 /* IncludesStructuredOrInstantiable */;
  44170. if (type === wildcardType)
  44171. includes |= 4194304 /* IncludesWildcard */;
  44172. if (!strictNullChecks && flags & 98304 /* Nullable */) {
  44173. if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
  44174. includes |= 2097152 /* IncludesNonWideningType */;
  44175. }
  44176. else {
  44177. var len = typeSet.length;
  44178. var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
  44179. if (index < 0) {
  44180. typeSet.splice(~index, 0, type);
  44181. }
  44182. }
  44183. }
  44184. return includes;
  44185. }
  44186. // Add the given types to the given type set. Order is preserved, duplicates are removed,
  44187. // and nested types of the given kind are flattened into the set.
  44188. function addTypesToUnion(typeSet, includes, types) {
  44189. for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
  44190. var type = types_8[_i];
  44191. includes = addTypeToUnion(typeSet, includes, type);
  44192. }
  44193. return includes;
  44194. }
  44195. function isSetOfLiteralsFromSameEnum(types) {
  44196. var first = types[0];
  44197. if (first.flags & 1024 /* EnumLiteral */) {
  44198. var firstEnum = getParentOfSymbol(first.symbol);
  44199. for (var i = 1; i < types.length; i++) {
  44200. var other = types[i];
  44201. if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
  44202. return false;
  44203. }
  44204. }
  44205. return true;
  44206. }
  44207. return false;
  44208. }
  44209. function removeSubtypes(types, primitivesOnly) {
  44210. var len = types.length;
  44211. if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
  44212. return true;
  44213. }
  44214. var i = len;
  44215. var count = 0;
  44216. while (i > 0) {
  44217. i--;
  44218. var source = types[i];
  44219. for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
  44220. var target = types_9[_i];
  44221. if (source !== target) {
  44222. if (count === 100000) {
  44223. // After 100000 subtype checks we estimate the remaining amount of work by assuming the
  44224. // same ratio of checks per element. If the estimated number of remaining type checks is
  44225. // greater than an upper limit we deem the union type too complex to represent. The
  44226. // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
  44227. // caps union types at 5000 unique literal types and 1000 unique object types.
  44228. var estimatedCount = (count / (len - i)) * len;
  44229. if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
  44230. error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
  44231. return false;
  44232. }
  44233. }
  44234. count++;
  44235. if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
  44236. !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
  44237. isTypeDerivedFrom(source, target))) {
  44238. ts.orderedRemoveItemAt(types, i);
  44239. break;
  44240. }
  44241. }
  44242. }
  44243. }
  44244. return true;
  44245. }
  44246. function removeRedundantLiteralTypes(types, includes) {
  44247. var i = types.length;
  44248. while (i > 0) {
  44249. i--;
  44250. var t = types[i];
  44251. var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
  44252. t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
  44253. t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
  44254. t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
  44255. isFreshLiteralType(t) && containsType(types, t.regularType);
  44256. if (remove) {
  44257. ts.orderedRemoveItemAt(types, i);
  44258. }
  44259. }
  44260. }
  44261. // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
  44262. // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
  44263. // of other types. Subtype reduction is expensive for large union types and is possible only when union
  44264. // types are known not to circularly reference themselves (as is the case with union types created by
  44265. // expression constructs such as array literals and the || and ?: operators). Named types can
  44266. // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
  44267. // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
  44268. function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
  44269. if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
  44270. if (types.length === 0) {
  44271. return neverType;
  44272. }
  44273. if (types.length === 1) {
  44274. return types[0];
  44275. }
  44276. var typeSet = [];
  44277. var includes = addTypesToUnion(typeSet, 0, types);
  44278. if (unionReduction !== 0 /* None */) {
  44279. if (includes & 3 /* AnyOrUnknown */) {
  44280. return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
  44281. }
  44282. switch (unionReduction) {
  44283. case 1 /* Literal */:
  44284. if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
  44285. removeRedundantLiteralTypes(typeSet, includes);
  44286. }
  44287. break;
  44288. case 2 /* Subtype */:
  44289. if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
  44290. return errorType;
  44291. }
  44292. break;
  44293. }
  44294. if (typeSet.length === 0) {
  44295. return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
  44296. includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
  44297. neverType;
  44298. }
  44299. }
  44300. return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
  44301. }
  44302. function getUnionTypePredicate(signatures) {
  44303. var first;
  44304. var types = [];
  44305. for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
  44306. var sig = signatures_6[_i];
  44307. var pred = getTypePredicateOfSignature(sig);
  44308. if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
  44309. continue;
  44310. }
  44311. if (first) {
  44312. if (!typePredicateKindsMatch(first, pred)) {
  44313. // No common type predicate.
  44314. return undefined;
  44315. }
  44316. }
  44317. else {
  44318. first = pred;
  44319. }
  44320. types.push(pred.type);
  44321. }
  44322. if (!first) {
  44323. // No union signatures had a type predicate.
  44324. return undefined;
  44325. }
  44326. var unionType = getUnionType(types);
  44327. return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
  44328. }
  44329. function typePredicateKindsMatch(a, b) {
  44330. return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
  44331. }
  44332. // This function assumes the constituent type list is sorted and deduplicated.
  44333. function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
  44334. if (types.length === 0) {
  44335. return neverType;
  44336. }
  44337. if (types.length === 1) {
  44338. return types[0];
  44339. }
  44340. var id = getTypeListId(types);
  44341. var type = unionTypes.get(id);
  44342. if (!type) {
  44343. type = createType(1048576 /* Union */);
  44344. unionTypes.set(id, type);
  44345. type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
  44346. type.types = types;
  44347. /*
  44348. Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
  44349. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
  44350. (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
  44351. It's important that we create equivalent union types only once, so that's an unfortunate side effect.
  44352. */
  44353. type.aliasSymbol = aliasSymbol;
  44354. type.aliasTypeArguments = aliasTypeArguments;
  44355. }
  44356. return type;
  44357. }
  44358. function getTypeFromUnionTypeNode(node) {
  44359. var links = getNodeLinks(node);
  44360. if (!links.resolvedType) {
  44361. var aliasSymbol = getAliasSymbolForTypeNode(node);
  44362. links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
  44363. }
  44364. return links.resolvedType;
  44365. }
  44366. function addTypeToIntersection(typeSet, includes, type) {
  44367. var flags = type.flags;
  44368. if (flags & 2097152 /* Intersection */) {
  44369. return addTypesToIntersection(typeSet, includes, type.types);
  44370. }
  44371. if (isEmptyAnonymousObjectType(type)) {
  44372. if (!(includes & 8388608 /* IncludesEmptyObject */)) {
  44373. includes |= 8388608 /* IncludesEmptyObject */;
  44374. typeSet.set(type.id.toString(), type);
  44375. }
  44376. }
  44377. else {
  44378. if (flags & 3 /* AnyOrUnknown */) {
  44379. if (type === wildcardType)
  44380. includes |= 4194304 /* IncludesWildcard */;
  44381. }
  44382. else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
  44383. if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
  44384. // We have seen two distinct unit types which means we should reduce to an
  44385. // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
  44386. includes |= 67108864 /* NonPrimitive */;
  44387. }
  44388. typeSet.set(type.id.toString(), type);
  44389. }
  44390. includes |= flags & 68943871 /* IncludesMask */;
  44391. }
  44392. return includes;
  44393. }
  44394. // Add the given types to the given type set. Order is preserved, freshness is removed from literal
  44395. // types, duplicates are removed, and nested types of the given kind are flattened into the set.
  44396. function addTypesToIntersection(typeSet, includes, types) {
  44397. for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
  44398. var type = types_10[_i];
  44399. includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
  44400. }
  44401. return includes;
  44402. }
  44403. function removeRedundantPrimitiveTypes(types, includes) {
  44404. var i = types.length;
  44405. while (i > 0) {
  44406. i--;
  44407. var t = types[i];
  44408. var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
  44409. t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
  44410. t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
  44411. t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
  44412. if (remove) {
  44413. ts.orderedRemoveItemAt(types, i);
  44414. }
  44415. }
  44416. }
  44417. // Check that the given type has a match in every union. A given type is matched by
  44418. // an identical type, and a literal type is additionally matched by its corresponding
  44419. // primitive type.
  44420. function eachUnionContains(unionTypes, type) {
  44421. for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
  44422. var u = unionTypes_1[_i];
  44423. if (!containsType(u.types, type)) {
  44424. var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
  44425. type.flags & 256 /* NumberLiteral */ ? numberType :
  44426. type.flags & 2048 /* BigIntLiteral */ ? bigintType :
  44427. type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
  44428. undefined;
  44429. if (!primitive || !containsType(u.types, primitive)) {
  44430. return false;
  44431. }
  44432. }
  44433. }
  44434. return true;
  44435. }
  44436. function extractIrreducible(types, flag) {
  44437. if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
  44438. for (var i = 0; i < types.length; i++) {
  44439. types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
  44440. }
  44441. return true;
  44442. }
  44443. return false;
  44444. }
  44445. // If the given list of types contains more than one union of primitive types, replace the
  44446. // first with a union containing an intersection of those primitive types, then remove the
  44447. // other unions and return true. Otherwise, do nothing and return false.
  44448. function intersectUnionsOfPrimitiveTypes(types) {
  44449. var unionTypes;
  44450. var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
  44451. if (index < 0) {
  44452. return false;
  44453. }
  44454. var i = index + 1;
  44455. // Remove all but the first union of primitive types and collect them in
  44456. // the unionTypes array.
  44457. while (i < types.length) {
  44458. var t = types[i];
  44459. if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
  44460. (unionTypes || (unionTypes = [types[index]])).push(t);
  44461. ts.orderedRemoveItemAt(types, i);
  44462. }
  44463. else {
  44464. i++;
  44465. }
  44466. }
  44467. // Return false if there was only one union of primitive types
  44468. if (!unionTypes) {
  44469. return false;
  44470. }
  44471. // We have more than one union of primitive types, now intersect them. For each
  44472. // type in each union we check if the type is matched in every union and if so
  44473. // we include it in the result.
  44474. var checked = [];
  44475. var result = [];
  44476. for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
  44477. var u = unionTypes_2[_i];
  44478. for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
  44479. var t = _b[_a];
  44480. if (insertType(checked, t)) {
  44481. if (eachUnionContains(unionTypes, t)) {
  44482. insertType(result, t);
  44483. }
  44484. }
  44485. }
  44486. }
  44487. // Finally replace the first union with the result
  44488. types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
  44489. return true;
  44490. }
  44491. function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
  44492. var result = createType(2097152 /* Intersection */);
  44493. result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
  44494. result.types = types;
  44495. result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
  44496. result.aliasTypeArguments = aliasTypeArguments;
  44497. return result;
  44498. }
  44499. // We normalize combinations of intersection and union types based on the distributive property of the '&'
  44500. // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
  44501. // types with union type constituents into equivalent union types with intersection type constituents and
  44502. // effectively ensure that union types are always at the top level in type representations.
  44503. //
  44504. // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
  44505. // type operator and we can't reduce those because we want to support recursive intersection types. For example,
  44506. // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
  44507. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
  44508. // for intersections of types with signatures can be deterministic.
  44509. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
  44510. var typeMembershipMap = ts.createMap();
  44511. var includes = addTypesToIntersection(typeMembershipMap, 0, types);
  44512. var typeSet = ts.arrayFrom(typeMembershipMap.values());
  44513. // An intersection type is considered empty if it contains
  44514. // the type never, or
  44515. // more than one unit type or,
  44516. // an object type and a nullable type (null or undefined), or
  44517. // a string-like type and a type known to be non-string-like, or
  44518. // a number-like type and a type known to be non-number-like, or
  44519. // a symbol-like type and a type known to be non-symbol-like, or
  44520. // a void-like type and a type known to be non-void-like, or
  44521. // a non-primitive type and a type known to be primitive.
  44522. if (includes & 131072 /* Never */ ||
  44523. strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) ||
  44524. includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
  44525. includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
  44526. includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
  44527. includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
  44528. includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
  44529. includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
  44530. return neverType;
  44531. }
  44532. if (includes & 1 /* Any */) {
  44533. return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
  44534. }
  44535. if (!strictNullChecks && includes & 98304 /* Nullable */) {
  44536. return includes & 32768 /* Undefined */ ? undefinedType : nullType;
  44537. }
  44538. if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
  44539. includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
  44540. includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
  44541. includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
  44542. removeRedundantPrimitiveTypes(typeSet, includes);
  44543. }
  44544. if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
  44545. ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
  44546. }
  44547. if (typeSet.length === 0) {
  44548. return unknownType;
  44549. }
  44550. if (typeSet.length === 1) {
  44551. return typeSet[0];
  44552. }
  44553. var id = getTypeListId(typeSet);
  44554. var result = intersectionTypes.get(id);
  44555. if (!result) {
  44556. if (includes & 1048576 /* Union */) {
  44557. if (intersectUnionsOfPrimitiveTypes(typeSet)) {
  44558. // When the intersection creates a reduced set (which might mean that *all* union types have
  44559. // disappeared), we restart the operation to get a new set of combined flags. Once we have
  44560. // reduced we'll never reduce again, so this occurs at most once.
  44561. result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
  44562. }
  44563. else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
  44564. result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
  44565. }
  44566. else if (extractIrreducible(typeSet, 65536 /* Null */)) {
  44567. result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
  44568. }
  44569. else {
  44570. // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
  44571. // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
  44572. // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
  44573. var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
  44574. if (size >= 100000) {
  44575. error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
  44576. return errorType;
  44577. }
  44578. var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
  44579. var unionType = typeSet[unionIndex_1];
  44580. result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
  44581. }
  44582. }
  44583. else {
  44584. result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
  44585. }
  44586. intersectionTypes.set(id, result);
  44587. }
  44588. return result;
  44589. }
  44590. function getTypeFromIntersectionTypeNode(node) {
  44591. var links = getNodeLinks(node);
  44592. if (!links.resolvedType) {
  44593. var aliasSymbol = getAliasSymbolForTypeNode(node);
  44594. links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
  44595. }
  44596. return links.resolvedType;
  44597. }
  44598. function createIndexType(type, stringsOnly) {
  44599. var result = createType(4194304 /* Index */);
  44600. result.type = type;
  44601. result.stringsOnly = stringsOnly;
  44602. return result;
  44603. }
  44604. function getIndexTypeForGenericType(type, stringsOnly) {
  44605. return stringsOnly ?
  44606. type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
  44607. type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
  44608. }
  44609. function getLiteralTypeFromPropertyName(name) {
  44610. if (ts.isPrivateIdentifier(name)) {
  44611. return neverType;
  44612. }
  44613. return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
  44614. getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
  44615. }
  44616. function getBigIntLiteralType(node) {
  44617. return getLiteralType({
  44618. negative: false,
  44619. base10Value: ts.parsePseudoBigInt(node.text)
  44620. });
  44621. }
  44622. function getLiteralTypeFromProperty(prop, include) {
  44623. if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
  44624. var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
  44625. if (!type && !ts.isKnownSymbol(prop)) {
  44626. if (prop.escapedName === "default" /* Default */) {
  44627. type = getLiteralType("default");
  44628. }
  44629. else {
  44630. var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
  44631. type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
  44632. }
  44633. }
  44634. if (type && type.flags & include) {
  44635. return type;
  44636. }
  44637. }
  44638. return neverType;
  44639. }
  44640. function getLiteralTypeFromProperties(type, include) {
  44641. return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
  44642. }
  44643. function getNonEnumNumberIndexInfo(type) {
  44644. var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
  44645. return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
  44646. }
  44647. function getIndexType(type, stringsOnly, noIndexSignatures) {
  44648. if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
  44649. return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
  44650. type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
  44651. maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
  44652. ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
  44653. type === wildcardType ? wildcardType :
  44654. type.flags & 2 /* Unknown */ ? neverType :
  44655. type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
  44656. stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
  44657. !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
  44658. getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
  44659. getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
  44660. }
  44661. function getExtractStringType(type) {
  44662. if (keyofStringsOnly) {
  44663. return type;
  44664. }
  44665. var extractTypeAlias = getGlobalExtractSymbol();
  44666. return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
  44667. }
  44668. function getIndexTypeOrString(type) {
  44669. var indexType = getExtractStringType(getIndexType(type));
  44670. return indexType.flags & 131072 /* Never */ ? stringType : indexType;
  44671. }
  44672. function getTypeFromTypeOperatorNode(node) {
  44673. var links = getNodeLinks(node);
  44674. if (!links.resolvedType) {
  44675. switch (node.operator) {
  44676. case 134 /* KeyOfKeyword */:
  44677. links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
  44678. break;
  44679. case 147 /* UniqueKeyword */:
  44680. links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
  44681. ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
  44682. : errorType;
  44683. break;
  44684. case 138 /* ReadonlyKeyword */:
  44685. links.resolvedType = getTypeFromTypeNode(node.type);
  44686. break;
  44687. default:
  44688. throw ts.Debug.assertNever(node.operator);
  44689. }
  44690. }
  44691. return links.resolvedType;
  44692. }
  44693. function createIndexedAccessType(objectType, indexType) {
  44694. var type = createType(8388608 /* IndexedAccess */);
  44695. type.objectType = objectType;
  44696. type.indexType = indexType;
  44697. return type;
  44698. }
  44699. /**
  44700. * Returns if a type is or consists of a JSLiteral object type
  44701. * In addition to objects which are directly literals,
  44702. * * unions where every element is a jsliteral
  44703. * * intersections where at least one element is a jsliteral
  44704. * * and instantiable types constrained to a jsliteral
  44705. * Should all count as literals and not print errors on access or assignment of possibly existing properties.
  44706. * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
  44707. */
  44708. function isJSLiteralType(type) {
  44709. if (noImplicitAny) {
  44710. return false; // Flag is meaningless under `noImplicitAny` mode
  44711. }
  44712. if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
  44713. return true;
  44714. }
  44715. if (type.flags & 1048576 /* Union */) {
  44716. return ts.every(type.types, isJSLiteralType);
  44717. }
  44718. if (type.flags & 2097152 /* Intersection */) {
  44719. return ts.some(type.types, isJSLiteralType);
  44720. }
  44721. if (type.flags & 63176704 /* Instantiable */) {
  44722. return isJSLiteralType(getResolvedBaseConstraint(type));
  44723. }
  44724. return false;
  44725. }
  44726. function getPropertyNameFromIndex(indexType, accessNode) {
  44727. var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
  44728. return isTypeUsableAsPropertyName(indexType) ?
  44729. getPropertyNameFromType(indexType) :
  44730. accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
  44731. ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
  44732. accessNode && ts.isPropertyName(accessNode) ?
  44733. // late bound names are handled in the first branch, so here we only need to handle normal names
  44734. ts.getPropertyNameForPropertyNameNode(accessNode) :
  44735. undefined;
  44736. }
  44737. function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
  44738. var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
  44739. var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
  44740. if (propName !== undefined) {
  44741. var prop = getPropertyOfType(objectType, propName);
  44742. if (prop) {
  44743. if (accessExpression) {
  44744. markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
  44745. if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
  44746. error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
  44747. return undefined;
  44748. }
  44749. if (accessFlags & 4 /* CacheSymbol */) {
  44750. getNodeLinks(accessNode).resolvedSymbol = prop;
  44751. }
  44752. }
  44753. var propType = getTypeOfSymbol(prop);
  44754. return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
  44755. getFlowTypeOfReference(accessExpression, propType) :
  44756. propType;
  44757. }
  44758. if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
  44759. if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
  44760. var indexNode = getIndexNodeForAccessExpression(accessNode);
  44761. if (isTupleType(objectType)) {
  44762. error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
  44763. }
  44764. else {
  44765. error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
  44766. }
  44767. }
  44768. errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
  44769. return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
  44770. }
  44771. }
  44772. if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
  44773. if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
  44774. return objectType;
  44775. }
  44776. var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
  44777. var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
  44778. if (indexInfo) {
  44779. if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
  44780. if (accessExpression) {
  44781. error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
  44782. }
  44783. return undefined;
  44784. }
  44785. if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
  44786. var indexNode = getIndexNodeForAccessExpression(accessNode);
  44787. error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
  44788. return indexInfo.type;
  44789. }
  44790. errorIfWritingToReadonlyIndex(indexInfo);
  44791. return indexInfo.type;
  44792. }
  44793. if (indexType.flags & 131072 /* Never */) {
  44794. return neverType;
  44795. }
  44796. if (isJSLiteralType(objectType)) {
  44797. return anyType;
  44798. }
  44799. if (accessExpression && !isConstEnumObjectType(objectType)) {
  44800. if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
  44801. error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
  44802. }
  44803. else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
  44804. if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
  44805. error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
  44806. }
  44807. else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
  44808. error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
  44809. }
  44810. else {
  44811. var suggestion = void 0;
  44812. if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
  44813. if (suggestion !== undefined) {
  44814. error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
  44815. }
  44816. }
  44817. else {
  44818. var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
  44819. if (suggestion_1 !== undefined) {
  44820. error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion_1);
  44821. }
  44822. else {
  44823. var errorInfo = void 0;
  44824. if (indexType.flags & 1024 /* EnumLiteral */) {
  44825. errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
  44826. }
  44827. else if (indexType.flags & 8192 /* UniqueESSymbol */) {
  44828. var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
  44829. errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
  44830. }
  44831. else if (indexType.flags & 128 /* StringLiteral */) {
  44832. errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
  44833. }
  44834. else if (indexType.flags & 256 /* NumberLiteral */) {
  44835. errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
  44836. }
  44837. else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
  44838. errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType));
  44839. }
  44840. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType));
  44841. diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
  44842. }
  44843. }
  44844. }
  44845. }
  44846. return undefined;
  44847. }
  44848. }
  44849. if (isJSLiteralType(objectType)) {
  44850. return anyType;
  44851. }
  44852. if (accessNode) {
  44853. var indexNode = getIndexNodeForAccessExpression(accessNode);
  44854. if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
  44855. error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
  44856. }
  44857. else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
  44858. error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
  44859. }
  44860. else {
  44861. error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
  44862. }
  44863. }
  44864. if (isTypeAny(indexType)) {
  44865. return indexType;
  44866. }
  44867. return undefined;
  44868. function errorIfWritingToReadonlyIndex(indexInfo) {
  44869. if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
  44870. error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
  44871. }
  44872. }
  44873. }
  44874. function getIndexNodeForAccessExpression(accessNode) {
  44875. return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
  44876. accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
  44877. accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
  44878. accessNode;
  44879. }
  44880. function isGenericObjectType(type) {
  44881. return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
  44882. }
  44883. function isGenericIndexType(type) {
  44884. return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
  44885. }
  44886. function isThisTypeParameter(type) {
  44887. return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
  44888. }
  44889. function getSimplifiedType(type, writing) {
  44890. return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
  44891. type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
  44892. type;
  44893. }
  44894. function distributeIndexOverObjectType(objectType, indexType, writing) {
  44895. // (T | U)[K] -> T[K] | U[K] (reading)
  44896. // (T | U)[K] -> T[K] & U[K] (writing)
  44897. // (T & U)[K] -> T[K] & U[K]
  44898. if (objectType.flags & 3145728 /* UnionOrIntersection */) {
  44899. var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
  44900. return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
  44901. }
  44902. }
  44903. function distributeObjectOverIndexType(objectType, indexType, writing) {
  44904. // T[A | B] -> T[A] | T[B] (reading)
  44905. // T[A | B] -> T[A] & T[B] (writing)
  44906. if (indexType.flags & 1048576 /* Union */) {
  44907. var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
  44908. return writing ? getIntersectionType(types) : getUnionType(types);
  44909. }
  44910. }
  44911. function unwrapSubstitution(type) {
  44912. if (type.flags & 33554432 /* Substitution */) {
  44913. return type.substitute;
  44914. }
  44915. return type;
  44916. }
  44917. // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
  44918. // the type itself if no transformation is possible. The writing flag indicates that the type is
  44919. // the target of an assignment.
  44920. function getSimplifiedIndexedAccessType(type, writing) {
  44921. var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
  44922. if (type[cache]) {
  44923. return type[cache] === circularConstraintType ? type : type[cache];
  44924. }
  44925. type[cache] = circularConstraintType;
  44926. // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
  44927. // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
  44928. var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
  44929. var indexType = getSimplifiedType(type.indexType, writing);
  44930. // T[A | B] -> T[A] | T[B] (reading)
  44931. // T[A | B] -> T[A] & T[B] (writing)
  44932. var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
  44933. if (distributedOverIndex) {
  44934. return type[cache] = distributedOverIndex;
  44935. }
  44936. // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
  44937. if (!(indexType.flags & 63176704 /* Instantiable */)) {
  44938. // (T | U)[K] -> T[K] | U[K] (reading)
  44939. // (T | U)[K] -> T[K] & U[K] (writing)
  44940. // (T & U)[K] -> T[K] & U[K]
  44941. var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
  44942. if (distributedOverObject) {
  44943. return type[cache] = distributedOverObject;
  44944. }
  44945. }
  44946. // So ultimately (reading):
  44947. // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2]
  44948. // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
  44949. // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
  44950. // construct the type Box<T[X]>.
  44951. if (isGenericMappedType(objectType)) {
  44952. return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
  44953. }
  44954. return type[cache] = type;
  44955. }
  44956. function getSimplifiedConditionalType(type, writing) {
  44957. var checkType = type.checkType;
  44958. var extendsType = type.extendsType;
  44959. var trueType = getTrueTypeFromConditionalType(type);
  44960. var falseType = getFalseTypeFromConditionalType(type);
  44961. // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
  44962. if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
  44963. if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
  44964. return getSimplifiedType(trueType, writing);
  44965. }
  44966. else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
  44967. return neverType;
  44968. }
  44969. }
  44970. else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
  44971. if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
  44972. return neverType;
  44973. }
  44974. else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
  44975. return getSimplifiedType(falseType, writing);
  44976. }
  44977. }
  44978. return type;
  44979. }
  44980. /**
  44981. * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
  44982. */
  44983. function isIntersectionEmpty(type1, type2) {
  44984. return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
  44985. }
  44986. function substituteIndexedMappedType(objectType, index) {
  44987. var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
  44988. var templateMapper = combineTypeMappers(objectType.mapper, mapper);
  44989. return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
  44990. }
  44991. function getIndexedAccessType(objectType, indexType, accessNode) {
  44992. return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */) || (accessNode ? errorType : unknownType);
  44993. }
  44994. function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags) {
  44995. if (accessFlags === void 0) { accessFlags = 0 /* None */; }
  44996. if (objectType === wildcardType || indexType === wildcardType) {
  44997. return wildcardType;
  44998. }
  44999. // If the object type has a string index signature and no other members we know that the result will
  45000. // always be the type of that index signature and we can simplify accordingly.
  45001. if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
  45002. indexType = stringType;
  45003. }
  45004. // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
  45005. // we are performing a higher-order index access where we cannot meaningfully access the properties of the
  45006. // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
  45007. // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
  45008. // has always been resolved eagerly using the constraint type of 'this' at the given location.
  45009. if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
  45010. if (objectType.flags & 3 /* AnyOrUnknown */) {
  45011. return objectType;
  45012. }
  45013. // Defer the operation by creating an indexed access type.
  45014. var id = objectType.id + "," + indexType.id;
  45015. var type = indexedAccessTypes.get(id);
  45016. if (!type) {
  45017. indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType));
  45018. }
  45019. return type;
  45020. }
  45021. // In the following we resolve T[K] to the type of the property in T selected by K.
  45022. // We treat boolean as different from other unions to improve errors;
  45023. // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
  45024. var apparentObjectType = getApparentType(objectType);
  45025. if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
  45026. var propTypes = [];
  45027. var wasMissingProp = false;
  45028. for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
  45029. var t = _a[_i];
  45030. var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
  45031. if (propType) {
  45032. propTypes.push(propType);
  45033. }
  45034. else if (!accessNode) {
  45035. // If there's no error node, we can immeditely stop, since error reporting is off
  45036. return undefined;
  45037. }
  45038. else {
  45039. // Otherwise we set a flag and return at the end of the loop so we still mark all errors
  45040. wasMissingProp = true;
  45041. }
  45042. }
  45043. if (wasMissingProp) {
  45044. return undefined;
  45045. }
  45046. return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes) : getUnionType(propTypes);
  45047. }
  45048. return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
  45049. }
  45050. function getTypeFromIndexedAccessTypeNode(node) {
  45051. var links = getNodeLinks(node);
  45052. if (!links.resolvedType) {
  45053. var objectType = getTypeFromTypeNode(node.objectType);
  45054. var indexType = getTypeFromTypeNode(node.indexType);
  45055. var resolved = getIndexedAccessType(objectType, indexType, node);
  45056. links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
  45057. resolved.objectType === objectType &&
  45058. resolved.indexType === indexType ?
  45059. getConstrainedTypeVariable(resolved, node) : resolved;
  45060. }
  45061. return links.resolvedType;
  45062. }
  45063. function getTypeFromMappedTypeNode(node) {
  45064. var links = getNodeLinks(node);
  45065. if (!links.resolvedType) {
  45066. var type = createObjectType(32 /* Mapped */, node.symbol);
  45067. type.declaration = node;
  45068. type.aliasSymbol = getAliasSymbolForTypeNode(node);
  45069. type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
  45070. links.resolvedType = type;
  45071. // Eagerly resolve the constraint type which forces an error if the constraint type circularly
  45072. // references itself through one or more type aliases.
  45073. getConstraintTypeFromMappedType(type);
  45074. }
  45075. return links.resolvedType;
  45076. }
  45077. function getActualTypeVariable(type) {
  45078. if (type.flags & 33554432 /* Substitution */) {
  45079. return type.typeVariable;
  45080. }
  45081. if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
  45082. type.indexType.flags & 33554432 /* Substitution */)) {
  45083. return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
  45084. }
  45085. return type;
  45086. }
  45087. function getConditionalType(root, mapper) {
  45088. var checkType = instantiateType(root.checkType, mapper);
  45089. var extendsType = instantiateType(root.extendsType, mapper);
  45090. if (checkType === wildcardType || extendsType === wildcardType) {
  45091. return wildcardType;
  45092. }
  45093. var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
  45094. var combinedMapper;
  45095. if (root.inferTypeParameters) {
  45096. var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
  45097. // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
  45098. // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
  45099. // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
  45100. // so in those cases we refain from performing inference and retain the uninfered type parameter
  45101. if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
  45102. // We don't want inferences from constraints as they may cause us to eagerly resolve the
  45103. // conditional type instead of deferring resolution. Also, we always want strict function
  45104. // types rules (i.e. proper contravariance) for inferences.
  45105. inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
  45106. }
  45107. combinedMapper = combineTypeMappers(mapper, context.mapper);
  45108. }
  45109. // Instantiate the extends type including inferences for 'infer T' type parameters
  45110. var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
  45111. // We attempt to resolve the conditional type only when the check and extends types are non-generic
  45112. if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
  45113. if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
  45114. return instantiateType(root.trueType, combinedMapper || mapper);
  45115. }
  45116. // Return union of trueType and falseType for 'any' since it matches anything
  45117. if (checkType.flags & 1 /* Any */) {
  45118. return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
  45119. }
  45120. // Return falseType for a definitely false extends check. We check an instantiations of the two
  45121. // types with type parameters mapped to the wildcard type, the most permissive instantiations
  45122. // possible (the wildcard type is assignable to and from all types). If those are not related,
  45123. // then no instantiations will be and we can just return the false branch type.
  45124. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
  45125. return instantiateType(root.falseType, mapper);
  45126. }
  45127. // Return trueType for a definitely true extends check. We check instantiations of the two
  45128. // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
  45129. // that has no constraint. This ensures that, for example, the type
  45130. // type Foo<T extends { x: any }> = T extends { x: string } ? string : number
  45131. // doesn't immediately resolve to 'string' instead of being deferred.
  45132. if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
  45133. return instantiateType(root.trueType, combinedMapper || mapper);
  45134. }
  45135. }
  45136. // Return a deferred type for a check that is neither definitely true nor definitely false
  45137. var erasedCheckType = getActualTypeVariable(checkType);
  45138. var result = createType(16777216 /* Conditional */);
  45139. result.root = root;
  45140. result.checkType = erasedCheckType;
  45141. result.extendsType = extendsType;
  45142. result.mapper = mapper;
  45143. result.combinedMapper = combinedMapper;
  45144. result.aliasSymbol = root.aliasSymbol;
  45145. result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
  45146. return result;
  45147. }
  45148. function getTrueTypeFromConditionalType(type) {
  45149. return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
  45150. }
  45151. function getFalseTypeFromConditionalType(type) {
  45152. return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
  45153. }
  45154. function getInferredTrueTypeFromConditionalType(type) {
  45155. return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
  45156. }
  45157. function getInferTypeParameters(node) {
  45158. var result;
  45159. if (node.locals) {
  45160. node.locals.forEach(function (symbol) {
  45161. if (symbol.flags & 262144 /* TypeParameter */) {
  45162. result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
  45163. }
  45164. });
  45165. }
  45166. return result;
  45167. }
  45168. function getTypeFromConditionalTypeNode(node) {
  45169. var links = getNodeLinks(node);
  45170. if (!links.resolvedType) {
  45171. var checkType = getTypeFromTypeNode(node.checkType);
  45172. var aliasSymbol = getAliasSymbolForTypeNode(node);
  45173. var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
  45174. var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
  45175. var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
  45176. var root = {
  45177. node: node,
  45178. checkType: checkType,
  45179. extendsType: getTypeFromTypeNode(node.extendsType),
  45180. trueType: getTypeFromTypeNode(node.trueType),
  45181. falseType: getTypeFromTypeNode(node.falseType),
  45182. isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
  45183. inferTypeParameters: getInferTypeParameters(node),
  45184. outerTypeParameters: outerTypeParameters,
  45185. instantiations: undefined,
  45186. aliasSymbol: aliasSymbol,
  45187. aliasTypeArguments: aliasTypeArguments
  45188. };
  45189. links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
  45190. if (outerTypeParameters) {
  45191. root.instantiations = ts.createMap();
  45192. root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
  45193. }
  45194. }
  45195. return links.resolvedType;
  45196. }
  45197. function getTypeFromInferTypeNode(node) {
  45198. var links = getNodeLinks(node);
  45199. if (!links.resolvedType) {
  45200. links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
  45201. }
  45202. return links.resolvedType;
  45203. }
  45204. function getIdentifierChain(node) {
  45205. if (ts.isIdentifier(node)) {
  45206. return [node];
  45207. }
  45208. else {
  45209. return ts.append(getIdentifierChain(node.left), node.right);
  45210. }
  45211. }
  45212. function getTypeFromImportTypeNode(node) {
  45213. var links = getNodeLinks(node);
  45214. if (!links.resolvedType) {
  45215. if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
  45216. error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
  45217. links.resolvedSymbol = unknownSymbol;
  45218. return links.resolvedType = errorType;
  45219. }
  45220. if (!ts.isLiteralImportTypeNode(node)) {
  45221. error(node.argument, ts.Diagnostics.String_literal_expected);
  45222. links.resolvedSymbol = unknownSymbol;
  45223. return links.resolvedType = errorType;
  45224. }
  45225. var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
  45226. // TODO: Future work: support unions/generics/whatever via a deferred import-type
  45227. var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
  45228. if (!innerModuleSymbol) {
  45229. links.resolvedSymbol = unknownSymbol;
  45230. return links.resolvedType = errorType;
  45231. }
  45232. var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
  45233. if (!ts.nodeIsMissing(node.qualifier)) {
  45234. var nameStack = getIdentifierChain(node.qualifier);
  45235. var currentNamespace = moduleSymbol;
  45236. var current = void 0;
  45237. while (current = nameStack.shift()) {
  45238. var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
  45239. var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
  45240. if (!next) {
  45241. error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
  45242. return links.resolvedType = errorType;
  45243. }
  45244. getNodeLinks(current).resolvedSymbol = next;
  45245. getNodeLinks(current.parent).resolvedSymbol = next;
  45246. currentNamespace = next;
  45247. }
  45248. links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
  45249. }
  45250. else {
  45251. if (moduleSymbol.flags & targetMeaning) {
  45252. links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
  45253. }
  45254. else {
  45255. var errorMessage = targetMeaning === 111551 /* Value */
  45256. ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
  45257. : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
  45258. error(node, errorMessage, node.argument.literal.text);
  45259. links.resolvedSymbol = unknownSymbol;
  45260. links.resolvedType = errorType;
  45261. }
  45262. }
  45263. }
  45264. return links.resolvedType;
  45265. }
  45266. function resolveImportSymbolType(node, links, symbol, meaning) {
  45267. var resolvedSymbol = resolveSymbol(symbol);
  45268. links.resolvedSymbol = resolvedSymbol;
  45269. if (meaning === 111551 /* Value */) {
  45270. return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
  45271. }
  45272. else {
  45273. return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
  45274. }
  45275. }
  45276. function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
  45277. var links = getNodeLinks(node);
  45278. if (!links.resolvedType) {
  45279. // Deferred resolution of members is handled by resolveObjectTypeMembers
  45280. var aliasSymbol = getAliasSymbolForTypeNode(node);
  45281. if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
  45282. links.resolvedType = emptyTypeLiteralType;
  45283. }
  45284. else {
  45285. var type = createObjectType(16 /* Anonymous */, node.symbol);
  45286. type.aliasSymbol = aliasSymbol;
  45287. type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
  45288. if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
  45289. type = createArrayType(type);
  45290. }
  45291. links.resolvedType = type;
  45292. }
  45293. }
  45294. return links.resolvedType;
  45295. }
  45296. function getAliasSymbolForTypeNode(node) {
  45297. var host = node.parent;
  45298. while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
  45299. host = host.parent;
  45300. }
  45301. return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
  45302. }
  45303. function getTypeArgumentsForAliasSymbol(symbol) {
  45304. return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
  45305. }
  45306. function isNonGenericObjectType(type) {
  45307. return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
  45308. }
  45309. function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
  45310. return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
  45311. }
  45312. function isSinglePropertyAnonymousObjectType(type) {
  45313. return !!(type.flags & 524288 /* Object */) &&
  45314. !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
  45315. (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
  45316. }
  45317. function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
  45318. if (type.types.length === 2) {
  45319. var firstType = type.types[0];
  45320. var secondType = type.types[1];
  45321. if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
  45322. return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
  45323. }
  45324. if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
  45325. return getAnonymousPartialType(secondType);
  45326. }
  45327. if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
  45328. return getAnonymousPartialType(firstType);
  45329. }
  45330. }
  45331. function getAnonymousPartialType(type) {
  45332. // gets the type as if it had been spread, but where everything in the spread is made optional
  45333. var members = ts.createSymbolTable();
  45334. for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
  45335. var prop = _a[_i];
  45336. if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
  45337. // do nothing, skip privates
  45338. }
  45339. else if (isSpreadableProperty(prop)) {
  45340. var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
  45341. var flags = 4 /* Property */ | 16777216 /* Optional */;
  45342. var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
  45343. result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
  45344. result.declarations = prop.declarations;
  45345. result.nameType = getSymbolLinks(prop).nameType;
  45346. result.syntheticOrigin = prop;
  45347. members.set(prop.escapedName, result);
  45348. }
  45349. }
  45350. var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
  45351. spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
  45352. return spread;
  45353. }
  45354. }
  45355. /**
  45356. * Since the source of spread types are object literals, which are not binary,
  45357. * this function should be called in a left folding style, with left = previous result of getSpreadType
  45358. * and right = the new element to be spread.
  45359. */
  45360. function getSpreadType(left, right, symbol, objectFlags, readonly) {
  45361. if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
  45362. return anyType;
  45363. }
  45364. if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
  45365. return unknownType;
  45366. }
  45367. if (left.flags & 131072 /* Never */) {
  45368. return right;
  45369. }
  45370. if (right.flags & 131072 /* Never */) {
  45371. return left;
  45372. }
  45373. if (left.flags & 1048576 /* Union */) {
  45374. var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
  45375. if (merged) {
  45376. return getSpreadType(merged, right, symbol, objectFlags, readonly);
  45377. }
  45378. return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
  45379. }
  45380. if (right.flags & 1048576 /* Union */) {
  45381. var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
  45382. if (merged) {
  45383. return getSpreadType(left, merged, symbol, objectFlags, readonly);
  45384. }
  45385. return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
  45386. }
  45387. if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
  45388. return left;
  45389. }
  45390. if (isGenericObjectType(left) || isGenericObjectType(right)) {
  45391. if (isEmptyObjectType(left)) {
  45392. return right;
  45393. }
  45394. // When the left type is an intersection, we may need to merge the last constituent of the
  45395. // intersection with the right type. For example when the left type is 'T & { a: string }'
  45396. // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
  45397. if (left.flags & 2097152 /* Intersection */) {
  45398. var types = left.types;
  45399. var lastLeft = types[types.length - 1];
  45400. if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
  45401. return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
  45402. }
  45403. }
  45404. return getIntersectionType([left, right]);
  45405. }
  45406. var members = ts.createSymbolTable();
  45407. var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
  45408. var stringIndexInfo;
  45409. var numberIndexInfo;
  45410. if (left === emptyObjectType) {
  45411. // for the first spread element, left === emptyObjectType, so take the right's string indexer
  45412. stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
  45413. numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
  45414. }
  45415. else {
  45416. stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
  45417. numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
  45418. }
  45419. for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
  45420. var rightProp = _a[_i];
  45421. if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
  45422. skippedPrivateMembers.set(rightProp.escapedName, true);
  45423. }
  45424. else if (isSpreadableProperty(rightProp)) {
  45425. members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
  45426. }
  45427. }
  45428. for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
  45429. var leftProp = _c[_b];
  45430. if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
  45431. continue;
  45432. }
  45433. if (members.has(leftProp.escapedName)) {
  45434. var rightProp = members.get(leftProp.escapedName);
  45435. var rightType = getTypeOfSymbol(rightProp);
  45436. if (rightProp.flags & 16777216 /* Optional */) {
  45437. var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
  45438. var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
  45439. var result = createSymbol(flags, leftProp.escapedName);
  45440. result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
  45441. result.leftSpread = leftProp;
  45442. result.rightSpread = rightProp;
  45443. result.declarations = declarations;
  45444. result.nameType = getSymbolLinks(leftProp).nameType;
  45445. members.set(leftProp.escapedName, result);
  45446. }
  45447. }
  45448. else {
  45449. members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
  45450. }
  45451. }
  45452. var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
  45453. spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
  45454. return spread;
  45455. }
  45456. /** We approximate own properties as non-methods plus methods that are inside the object literal */
  45457. function isSpreadableProperty(prop) {
  45458. return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
  45459. (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
  45460. !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
  45461. }
  45462. function getSpreadSymbol(prop, readonly) {
  45463. var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
  45464. if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
  45465. return prop;
  45466. }
  45467. var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
  45468. var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
  45469. result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
  45470. result.declarations = prop.declarations;
  45471. result.nameType = getSymbolLinks(prop).nameType;
  45472. result.syntheticOrigin = prop;
  45473. return result;
  45474. }
  45475. function getIndexInfoWithReadonly(info, readonly) {
  45476. return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
  45477. }
  45478. function createLiteralType(flags, value, symbol) {
  45479. var type = createType(flags);
  45480. type.symbol = symbol;
  45481. type.value = value;
  45482. return type;
  45483. }
  45484. function getFreshTypeOfLiteralType(type) {
  45485. if (type.flags & 2944 /* Literal */) {
  45486. if (!type.freshType) {
  45487. var freshType = createLiteralType(type.flags, type.value, type.symbol);
  45488. freshType.regularType = type;
  45489. freshType.freshType = freshType;
  45490. type.freshType = freshType;
  45491. }
  45492. return type.freshType;
  45493. }
  45494. return type;
  45495. }
  45496. function getRegularTypeOfLiteralType(type) {
  45497. return type.flags & 2944 /* Literal */ ? type.regularType :
  45498. type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) :
  45499. type;
  45500. }
  45501. function isFreshLiteralType(type) {
  45502. return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
  45503. }
  45504. function getLiteralType(value, enumId, symbol) {
  45505. // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
  45506. // where NNN is the text representation of a numeric literal and SSS are the characters
  45507. // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
  45508. // EEE is a unique id for the containing enum type.
  45509. var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
  45510. var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
  45511. var type = literalTypes.get(key);
  45512. if (!type) {
  45513. var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
  45514. typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
  45515. (enumId ? 1024 /* EnumLiteral */ : 0);
  45516. literalTypes.set(key, type = createLiteralType(flags, value, symbol));
  45517. type.regularType = type;
  45518. }
  45519. return type;
  45520. }
  45521. function getTypeFromLiteralTypeNode(node) {
  45522. var links = getNodeLinks(node);
  45523. if (!links.resolvedType) {
  45524. links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
  45525. }
  45526. return links.resolvedType;
  45527. }
  45528. function createUniqueESSymbolType(symbol) {
  45529. var type = createType(8192 /* UniqueESSymbol */);
  45530. type.symbol = symbol;
  45531. type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
  45532. return type;
  45533. }
  45534. function getESSymbolLikeTypeForNode(node) {
  45535. if (ts.isValidESSymbolDeclaration(node)) {
  45536. var symbol = getSymbolOfNode(node);
  45537. var links = getSymbolLinks(symbol);
  45538. return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
  45539. }
  45540. return esSymbolType;
  45541. }
  45542. function getThisType(node) {
  45543. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
  45544. var parent = container && container.parent;
  45545. if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
  45546. if (!ts.hasModifier(container, 32 /* Static */) &&
  45547. (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
  45548. return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
  45549. }
  45550. }
  45551. // inside x.prototype = { ... }
  45552. if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
  45553. return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
  45554. }
  45555. // /** @return {this} */
  45556. // x.prototype.m = function() { ... }
  45557. var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
  45558. if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
  45559. return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
  45560. }
  45561. // inside constructor function C() { ... }
  45562. if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
  45563. return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
  45564. }
  45565. error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
  45566. return errorType;
  45567. }
  45568. function getTypeFromThisTypeNode(node) {
  45569. var links = getNodeLinks(node);
  45570. if (!links.resolvedType) {
  45571. links.resolvedType = getThisType(node);
  45572. }
  45573. return links.resolvedType;
  45574. }
  45575. function getTypeFromTypeNode(node) {
  45576. switch (node.kind) {
  45577. case 125 /* AnyKeyword */:
  45578. case 295 /* JSDocAllType */:
  45579. case 296 /* JSDocUnknownType */:
  45580. return anyType;
  45581. case 148 /* UnknownKeyword */:
  45582. return unknownType;
  45583. case 143 /* StringKeyword */:
  45584. return stringType;
  45585. case 140 /* NumberKeyword */:
  45586. return numberType;
  45587. case 151 /* BigIntKeyword */:
  45588. return bigintType;
  45589. case 128 /* BooleanKeyword */:
  45590. return booleanType;
  45591. case 144 /* SymbolKeyword */:
  45592. return esSymbolType;
  45593. case 110 /* VoidKeyword */:
  45594. return voidType;
  45595. case 146 /* UndefinedKeyword */:
  45596. return undefinedType;
  45597. case 100 /* NullKeyword */:
  45598. return nullType;
  45599. case 137 /* NeverKeyword */:
  45600. return neverType;
  45601. case 141 /* ObjectKeyword */:
  45602. return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
  45603. case 183 /* ThisType */:
  45604. case 104 /* ThisKeyword */:
  45605. return getTypeFromThisTypeNode(node);
  45606. case 187 /* LiteralType */:
  45607. return getTypeFromLiteralTypeNode(node);
  45608. case 169 /* TypeReference */:
  45609. return getTypeFromTypeReference(node);
  45610. case 168 /* TypePredicate */:
  45611. return node.assertsModifier ? voidType : booleanType;
  45612. case 216 /* ExpressionWithTypeArguments */:
  45613. return getTypeFromTypeReference(node);
  45614. case 172 /* TypeQuery */:
  45615. return getTypeFromTypeQueryNode(node);
  45616. case 174 /* ArrayType */:
  45617. case 175 /* TupleType */:
  45618. return getTypeFromArrayOrTupleTypeNode(node);
  45619. case 176 /* OptionalType */:
  45620. return getTypeFromOptionalTypeNode(node);
  45621. case 178 /* UnionType */:
  45622. return getTypeFromUnionTypeNode(node);
  45623. case 179 /* IntersectionType */:
  45624. return getTypeFromIntersectionTypeNode(node);
  45625. case 297 /* JSDocNullableType */:
  45626. return getTypeFromJSDocNullableTypeNode(node);
  45627. case 299 /* JSDocOptionalType */:
  45628. return addOptionality(getTypeFromTypeNode(node.type));
  45629. case 182 /* ParenthesizedType */:
  45630. case 298 /* JSDocNonNullableType */:
  45631. case 294 /* JSDocTypeExpression */:
  45632. return getTypeFromTypeNode(node.type);
  45633. case 177 /* RestType */:
  45634. return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
  45635. case 301 /* JSDocVariadicType */:
  45636. return getTypeFromJSDocVariadicType(node);
  45637. case 170 /* FunctionType */:
  45638. case 171 /* ConstructorType */:
  45639. case 173 /* TypeLiteral */:
  45640. case 304 /* JSDocTypeLiteral */:
  45641. case 300 /* JSDocFunctionType */:
  45642. case 305 /* JSDocSignature */:
  45643. return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
  45644. case 184 /* TypeOperator */:
  45645. return getTypeFromTypeOperatorNode(node);
  45646. case 185 /* IndexedAccessType */:
  45647. return getTypeFromIndexedAccessTypeNode(node);
  45648. case 186 /* MappedType */:
  45649. return getTypeFromMappedTypeNode(node);
  45650. case 180 /* ConditionalType */:
  45651. return getTypeFromConditionalTypeNode(node);
  45652. case 181 /* InferType */:
  45653. return getTypeFromInferTypeNode(node);
  45654. case 188 /* ImportType */:
  45655. return getTypeFromImportTypeNode(node);
  45656. // This function assumes that an identifier or qualified name is a type expression
  45657. // Callers should first ensure this by calling isTypeNode
  45658. case 75 /* Identifier */:
  45659. case 153 /* QualifiedName */:
  45660. var symbol = getSymbolAtLocation(node);
  45661. return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
  45662. default:
  45663. return errorType;
  45664. }
  45665. }
  45666. function instantiateList(items, mapper, instantiator) {
  45667. if (items && items.length) {
  45668. for (var i = 0; i < items.length; i++) {
  45669. var item = items[i];
  45670. var mapped = instantiator(item, mapper);
  45671. if (item !== mapped) {
  45672. var result = i === 0 ? [] : items.slice(0, i);
  45673. result.push(mapped);
  45674. for (i++; i < items.length; i++) {
  45675. result.push(instantiator(items[i], mapper));
  45676. }
  45677. return result;
  45678. }
  45679. }
  45680. }
  45681. return items;
  45682. }
  45683. function instantiateTypes(types, mapper) {
  45684. return instantiateList(types, mapper, instantiateType);
  45685. }
  45686. function instantiateSignatures(signatures, mapper) {
  45687. return instantiateList(signatures, mapper, instantiateSignature);
  45688. }
  45689. function makeUnaryTypeMapper(source, target) {
  45690. return function (t) { return t === source ? target : t; };
  45691. }
  45692. function makeBinaryTypeMapper(source1, target1, source2, target2) {
  45693. return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; };
  45694. }
  45695. function makeArrayTypeMapper(sources, targets) {
  45696. return function (t) {
  45697. for (var i = 0; i < sources.length; i++) {
  45698. if (t === sources[i]) {
  45699. return targets ? targets[i] : anyType;
  45700. }
  45701. }
  45702. return t;
  45703. };
  45704. }
  45705. function createTypeMapper(sources, targets) {
  45706. ts.Debug.assert(targets === undefined || sources.length === targets.length);
  45707. return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) :
  45708. sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) :
  45709. makeArrayTypeMapper(sources, targets);
  45710. }
  45711. function createTypeEraser(sources) {
  45712. return createTypeMapper(sources, /*targets*/ undefined);
  45713. }
  45714. /**
  45715. * Maps forward-references to later types parameters to the empty object type.
  45716. * This is used during inference when instantiating type parameter defaults.
  45717. */
  45718. function createBackreferenceMapper(context, index) {
  45719. return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; };
  45720. }
  45721. function combineTypeMappers(mapper1, mapper2) {
  45722. if (!mapper1)
  45723. return mapper2;
  45724. if (!mapper2)
  45725. return mapper1;
  45726. return function (t) { return instantiateType(mapper1(t), mapper2); };
  45727. }
  45728. function createReplacementMapper(source, target, baseMapper) {
  45729. return function (t) { return t === source ? target : baseMapper(t); };
  45730. }
  45731. function permissiveMapper(type) {
  45732. return type.flags & 262144 /* TypeParameter */ ? wildcardType : type;
  45733. }
  45734. function getRestrictiveTypeParameter(tp) {
  45735. return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
  45736. tp.restrictiveInstantiation.constraint = unknownType,
  45737. tp.restrictiveInstantiation);
  45738. }
  45739. function restrictiveMapper(type) {
  45740. return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type;
  45741. }
  45742. function cloneTypeParameter(typeParameter) {
  45743. var result = createTypeParameter(typeParameter.symbol);
  45744. result.target = typeParameter;
  45745. return result;
  45746. }
  45747. function instantiateTypePredicate(predicate, mapper) {
  45748. return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
  45749. }
  45750. function instantiateSignature(signature, mapper, eraseTypeParameters) {
  45751. var freshTypeParameters;
  45752. if (signature.typeParameters && !eraseTypeParameters) {
  45753. // First create a fresh set of type parameters, then include a mapping from the old to the
  45754. // new type parameters in the mapper function. Finally store this mapper in the new type
  45755. // parameters such that we can use it when instantiating constraints.
  45756. freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
  45757. mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
  45758. for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
  45759. var tp = freshTypeParameters_1[_i];
  45760. tp.mapper = mapper;
  45761. }
  45762. }
  45763. // Don't compute resolvedReturnType and resolvedTypePredicate now,
  45764. // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
  45765. // See GH#17600.
  45766. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol),
  45767. /*resolvedReturnType*/ undefined,
  45768. /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
  45769. result.target = signature;
  45770. result.mapper = mapper;
  45771. return result;
  45772. }
  45773. function instantiateSymbol(symbol, mapper) {
  45774. var links = getSymbolLinks(symbol);
  45775. if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) {
  45776. // If the type of the symbol is already resolved, and if that type could not possibly
  45777. // be affected by instantiation, simply return the symbol itself.
  45778. return symbol;
  45779. }
  45780. if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
  45781. // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
  45782. // type mappers. This ensures that original type identities are properly preserved and that aliases
  45783. // always reference a non-aliases.
  45784. symbol = links.target;
  45785. mapper = combineTypeMappers(links.mapper, mapper);
  45786. }
  45787. // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
  45788. // also transient so that we can just store data on it directly.
  45789. var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
  45790. result.declarations = symbol.declarations;
  45791. result.parent = symbol.parent;
  45792. result.target = symbol;
  45793. result.mapper = mapper;
  45794. if (symbol.valueDeclaration) {
  45795. result.valueDeclaration = symbol.valueDeclaration;
  45796. }
  45797. if (links.nameType) {
  45798. result.nameType = links.nameType;
  45799. }
  45800. return result;
  45801. }
  45802. function getObjectTypeInstantiation(type, mapper) {
  45803. var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
  45804. var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
  45805. var links = getNodeLinks(node);
  45806. var typeParameters = links.outerTypeParameters;
  45807. if (!typeParameters) {
  45808. // The first time an anonymous type is instantiated we compute and store a list of the type
  45809. // parameters that are in scope (and therefore potentially referenced). For type literals that
  45810. // aren't the right hand side of a generic type alias declaration we optimize by reducing the
  45811. // set of type parameters to those that are possibly referenced in the literal.
  45812. var declaration_1 = node;
  45813. if (ts.isInJSFile(declaration_1)) {
  45814. var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
  45815. if (paramTag) {
  45816. var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
  45817. if (paramSymbol) {
  45818. declaration_1 = paramSymbol.valueDeclaration;
  45819. }
  45820. }
  45821. }
  45822. var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
  45823. if (isJSConstructor(declaration_1)) {
  45824. var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
  45825. outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
  45826. }
  45827. typeParameters = outerTypeParameters || ts.emptyArray;
  45828. typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
  45829. ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
  45830. typeParameters;
  45831. links.outerTypeParameters = typeParameters;
  45832. if (typeParameters.length) {
  45833. links.instantiations = ts.createMap();
  45834. links.instantiations.set(getTypeListId(typeParameters), target);
  45835. }
  45836. }
  45837. if (typeParameters.length) {
  45838. // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
  45839. // mapper to the type parameters to produce the effective list of type arguments, and compute the
  45840. // instantiation cache key from the type IDs of the type arguments.
  45841. var typeArguments = ts.map(typeParameters, combineTypeMappers(type.mapper, mapper));
  45842. var id = getTypeListId(typeArguments);
  45843. var result = links.instantiations.get(id);
  45844. if (!result) {
  45845. var newMapper = createTypeMapper(typeParameters, typeArguments);
  45846. result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
  45847. target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
  45848. instantiateAnonymousType(target, newMapper);
  45849. links.instantiations.set(id, result);
  45850. }
  45851. return result;
  45852. }
  45853. return type;
  45854. }
  45855. function maybeTypeParameterReference(node) {
  45856. return !(node.kind === 153 /* QualifiedName */ ||
  45857. node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
  45858. node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
  45859. }
  45860. function isTypeParameterPossiblyReferenced(tp, node) {
  45861. // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
  45862. // between the node and the type parameter declaration, if the node contains actual references to the
  45863. // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
  45864. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
  45865. var container = tp.symbol.declarations[0].parent;
  45866. for (var n = node; n !== container; n = n.parent) {
  45867. if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
  45868. return true;
  45869. }
  45870. }
  45871. return !!ts.forEachChild(node, containsReference);
  45872. }
  45873. return true;
  45874. function containsReference(node) {
  45875. switch (node.kind) {
  45876. case 183 /* ThisType */:
  45877. return !!tp.isThisType;
  45878. case 75 /* Identifier */:
  45879. return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
  45880. getTypeFromTypeNode(node) === tp;
  45881. case 172 /* TypeQuery */:
  45882. return true;
  45883. }
  45884. return !!ts.forEachChild(node, containsReference);
  45885. }
  45886. }
  45887. function getHomomorphicTypeVariable(type) {
  45888. var constraintType = getConstraintTypeFromMappedType(type);
  45889. if (constraintType.flags & 4194304 /* Index */) {
  45890. var typeVariable = getActualTypeVariable(constraintType.type);
  45891. if (typeVariable.flags & 262144 /* TypeParameter */) {
  45892. return typeVariable;
  45893. }
  45894. }
  45895. return undefined;
  45896. }
  45897. function instantiateMappedType(type, mapper) {
  45898. // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
  45899. // operation depends on T as follows:
  45900. // * If T is a primitive type no mapping is performed and the result is simply T.
  45901. // * If T is a union type we distribute the mapped type over the union.
  45902. // * If T is an array we map to an array where the element type has been transformed.
  45903. // * If T is a tuple we map to a tuple where the element types have been transformed.
  45904. // * Otherwise we map to an object type where the type of each property has been transformed.
  45905. // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
  45906. // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
  45907. // { [P in keyof A]: X } | undefined.
  45908. var typeVariable = getHomomorphicTypeVariable(type);
  45909. if (typeVariable) {
  45910. var mappedTypeVariable = instantiateType(typeVariable, mapper);
  45911. if (typeVariable !== mappedTypeVariable) {
  45912. return mapType(mappedTypeVariable, function (t) {
  45913. if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
  45914. var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
  45915. return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
  45916. isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
  45917. instantiateAnonymousType(type, replacementMapper);
  45918. }
  45919. return t;
  45920. });
  45921. }
  45922. }
  45923. return instantiateAnonymousType(type, mapper);
  45924. }
  45925. function getModifiedReadonlyState(state, modifiers) {
  45926. return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
  45927. }
  45928. function instantiateMappedArrayType(arrayType, mappedType, mapper) {
  45929. var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
  45930. return elementType === errorType ? errorType :
  45931. createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
  45932. }
  45933. function instantiateMappedTupleType(tupleType, mappedType, mapper) {
  45934. var minLength = tupleType.target.minLength;
  45935. var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
  45936. return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
  45937. });
  45938. var modifiers = getMappedTypeModifiers(mappedType);
  45939. var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
  45940. modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
  45941. minLength;
  45942. var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
  45943. return ts.contains(elementTypes, errorType) ? errorType :
  45944. createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
  45945. }
  45946. function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
  45947. var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
  45948. var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
  45949. var modifiers = getMappedTypeModifiers(type);
  45950. return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) :
  45951. strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
  45952. propType;
  45953. }
  45954. function instantiateAnonymousType(type, mapper) {
  45955. var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
  45956. if (type.objectFlags & 32 /* Mapped */) {
  45957. result.declaration = type.declaration;
  45958. // C.f. instantiateSignature
  45959. var origTypeParameter = getTypeParameterFromMappedType(type);
  45960. var freshTypeParameter = cloneTypeParameter(origTypeParameter);
  45961. result.typeParameter = freshTypeParameter;
  45962. mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
  45963. freshTypeParameter.mapper = mapper;
  45964. }
  45965. result.target = type;
  45966. result.mapper = mapper;
  45967. result.aliasSymbol = type.aliasSymbol;
  45968. result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
  45969. return result;
  45970. }
  45971. function getConditionalTypeInstantiation(type, mapper) {
  45972. var root = type.root;
  45973. if (root.outerTypeParameters) {
  45974. // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
  45975. // mapper to the type parameters to produce the effective list of type arguments, and compute the
  45976. // instantiation cache key from the type IDs of the type arguments.
  45977. var typeArguments = ts.map(root.outerTypeParameters, mapper);
  45978. var id = getTypeListId(typeArguments);
  45979. var result = root.instantiations.get(id);
  45980. if (!result) {
  45981. var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
  45982. result = instantiateConditionalType(root, newMapper);
  45983. root.instantiations.set(id, result);
  45984. }
  45985. return result;
  45986. }
  45987. return type;
  45988. }
  45989. function instantiateConditionalType(root, mapper) {
  45990. // Check if we have a conditional type where the check type is a naked type parameter. If so,
  45991. // the conditional type is distributive over union types and when T is instantiated to a union
  45992. // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
  45993. if (root.isDistributive) {
  45994. var checkType_1 = root.checkType;
  45995. var instantiatedType = mapper(checkType_1);
  45996. if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
  45997. return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
  45998. }
  45999. }
  46000. return getConditionalType(root, mapper);
  46001. }
  46002. function instantiateType(type, mapper) {
  46003. if (!type || !mapper || mapper === identityMapper) {
  46004. return type;
  46005. }
  46006. if (instantiationDepth === 50 || instantiationCount >= 5000000) {
  46007. // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
  46008. // with a combination of infinite generic types that perpetually generate new type identities. We stop
  46009. // the recursion here by yielding the error type.
  46010. error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
  46011. return errorType;
  46012. }
  46013. instantiationCount++;
  46014. instantiationDepth++;
  46015. var result = instantiateTypeWorker(type, mapper);
  46016. instantiationDepth--;
  46017. return result;
  46018. }
  46019. function instantiateTypeWorker(type, mapper) {
  46020. var flags = type.flags;
  46021. if (flags & 262144 /* TypeParameter */) {
  46022. return mapper(type);
  46023. }
  46024. if (flags & 524288 /* Object */) {
  46025. var objectFlags = type.objectFlags;
  46026. if (objectFlags & 16 /* Anonymous */) {
  46027. // If the anonymous type originates in a declaration of a function, method, class, or
  46028. // interface, in an object type literal, or in an object literal expression, we may need
  46029. // to instantiate the type because it might reference a type parameter.
  46030. return couldContainTypeVariables(type) ?
  46031. getObjectTypeInstantiation(type, mapper) : type;
  46032. }
  46033. if (objectFlags & 32 /* Mapped */) {
  46034. return getObjectTypeInstantiation(type, mapper);
  46035. }
  46036. if (objectFlags & 4 /* Reference */) {
  46037. if (type.node) {
  46038. return getObjectTypeInstantiation(type, mapper);
  46039. }
  46040. var resolvedTypeArguments = type.resolvedTypeArguments;
  46041. var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
  46042. return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
  46043. }
  46044. return type;
  46045. }
  46046. if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) {
  46047. var types = type.types;
  46048. var newTypes = instantiateTypes(types, mapper);
  46049. return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
  46050. }
  46051. if (flags & 2097152 /* Intersection */) {
  46052. var types = type.types;
  46053. var newTypes = instantiateTypes(types, mapper);
  46054. return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
  46055. }
  46056. if (flags & 4194304 /* Index */) {
  46057. return getIndexType(instantiateType(type.type, mapper));
  46058. }
  46059. if (flags & 8388608 /* IndexedAccess */) {
  46060. return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
  46061. }
  46062. if (flags & 16777216 /* Conditional */) {
  46063. return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
  46064. }
  46065. if (flags & 33554432 /* Substitution */) {
  46066. var maybeVariable = instantiateType(type.typeVariable, mapper);
  46067. if (maybeVariable.flags & 8650752 /* TypeVariable */) {
  46068. return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
  46069. }
  46070. else {
  46071. var sub = instantiateType(type.substitute, mapper);
  46072. if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
  46073. return maybeVariable;
  46074. }
  46075. return sub;
  46076. }
  46077. }
  46078. return type;
  46079. }
  46080. function getPermissiveInstantiation(type) {
  46081. return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
  46082. type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
  46083. }
  46084. function getRestrictiveInstantiation(type) {
  46085. if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
  46086. return type;
  46087. }
  46088. if (type.restrictiveInstantiation) {
  46089. return type.restrictiveInstantiation;
  46090. }
  46091. type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
  46092. // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
  46093. // which is redundant - we'll produce new type identities, but all type params have already been mapped.
  46094. // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
  46095. // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
  46096. // are constrained to `unknown` and produce tons of false positives/negatives!
  46097. type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
  46098. return type.restrictiveInstantiation;
  46099. }
  46100. function instantiateIndexInfo(info, mapper) {
  46101. return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
  46102. }
  46103. // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
  46104. // that is subject to contextual typing.
  46105. function isContextSensitive(node) {
  46106. ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
  46107. switch (node.kind) {
  46108. case 201 /* FunctionExpression */:
  46109. case 202 /* ArrowFunction */:
  46110. case 161 /* MethodDeclaration */:
  46111. case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
  46112. return isContextSensitiveFunctionLikeDeclaration(node);
  46113. case 193 /* ObjectLiteralExpression */:
  46114. return ts.some(node.properties, isContextSensitive);
  46115. case 192 /* ArrayLiteralExpression */:
  46116. return ts.some(node.elements, isContextSensitive);
  46117. case 210 /* ConditionalExpression */:
  46118. return isContextSensitive(node.whenTrue) ||
  46119. isContextSensitive(node.whenFalse);
  46120. case 209 /* BinaryExpression */:
  46121. return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
  46122. (isContextSensitive(node.left) || isContextSensitive(node.right));
  46123. case 281 /* PropertyAssignment */:
  46124. return isContextSensitive(node.initializer);
  46125. case 200 /* ParenthesizedExpression */:
  46126. return isContextSensitive(node.expression);
  46127. case 274 /* JsxAttributes */:
  46128. return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
  46129. case 273 /* JsxAttribute */: {
  46130. // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
  46131. var initializer = node.initializer;
  46132. return !!initializer && isContextSensitive(initializer);
  46133. }
  46134. case 276 /* JsxExpression */: {
  46135. // It is possible to that node.expression is undefined (e.g <div x={} />)
  46136. var expression = node.expression;
  46137. return !!expression && isContextSensitive(expression);
  46138. }
  46139. }
  46140. return false;
  46141. }
  46142. function isContextSensitiveFunctionLikeDeclaration(node) {
  46143. return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
  46144. (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
  46145. }
  46146. function hasContextSensitiveParameters(node) {
  46147. // Functions with type parameters are not context sensitive.
  46148. if (!node.typeParameters) {
  46149. // Functions with any parameters that lack type annotations are context sensitive.
  46150. if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
  46151. return true;
  46152. }
  46153. if (node.kind !== 202 /* ArrowFunction */) {
  46154. // If the first parameter is not an explicit 'this' parameter, then the function has
  46155. // an implicit 'this' parameter which is subject to contextual typing.
  46156. var parameter = ts.firstOrUndefined(node.parameters);
  46157. if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
  46158. return true;
  46159. }
  46160. }
  46161. }
  46162. return false;
  46163. }
  46164. function hasContextSensitiveReturnExpression(node) {
  46165. // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
  46166. return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
  46167. }
  46168. function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
  46169. return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
  46170. isContextSensitiveFunctionLikeDeclaration(func);
  46171. }
  46172. function getTypeWithoutSignatures(type) {
  46173. if (type.flags & 524288 /* Object */) {
  46174. var resolved = resolveStructuredTypeMembers(type);
  46175. if (resolved.constructSignatures.length || resolved.callSignatures.length) {
  46176. var result = createObjectType(16 /* Anonymous */, type.symbol);
  46177. result.members = resolved.members;
  46178. result.properties = resolved.properties;
  46179. result.callSignatures = ts.emptyArray;
  46180. result.constructSignatures = ts.emptyArray;
  46181. return result;
  46182. }
  46183. }
  46184. else if (type.flags & 2097152 /* Intersection */) {
  46185. return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
  46186. }
  46187. return type;
  46188. }
  46189. // TYPE CHECKING
  46190. function isTypeIdenticalTo(source, target) {
  46191. return isTypeRelatedTo(source, target, identityRelation);
  46192. }
  46193. function compareTypesIdentical(source, target) {
  46194. return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
  46195. }
  46196. function compareTypesAssignable(source, target) {
  46197. return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
  46198. }
  46199. function compareTypesSubtypeOf(source, target) {
  46200. return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
  46201. }
  46202. function isTypeSubtypeOf(source, target) {
  46203. return isTypeRelatedTo(source, target, subtypeRelation);
  46204. }
  46205. function isTypeAssignableTo(source, target) {
  46206. return isTypeRelatedTo(source, target, assignableRelation);
  46207. }
  46208. // An object type S is considered to be derived from an object type T if
  46209. // S is a union type and every constituent of S is derived from T,
  46210. // T is a union type and S is derived from at least one constituent of T, or
  46211. // S is a type variable with a base constraint that is derived from T,
  46212. // T is one of the global types Object and Function and S is a subtype of T, or
  46213. // T occurs directly or indirectly in an 'extends' clause of S.
  46214. // Note that this check ignores type parameters and only considers the
  46215. // inheritance hierarchy.
  46216. function isTypeDerivedFrom(source, target) {
  46217. return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
  46218. target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
  46219. source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
  46220. target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
  46221. target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
  46222. hasBaseType(source, getTargetType(target));
  46223. }
  46224. /**
  46225. * This is *not* a bi-directional relationship.
  46226. * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
  46227. *
  46228. * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T.
  46229. * It is used to check following cases:
  46230. * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
  46231. * - the types of `case` clause expressions and their respective `switch` expressions.
  46232. * - the type of an expression in a type assertion with the type being asserted.
  46233. */
  46234. function isTypeComparableTo(source, target) {
  46235. return isTypeRelatedTo(source, target, comparableRelation);
  46236. }
  46237. function areTypesComparable(type1, type2) {
  46238. return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
  46239. }
  46240. function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
  46241. return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
  46242. }
  46243. /**
  46244. * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
  46245. * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
  46246. */
  46247. function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
  46248. return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
  46249. }
  46250. function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
  46251. if (isTypeRelatedTo(source, target, relation))
  46252. return true;
  46253. if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
  46254. return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
  46255. }
  46256. return false;
  46257. }
  46258. function isOrHasGenericConditional(type) {
  46259. return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
  46260. }
  46261. function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
  46262. if (!node || isOrHasGenericConditional(target))
  46263. return false;
  46264. if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
  46265. && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
  46266. return true;
  46267. }
  46268. switch (node.kind) {
  46269. case 276 /* JsxExpression */:
  46270. case 200 /* ParenthesizedExpression */:
  46271. return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
  46272. case 209 /* BinaryExpression */:
  46273. switch (node.operatorToken.kind) {
  46274. case 62 /* EqualsToken */:
  46275. case 27 /* CommaToken */:
  46276. return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
  46277. }
  46278. break;
  46279. case 193 /* ObjectLiteralExpression */:
  46280. return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
  46281. case 192 /* ArrayLiteralExpression */:
  46282. return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
  46283. case 274 /* JsxAttributes */:
  46284. return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
  46285. case 202 /* ArrowFunction */:
  46286. return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
  46287. }
  46288. return false;
  46289. }
  46290. function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
  46291. var callSignatures = getSignaturesOfType(source, 0 /* Call */);
  46292. var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
  46293. for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
  46294. var signatures = _a[_i];
  46295. if (ts.some(signatures, function (s) {
  46296. var returnType = getReturnTypeOfSignature(s);
  46297. return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
  46298. })) {
  46299. var resultObj = errorOutputContainer || {};
  46300. checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
  46301. var diagnostic = resultObj.errors[resultObj.errors.length - 1];
  46302. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
  46303. return true;
  46304. }
  46305. }
  46306. return false;
  46307. }
  46308. function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
  46309. // Don't elaborate blocks
  46310. if (ts.isBlock(node.body)) {
  46311. return false;
  46312. }
  46313. // Or functions with annotated parameter types
  46314. if (ts.some(node.parameters, ts.hasType)) {
  46315. return false;
  46316. }
  46317. var sourceSig = getSingleCallSignature(source);
  46318. if (!sourceSig) {
  46319. return false;
  46320. }
  46321. var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
  46322. if (!ts.length(targetSignatures)) {
  46323. return false;
  46324. }
  46325. var returnExpression = node.body;
  46326. var sourceReturn = getReturnTypeOfSignature(sourceSig);
  46327. var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
  46328. if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
  46329. var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
  46330. if (elaborated) {
  46331. return elaborated;
  46332. }
  46333. var resultObj = errorOutputContainer || {};
  46334. checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
  46335. if (resultObj.errors) {
  46336. if (target.symbol && ts.length(target.symbol.declarations)) {
  46337. ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
  46338. }
  46339. return true;
  46340. }
  46341. }
  46342. return false;
  46343. }
  46344. function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
  46345. var idx = getIndexedAccessTypeOrUndefined(target, nameType);
  46346. if (idx) {
  46347. return idx;
  46348. }
  46349. if (target.flags & 1048576 /* Union */) {
  46350. var best = getBestMatchingType(source, target);
  46351. if (best) {
  46352. return getIndexedAccessTypeOrUndefined(best, nameType);
  46353. }
  46354. }
  46355. }
  46356. /**
  46357. * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
  46358. * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError`
  46359. * Otherwise, we issue an error on _every_ element which fail the assignability check
  46360. */
  46361. function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
  46362. // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
  46363. var reportedError = false;
  46364. for (var status = iterator.next(); !status.done; status = iterator.next()) {
  46365. var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
  46366. var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
  46367. if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
  46368. continue; // Don't elaborate on indexes on generic variables
  46369. var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
  46370. if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
  46371. var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
  46372. if (elaborated) {
  46373. reportedError = true;
  46374. }
  46375. else {
  46376. // Issue error on the prop itself, since the prop couldn't elaborate the error
  46377. var resultObj = errorOutputContainer || {};
  46378. // Use the expression type, if available
  46379. var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType;
  46380. var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
  46381. if (result && specificSource !== sourcePropType) {
  46382. // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
  46383. checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
  46384. }
  46385. if (resultObj.errors) {
  46386. var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
  46387. var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
  46388. var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
  46389. var issuedElaboration = false;
  46390. if (!targetProp) {
  46391. var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
  46392. getIndexInfoOfType(target, 0 /* String */) ||
  46393. undefined;
  46394. if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
  46395. issuedElaboration = true;
  46396. ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
  46397. }
  46398. }
  46399. if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
  46400. var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
  46401. if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
  46402. ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
  46403. }
  46404. }
  46405. }
  46406. reportedError = true;
  46407. }
  46408. }
  46409. }
  46410. return reportedError;
  46411. }
  46412. function generateJsxAttributes(node) {
  46413. var _i, _a, prop;
  46414. return __generator(this, function (_b) {
  46415. switch (_b.label) {
  46416. case 0:
  46417. if (!ts.length(node.properties))
  46418. return [2 /*return*/];
  46419. _i = 0, _a = node.properties;
  46420. _b.label = 1;
  46421. case 1:
  46422. if (!(_i < _a.length)) return [3 /*break*/, 4];
  46423. prop = _a[_i];
  46424. if (ts.isJsxSpreadAttribute(prop))
  46425. return [3 /*break*/, 3];
  46426. return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
  46427. case 2:
  46428. _b.sent();
  46429. _b.label = 3;
  46430. case 3:
  46431. _i++;
  46432. return [3 /*break*/, 1];
  46433. case 4: return [2 /*return*/];
  46434. }
  46435. });
  46436. }
  46437. function generateJsxChildren(node, getInvalidTextDiagnostic) {
  46438. var memberOffset, i, child, nameType, elem;
  46439. return __generator(this, function (_a) {
  46440. switch (_a.label) {
  46441. case 0:
  46442. if (!ts.length(node.children))
  46443. return [2 /*return*/];
  46444. memberOffset = 0;
  46445. i = 0;
  46446. _a.label = 1;
  46447. case 1:
  46448. if (!(i < node.children.length)) return [3 /*break*/, 5];
  46449. child = node.children[i];
  46450. nameType = getLiteralType(i - memberOffset);
  46451. elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
  46452. if (!elem) return [3 /*break*/, 3];
  46453. return [4 /*yield*/, elem];
  46454. case 2:
  46455. _a.sent();
  46456. return [3 /*break*/, 4];
  46457. case 3:
  46458. memberOffset++;
  46459. _a.label = 4;
  46460. case 4:
  46461. i++;
  46462. return [3 /*break*/, 1];
  46463. case 5: return [2 /*return*/];
  46464. }
  46465. });
  46466. }
  46467. function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
  46468. switch (child.kind) {
  46469. case 276 /* JsxExpression */:
  46470. // child is of the type of the expression
  46471. return { errorNode: child, innerExpression: child.expression, nameType: nameType };
  46472. case 11 /* JsxText */:
  46473. if (child.containsOnlyTriviaWhiteSpaces) {
  46474. break; // Whitespace only jsx text isn't real jsx text
  46475. }
  46476. // child is a string
  46477. return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
  46478. case 266 /* JsxElement */:
  46479. case 267 /* JsxSelfClosingElement */:
  46480. case 270 /* JsxFragment */:
  46481. // child is of type JSX.Element
  46482. return { errorNode: child, innerExpression: child, nameType: nameType };
  46483. default:
  46484. return ts.Debug.assertNever(child, "Found invalid jsx child");
  46485. }
  46486. }
  46487. function getSemanticJsxChildren(children) {
  46488. return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
  46489. }
  46490. function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
  46491. var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
  46492. var invalidTextDiagnostic;
  46493. if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
  46494. var containingElement = node.parent.parent;
  46495. var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
  46496. var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
  46497. var childrenNameType = getLiteralType(childrenPropName);
  46498. var childrenTargetType = getIndexedAccessType(target, childrenNameType);
  46499. var validChildren = getSemanticJsxChildren(containingElement.children);
  46500. if (!ts.length(validChildren)) {
  46501. return result;
  46502. }
  46503. var moreThanOneRealChildren = ts.length(validChildren) > 1;
  46504. var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
  46505. var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
  46506. if (moreThanOneRealChildren) {
  46507. if (arrayLikeTargetParts !== neverType) {
  46508. var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
  46509. var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
  46510. result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
  46511. }
  46512. else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
  46513. // arity mismatch
  46514. result = true;
  46515. var diag = error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType));
  46516. if (errorOutputContainer && errorOutputContainer.skipLogging) {
  46517. (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
  46518. }
  46519. }
  46520. }
  46521. else {
  46522. if (nonArrayLikeTargetParts !== neverType) {
  46523. var child = validChildren[0];
  46524. var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
  46525. if (elem_1) {
  46526. result = elaborateElementwise((function () { return __generator(this, function (_a) {
  46527. switch (_a.label) {
  46528. case 0: return [4 /*yield*/, elem_1];
  46529. case 1:
  46530. _a.sent();
  46531. return [2 /*return*/];
  46532. }
  46533. }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
  46534. }
  46535. }
  46536. else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
  46537. // arity mismatch
  46538. result = true;
  46539. var diag = error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType));
  46540. if (errorOutputContainer && errorOutputContainer.skipLogging) {
  46541. (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
  46542. }
  46543. }
  46544. }
  46545. }
  46546. return result;
  46547. function getInvalidTextualChildDiagnostic() {
  46548. if (!invalidTextDiagnostic) {
  46549. var tagNameText = ts.getTextOfNode(node.parent.tagName);
  46550. var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
  46551. var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
  46552. var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
  46553. var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2;
  46554. invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
  46555. }
  46556. return invalidTextDiagnostic;
  46557. }
  46558. }
  46559. function generateLimitedTupleElements(node, target) {
  46560. var len, i, elem, nameType;
  46561. return __generator(this, function (_a) {
  46562. switch (_a.label) {
  46563. case 0:
  46564. len = ts.length(node.elements);
  46565. if (!len)
  46566. return [2 /*return*/];
  46567. i = 0;
  46568. _a.label = 1;
  46569. case 1:
  46570. if (!(i < len)) return [3 /*break*/, 4];
  46571. // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature
  46572. if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
  46573. return [3 /*break*/, 3];
  46574. elem = node.elements[i];
  46575. if (ts.isOmittedExpression(elem))
  46576. return [3 /*break*/, 3];
  46577. nameType = getLiteralType(i);
  46578. return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
  46579. case 2:
  46580. _a.sent();
  46581. _a.label = 3;
  46582. case 3:
  46583. i++;
  46584. return [3 /*break*/, 1];
  46585. case 4: return [2 /*return*/];
  46586. }
  46587. });
  46588. }
  46589. function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
  46590. if (target.flags & 131068 /* Primitive */)
  46591. return false;
  46592. if (isTupleLikeType(source)) {
  46593. return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
  46594. }
  46595. // recreate a tuple from the elements, if possible
  46596. var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
  46597. if (isTupleLikeType(tupleizedType)) {
  46598. return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
  46599. }
  46600. return false;
  46601. }
  46602. function generateObjectLiteralElements(node) {
  46603. var _i, _a, prop, type, _b;
  46604. return __generator(this, function (_c) {
  46605. switch (_c.label) {
  46606. case 0:
  46607. if (!ts.length(node.properties))
  46608. return [2 /*return*/];
  46609. _i = 0, _a = node.properties;
  46610. _c.label = 1;
  46611. case 1:
  46612. if (!(_i < _a.length)) return [3 /*break*/, 8];
  46613. prop = _a[_i];
  46614. if (ts.isSpreadAssignment(prop))
  46615. return [3 /*break*/, 7];
  46616. type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
  46617. if (!type || (type.flags & 131072 /* Never */)) {
  46618. return [3 /*break*/, 7];
  46619. }
  46620. _b = prop.kind;
  46621. switch (_b) {
  46622. case 164 /* SetAccessor */: return [3 /*break*/, 2];
  46623. case 163 /* GetAccessor */: return [3 /*break*/, 2];
  46624. case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
  46625. case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
  46626. case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
  46627. }
  46628. return [3 /*break*/, 6];
  46629. case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
  46630. case 3:
  46631. _c.sent();
  46632. return [3 /*break*/, 7];
  46633. case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }];
  46634. case 5:
  46635. _c.sent();
  46636. return [3 /*break*/, 7];
  46637. case 6:
  46638. ts.Debug.assertNever(prop);
  46639. _c.label = 7;
  46640. case 7:
  46641. _i++;
  46642. return [3 /*break*/, 1];
  46643. case 8: return [2 /*return*/];
  46644. }
  46645. });
  46646. }
  46647. function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
  46648. if (target.flags & 131068 /* Primitive */)
  46649. return false;
  46650. return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
  46651. }
  46652. /**
  46653. * This is *not* a bi-directional relationship.
  46654. * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
  46655. */
  46656. function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
  46657. return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
  46658. }
  46659. function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
  46660. return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false,
  46661. /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
  46662. }
  46663. /**
  46664. * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
  46665. */
  46666. function isAnySignature(s) {
  46667. return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
  46668. signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
  46669. isTypeAny(getReturnTypeOfSignature(s));
  46670. }
  46671. /**
  46672. * See signatureRelatedTo, compareSignaturesIdentical
  46673. */
  46674. function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
  46675. // TODO (drosen): De-duplicate code between related functions.
  46676. if (source === target) {
  46677. return -1 /* True */;
  46678. }
  46679. if (isAnySignature(target)) {
  46680. return -1 /* True */;
  46681. }
  46682. var targetCount = getParameterCount(target);
  46683. var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
  46684. (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
  46685. if (sourceHasMoreParameters) {
  46686. return 0 /* False */;
  46687. }
  46688. if (source.typeParameters && source.typeParameters !== target.typeParameters) {
  46689. target = getCanonicalSignature(target);
  46690. source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
  46691. }
  46692. var sourceCount = getParameterCount(source);
  46693. var sourceRestType = getNonArrayRestType(source);
  46694. var targetRestType = getNonArrayRestType(target);
  46695. if (sourceRestType || targetRestType) {
  46696. void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
  46697. }
  46698. if (sourceRestType && targetRestType && sourceCount !== targetCount) {
  46699. // We're not able to relate misaligned complex rest parameters
  46700. return 0 /* False */;
  46701. }
  46702. var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
  46703. var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
  46704. kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
  46705. var result = -1 /* True */;
  46706. var sourceThisType = getThisTypeOfSignature(source);
  46707. if (sourceThisType && sourceThisType !== voidType) {
  46708. var targetThisType = getThisTypeOfSignature(target);
  46709. if (targetThisType) {
  46710. // void sources are assignable to anything.
  46711. var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
  46712. || compareTypes(targetThisType, sourceThisType, reportErrors);
  46713. if (!related) {
  46714. if (reportErrors) {
  46715. errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
  46716. }
  46717. return 0 /* False */;
  46718. }
  46719. result &= related;
  46720. }
  46721. }
  46722. var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
  46723. var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
  46724. for (var i = 0; i < paramCount; i++) {
  46725. var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
  46726. var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
  46727. // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
  46728. // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
  46729. // they naturally relate only contra-variantly). However, if the source and target parameters both have
  46730. // function types with a single call signature, we know we are relating two callback parameters. In
  46731. // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
  46732. // similar to return values, callback parameters are output positions. This means that a Promise<T>,
  46733. // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
  46734. // with respect to T.
  46735. var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
  46736. var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
  46737. var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
  46738. (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
  46739. var related = callbacks ?
  46740. compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
  46741. !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
  46742. // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
  46743. if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
  46744. related = 0 /* False */;
  46745. }
  46746. if (!related) {
  46747. if (reportErrors) {
  46748. errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
  46749. }
  46750. return 0 /* False */;
  46751. }
  46752. result &= related;
  46753. }
  46754. if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
  46755. // If a signature resolution is already in-flight, skip issuing a circularity error
  46756. // here and just use the `any` type directly
  46757. var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
  46758. : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
  46759. : getReturnTypeOfSignature(target);
  46760. if (targetReturnType === voidType) {
  46761. return result;
  46762. }
  46763. var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
  46764. : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
  46765. : getReturnTypeOfSignature(source);
  46766. // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
  46767. var targetTypePredicate = getTypePredicateOfSignature(target);
  46768. if (targetTypePredicate) {
  46769. var sourceTypePredicate = getTypePredicateOfSignature(source);
  46770. if (sourceTypePredicate) {
  46771. result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
  46772. }
  46773. else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
  46774. if (reportErrors) {
  46775. errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
  46776. }
  46777. return 0 /* False */;
  46778. }
  46779. }
  46780. else {
  46781. // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
  46782. // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
  46783. // wouldn't be co-variant for T without this rule.
  46784. result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
  46785. compareTypes(sourceReturnType, targetReturnType, reportErrors);
  46786. if (!result && reportErrors && incompatibleErrorReporter) {
  46787. incompatibleErrorReporter(sourceReturnType, targetReturnType);
  46788. }
  46789. }
  46790. }
  46791. return result;
  46792. }
  46793. function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
  46794. if (source.kind !== target.kind) {
  46795. if (reportErrors) {
  46796. errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
  46797. errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
  46798. }
  46799. return 0 /* False */;
  46800. }
  46801. if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
  46802. if (source.parameterIndex !== target.parameterIndex) {
  46803. if (reportErrors) {
  46804. errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
  46805. errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
  46806. }
  46807. return 0 /* False */;
  46808. }
  46809. }
  46810. var related = source.type === target.type ? -1 /* True */ :
  46811. source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
  46812. 0 /* False */;
  46813. if (related === 0 /* False */ && reportErrors) {
  46814. errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
  46815. }
  46816. return related;
  46817. }
  46818. function isImplementationCompatibleWithOverload(implementation, overload) {
  46819. var erasedSource = getErasedSignature(implementation);
  46820. var erasedTarget = getErasedSignature(overload);
  46821. // First see if the return types are compatible in either direction.
  46822. var sourceReturnType = getReturnTypeOfSignature(erasedSource);
  46823. var targetReturnType = getReturnTypeOfSignature(erasedTarget);
  46824. if (targetReturnType === voidType
  46825. || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
  46826. || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
  46827. return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
  46828. }
  46829. return false;
  46830. }
  46831. function isEmptyResolvedType(t) {
  46832. return t !== anyFunctionType &&
  46833. t.properties.length === 0 &&
  46834. t.callSignatures.length === 0 &&
  46835. t.constructSignatures.length === 0 &&
  46836. !t.stringIndexInfo &&
  46837. !t.numberIndexInfo;
  46838. }
  46839. function isEmptyObjectType(type) {
  46840. return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
  46841. type.flags & 67108864 /* NonPrimitive */ ? true :
  46842. type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
  46843. type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
  46844. false;
  46845. }
  46846. function isEmptyAnonymousObjectType(type) {
  46847. return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
  46848. }
  46849. function isStringIndexSignatureOnlyType(type) {
  46850. return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
  46851. type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
  46852. false;
  46853. }
  46854. function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
  46855. if (sourceSymbol === targetSymbol) {
  46856. return true;
  46857. }
  46858. var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
  46859. var entry = enumRelation.get(id);
  46860. if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
  46861. return !!(entry & 1 /* Succeeded */);
  46862. }
  46863. if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
  46864. enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
  46865. return false;
  46866. }
  46867. var targetEnumType = getTypeOfSymbol(targetSymbol);
  46868. for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
  46869. var property = _a[_i];
  46870. if (property.flags & 8 /* EnumMember */) {
  46871. var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
  46872. if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
  46873. if (errorReporter) {
  46874. errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
  46875. enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
  46876. }
  46877. else {
  46878. enumRelation.set(id, 2 /* Failed */);
  46879. }
  46880. return false;
  46881. }
  46882. }
  46883. }
  46884. enumRelation.set(id, 1 /* Succeeded */);
  46885. return true;
  46886. }
  46887. function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
  46888. var s = source.flags;
  46889. var t = target.flags;
  46890. if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
  46891. return true;
  46892. if (t & 131072 /* Never */)
  46893. return false;
  46894. if (s & 132 /* StringLike */ && t & 4 /* String */)
  46895. return true;
  46896. if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
  46897. t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
  46898. source.value === target.value)
  46899. return true;
  46900. if (s & 296 /* NumberLike */ && t & 8 /* Number */)
  46901. return true;
  46902. if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
  46903. t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
  46904. source.value === target.value)
  46905. return true;
  46906. if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
  46907. return true;
  46908. if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
  46909. return true;
  46910. if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
  46911. return true;
  46912. if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
  46913. return true;
  46914. if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
  46915. if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
  46916. return true;
  46917. if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
  46918. source.value === target.value &&
  46919. isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
  46920. return true;
  46921. }
  46922. if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
  46923. return true;
  46924. if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
  46925. return true;
  46926. if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
  46927. return true;
  46928. if (relation === assignableRelation || relation === comparableRelation) {
  46929. if (s & 1 /* Any */)
  46930. return true;
  46931. // Type number or any numeric literal type is assignable to any numeric enum type or any
  46932. // numeric enum literal type. This rule exists for backwards compatibility reasons because
  46933. // bit-flag enum types sometimes look like literal enum types with numeric literal values.
  46934. if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
  46935. return true;
  46936. }
  46937. return false;
  46938. }
  46939. function isTypeRelatedTo(source, target, relation) {
  46940. if (isFreshLiteralType(source)) {
  46941. source = source.regularType;
  46942. }
  46943. if (isFreshLiteralType(target)) {
  46944. target = target.regularType;
  46945. }
  46946. if (source === target ||
  46947. relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
  46948. relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) {
  46949. return true;
  46950. }
  46951. if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
  46952. var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
  46953. if (related !== undefined) {
  46954. return !!(related & 1 /* Succeeded */);
  46955. }
  46956. }
  46957. if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
  46958. return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
  46959. }
  46960. return false;
  46961. }
  46962. function isIgnoredJsxProperty(source, sourceProp) {
  46963. return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
  46964. }
  46965. function getNormalizedType(type, writing) {
  46966. return isFreshLiteralType(type) ? type.regularType :
  46967. ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
  46968. type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute :
  46969. type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
  46970. type;
  46971. }
  46972. /**
  46973. * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
  46974. * @param source The left-hand-side of the relation.
  46975. * @param target The right-hand-side of the relation.
  46976. * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
  46977. * Used as both to determine which checks are performed and as a cache of previously computed results.
  46978. * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
  46979. * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
  46980. * @param containingMessageChain A chain of errors to prepend any new errors found.
  46981. * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
  46982. */
  46983. function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
  46984. var errorInfo;
  46985. var relatedInfo;
  46986. var maybeKeys;
  46987. var sourceStack;
  46988. var targetStack;
  46989. var maybeCount = 0;
  46990. var depth = 0;
  46991. var expandingFlags = 0 /* None */;
  46992. var overflow = false;
  46993. var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
  46994. var lastSkippedInfo;
  46995. var incompatibleStack = [];
  46996. ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
  46997. var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
  46998. if (incompatibleStack.length) {
  46999. reportIncompatibleStack();
  47000. }
  47001. if (overflow) {
  47002. var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
  47003. if (errorOutputContainer) {
  47004. (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
  47005. }
  47006. }
  47007. else if (errorInfo) {
  47008. if (containingMessageChain) {
  47009. var chain = containingMessageChain();
  47010. if (chain) {
  47011. ts.concatenateDiagnosticMessageChains(chain, errorInfo);
  47012. errorInfo = chain;
  47013. }
  47014. }
  47015. var relatedInformation = void 0;
  47016. // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
  47017. if (headMessage && errorNode && !result && source.symbol) {
  47018. var links = getSymbolLinks(source.symbol);
  47019. if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
  47020. var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
  47021. if (helpfulRetry) {
  47022. // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
  47023. var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead);
  47024. relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
  47025. }
  47026. }
  47027. }
  47028. var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
  47029. if (relatedInfo) {
  47030. ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
  47031. }
  47032. if (errorOutputContainer) {
  47033. (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
  47034. }
  47035. if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
  47036. diagnostics.add(diag);
  47037. }
  47038. }
  47039. if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
  47040. ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
  47041. }
  47042. return result !== 0 /* False */;
  47043. function resetErrorInfo(saved) {
  47044. errorInfo = saved.errorInfo;
  47045. lastSkippedInfo = saved.lastSkippedInfo;
  47046. incompatibleStack = saved.incompatibleStack;
  47047. overrideNextErrorInfo = saved.overrideNextErrorInfo;
  47048. relatedInfo = saved.relatedInfo;
  47049. }
  47050. function captureErrorCalculationState() {
  47051. return {
  47052. errorInfo: errorInfo,
  47053. lastSkippedInfo: lastSkippedInfo,
  47054. incompatibleStack: incompatibleStack.slice(),
  47055. overrideNextErrorInfo: overrideNextErrorInfo,
  47056. relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
  47057. };
  47058. }
  47059. function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
  47060. overrideNextErrorInfo++; // Suppress the next relation error
  47061. lastSkippedInfo = undefined; // Reset skipped info cache
  47062. incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
  47063. }
  47064. function reportIncompatibleStack() {
  47065. var stack = incompatibleStack;
  47066. incompatibleStack = [];
  47067. var info = lastSkippedInfo;
  47068. lastSkippedInfo = undefined;
  47069. if (stack.length === 1) {
  47070. reportError.apply(void 0, stack[0]);
  47071. if (info) {
  47072. // Actually do the last relation error
  47073. reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
  47074. }
  47075. return;
  47076. }
  47077. // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
  47078. // we can build from left to right
  47079. var path = "";
  47080. var secondaryRootErrors = [];
  47081. while (stack.length) {
  47082. var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
  47083. switch (msg.code) {
  47084. case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
  47085. // Parenthesize a `new` if there is one
  47086. if (path.indexOf("new ") === 0) {
  47087. path = "(" + path + ")";
  47088. }
  47089. var str = "" + args[0];
  47090. // If leading, just print back the arg (irrespective of if it's a valid identifier)
  47091. if (path.length === 0) {
  47092. path = "" + str;
  47093. }
  47094. // Otherwise write a dotted name if possible
  47095. else if (ts.isIdentifierText(str, compilerOptions.target)) {
  47096. path = path + "." + str;
  47097. }
  47098. // Failing that, check if the name is already a computed name
  47099. else if (str[0] === "[" && str[str.length - 1] === "]") {
  47100. path = "" + path + str;
  47101. }
  47102. // And finally write out a computed name as a last resort
  47103. else {
  47104. path = path + "[" + str + "]";
  47105. }
  47106. break;
  47107. }
  47108. case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
  47109. case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
  47110. case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
  47111. case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
  47112. if (path.length === 0) {
  47113. // Don't flatten signature compatability errors at the start of a chain - instead prefer
  47114. // to unify (the with no arguments bit is excessive for printback) and print them back
  47115. var mappedMsg = msg;
  47116. if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
  47117. mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
  47118. }
  47119. else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
  47120. mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
  47121. }
  47122. secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
  47123. }
  47124. else {
  47125. var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
  47126. msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
  47127. ? "new "
  47128. : "";
  47129. var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
  47130. msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
  47131. ? ""
  47132. : "...";
  47133. path = "" + prefix + path + "(" + params + ")";
  47134. }
  47135. break;
  47136. }
  47137. default:
  47138. return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
  47139. }
  47140. }
  47141. if (path) {
  47142. reportError(path[path.length - 1] === ")"
  47143. ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
  47144. : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
  47145. }
  47146. else {
  47147. // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
  47148. secondaryRootErrors.shift();
  47149. }
  47150. for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
  47151. var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
  47152. var originalValue = msg.elidedInCompatabilityPyramid;
  47153. msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
  47154. reportError.apply(void 0, __spreadArrays([msg], args));
  47155. msg.elidedInCompatabilityPyramid = originalValue;
  47156. }
  47157. if (info) {
  47158. // Actually do the last relation error
  47159. reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
  47160. }
  47161. }
  47162. function reportError(message, arg0, arg1, arg2, arg3) {
  47163. ts.Debug.assert(!!errorNode);
  47164. if (incompatibleStack.length)
  47165. reportIncompatibleStack();
  47166. if (message.elidedInCompatabilityPyramid)
  47167. return;
  47168. errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
  47169. }
  47170. function associateRelatedInfo(info) {
  47171. ts.Debug.assert(!!errorInfo);
  47172. if (!relatedInfo) {
  47173. relatedInfo = [info];
  47174. }
  47175. else {
  47176. relatedInfo.push(info);
  47177. }
  47178. }
  47179. function reportRelationError(message, source, target) {
  47180. if (incompatibleStack.length)
  47181. reportIncompatibleStack();
  47182. var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
  47183. if (target.flags & 262144 /* TypeParameter */ && target.immediateBaseConstraint !== undefined && isTypeAssignableTo(source, target.immediateBaseConstraint)) {
  47184. reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, sourceType, targetType, typeToString(target.immediateBaseConstraint));
  47185. }
  47186. if (!message) {
  47187. if (relation === comparableRelation) {
  47188. message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
  47189. }
  47190. else if (sourceType === targetType) {
  47191. message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
  47192. }
  47193. else {
  47194. message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
  47195. }
  47196. }
  47197. reportError(message, sourceType, targetType);
  47198. }
  47199. function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
  47200. var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
  47201. var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
  47202. if ((globalStringType === source && stringType === target) ||
  47203. (globalNumberType === source && numberType === target) ||
  47204. (globalBooleanType === source && booleanType === target) ||
  47205. (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
  47206. reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
  47207. }
  47208. }
  47209. /**
  47210. * Try and elaborate array and tuple errors. Returns false
  47211. * if we have found an elaboration, or we should ignore
  47212. * any other elaborations when relating the `source` and
  47213. * `target` types.
  47214. */
  47215. function tryElaborateArrayLikeErrors(source, target, reportErrors) {
  47216. /**
  47217. * The spec for elaboration is:
  47218. * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
  47219. * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
  47220. * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
  47221. * - If the source an array then skip property elaborations if the target is a tuple.
  47222. */
  47223. if (isTupleType(source)) {
  47224. if (source.target.readonly && isMutableArrayOrTuple(target)) {
  47225. if (reportErrors) {
  47226. reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
  47227. }
  47228. return false;
  47229. }
  47230. return isTupleType(target) || isArrayType(target);
  47231. }
  47232. if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
  47233. if (reportErrors) {
  47234. reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
  47235. }
  47236. return false;
  47237. }
  47238. if (isTupleType(target)) {
  47239. return isArrayType(source);
  47240. }
  47241. return true;
  47242. }
  47243. /**
  47244. * Compare two types and return
  47245. * * Ternary.True if they are related with no assumptions,
  47246. * * Ternary.Maybe if they are related with assumptions of other relationships, or
  47247. * * Ternary.False if they are not related.
  47248. */
  47249. function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
  47250. if (reportErrors === void 0) { reportErrors = false; }
  47251. if (intersectionState === void 0) { intersectionState = 0 /* None */; }
  47252. // Normalize the source and target types: Turn fresh literal types into regular literal types,
  47253. // turn deferred type references into regular type references, simplify indexed access and
  47254. // conditional types, and resolve substitution types to either the substitution (on the source
  47255. // side) or the type variable (on the target side).
  47256. var source = getNormalizedType(originalSource, /*writing*/ false);
  47257. var target = getNormalizedType(originalTarget, /*writing*/ true);
  47258. // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
  47259. // If so, reporting the `null` and `undefined` in the type is hardly useful.
  47260. // First, see if we're even relating an object type to a union.
  47261. // Then see if the target is stripped down to a single non-union type.
  47262. // Note
  47263. // * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
  47264. // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
  47265. // when dealing with generics.
  47266. // * We also don't deal with primitive source types, since we already halt elaboration below.
  47267. if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
  47268. target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
  47269. var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
  47270. if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
  47271. target = nullStrippedTarget;
  47272. }
  47273. }
  47274. // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases
  47275. if (source === target)
  47276. return -1 /* True */;
  47277. if (relation === identityRelation) {
  47278. return isIdenticalTo(source, target);
  47279. }
  47280. if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
  47281. isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
  47282. return -1 /* True */;
  47283. var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
  47284. var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
  47285. if (isPerformingExcessPropertyChecks) {
  47286. if (hasExcessProperties(source, target, reportErrors)) {
  47287. if (reportErrors) {
  47288. reportRelationError(headMessage, source, target);
  47289. }
  47290. return 0 /* False */;
  47291. }
  47292. }
  47293. var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
  47294. source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
  47295. target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
  47296. (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
  47297. if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
  47298. if (reportErrors) {
  47299. var calls = getSignaturesOfType(source, 0 /* Call */);
  47300. var constructs = getSignaturesOfType(source, 1 /* Construct */);
  47301. if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
  47302. constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
  47303. reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target));
  47304. }
  47305. else {
  47306. reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
  47307. }
  47308. }
  47309. return 0 /* False */;
  47310. }
  47311. var result = 0 /* False */;
  47312. var saveErrorInfo = captureErrorCalculationState();
  47313. // Note that these checks are specifically ordered to produce correct results. In particular,
  47314. // we need to deconstruct unions before intersections (because unions are always at the top),
  47315. // and we need to handle "each" relations before "some" relations for the same kind of type.
  47316. if (source.flags & 1048576 /* Union */) {
  47317. result = relation === comparableRelation ?
  47318. someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
  47319. eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */));
  47320. }
  47321. else {
  47322. if (target.flags & 1048576 /* Union */) {
  47323. result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
  47324. }
  47325. else if (target.flags & 2097152 /* Intersection */) {
  47326. result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
  47327. if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks)) {
  47328. // Validate against excess props using the original `source`
  47329. if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */)) {
  47330. return 0 /* False */;
  47331. }
  47332. }
  47333. }
  47334. else if (source.flags & 2097152 /* Intersection */) {
  47335. // Check to see if any constituents of the intersection are immediately related to the target.
  47336. //
  47337. // Don't report errors though. Checking whether a constituent is related to the source is not actually
  47338. // useful and leads to some confusing error messages. Instead it is better to let the below checks
  47339. // take care of this, or to not elaborate at all. For instance,
  47340. //
  47341. // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
  47342. //
  47343. // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
  47344. // than to report that 'D' is not assignable to 'A' or 'B'.
  47345. //
  47346. // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
  47347. // breaking the intersection apart.
  47348. result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
  47349. }
  47350. if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
  47351. if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
  47352. resetErrorInfo(saveErrorInfo);
  47353. }
  47354. }
  47355. }
  47356. if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
  47357. // The combined constraint of an intersection type is the intersection of the constraints of
  47358. // the constituents. When an intersection type contains instantiable types with union type
  47359. // constraints, there are situations where we need to examine the combined constraint. One is
  47360. // when the target is a union type. Another is when the intersection contains types belonging
  47361. // to one of the disjoint domains. For example, given type variables T and U, each with the
  47362. // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
  47363. // we need to check this constraint against a union on the target side. Also, given a type
  47364. // variable V constrained to 'string | number', 'V & number' has a combined constraint of
  47365. // 'string & number | number & number' which reduces to just 'number'.
  47366. // This also handles type parameters, as a type parameter with a union constraint compared against a union
  47367. // needs to have its constraint hoisted into an intersection with said type parameter, this way
  47368. // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
  47369. // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
  47370. var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
  47371. if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
  47372. if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
  47373. // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
  47374. if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
  47375. resetErrorInfo(saveErrorInfo);
  47376. }
  47377. }
  47378. }
  47379. }
  47380. if (!result && reportErrors) {
  47381. source = originalSource.aliasSymbol ? originalSource : source;
  47382. target = originalTarget.aliasSymbol ? originalTarget : target;
  47383. var maybeSuppress = overrideNextErrorInfo > 0;
  47384. if (maybeSuppress) {
  47385. overrideNextErrorInfo--;
  47386. }
  47387. if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
  47388. var currentError = errorInfo;
  47389. tryElaborateArrayLikeErrors(source, target, reportErrors);
  47390. if (errorInfo !== currentError) {
  47391. maybeSuppress = !!errorInfo;
  47392. }
  47393. }
  47394. if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
  47395. tryElaborateErrorsForPrimitivesAndObjects(source, target);
  47396. }
  47397. else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
  47398. reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
  47399. }
  47400. else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
  47401. var targetTypes = target.types;
  47402. var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
  47403. var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
  47404. if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
  47405. (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
  47406. // do not report top error
  47407. return result;
  47408. }
  47409. }
  47410. if (!headMessage && maybeSuppress) {
  47411. lastSkippedInfo = [source, target];
  47412. // Used by, eg, missing property checking to replace the top-level message with a more informative one
  47413. return result;
  47414. }
  47415. reportRelationError(headMessage, source, target);
  47416. }
  47417. return result;
  47418. }
  47419. function isIdenticalTo(source, target) {
  47420. var result;
  47421. var flags = source.flags & target.flags;
  47422. if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) {
  47423. return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
  47424. }
  47425. if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
  47426. if (result = eachTypeRelatedToSomeType(source, target)) {
  47427. if (result &= eachTypeRelatedToSomeType(target, source)) {
  47428. return result;
  47429. }
  47430. }
  47431. }
  47432. return 0 /* False */;
  47433. }
  47434. function getTypeOfPropertyInTypes(types, name) {
  47435. var appendPropType = function (propTypes, type) {
  47436. type = getApparentType(type);
  47437. var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
  47438. var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
  47439. return ts.append(propTypes, propType);
  47440. };
  47441. return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
  47442. }
  47443. function hasExcessProperties(source, target, reportErrors) {
  47444. if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
  47445. return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
  47446. }
  47447. var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
  47448. if ((relation === assignableRelation || relation === comparableRelation) &&
  47449. (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
  47450. return false;
  47451. }
  47452. var reducedTarget = target;
  47453. var checkTypes;
  47454. if (target.flags & 1048576 /* Union */) {
  47455. reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
  47456. checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
  47457. }
  47458. var _loop_11 = function (prop) {
  47459. if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
  47460. if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
  47461. if (reportErrors) {
  47462. // Report error in terms of object types in the target as those are the only ones
  47463. // we check in isKnownProperty.
  47464. var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
  47465. // We know *exactly* where things went wrong when comparing the types.
  47466. // Use this property as the error node as this will be more helpful in
  47467. // reasoning about what went wrong.
  47468. if (!errorNode)
  47469. return { value: ts.Debug.fail() };
  47470. if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
  47471. // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
  47472. // However, using an object-literal error message will be very confusing to the users so we give different a message.
  47473. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
  47474. if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
  47475. // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
  47476. // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
  47477. errorNode = prop.valueDeclaration.name;
  47478. }
  47479. reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
  47480. }
  47481. else {
  47482. // use the property's value declaration if the property is assigned inside the literal itself
  47483. var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
  47484. var suggestion = void 0;
  47485. if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
  47486. var propDeclaration = prop.valueDeclaration;
  47487. ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
  47488. errorNode = propDeclaration;
  47489. var name = propDeclaration.name;
  47490. if (ts.isIdentifier(name)) {
  47491. suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
  47492. }
  47493. }
  47494. if (suggestion !== undefined) {
  47495. reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion);
  47496. }
  47497. else {
  47498. reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
  47499. }
  47500. }
  47501. }
  47502. return { value: true };
  47503. }
  47504. if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
  47505. if (reportErrors) {
  47506. reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
  47507. }
  47508. return { value: true };
  47509. }
  47510. }
  47511. };
  47512. for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
  47513. var prop = _a[_i];
  47514. var state_4 = _loop_11(prop);
  47515. if (typeof state_4 === "object")
  47516. return state_4.value;
  47517. }
  47518. return false;
  47519. }
  47520. function shouldCheckAsExcessProperty(prop, container) {
  47521. return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
  47522. }
  47523. function eachTypeRelatedToSomeType(source, target) {
  47524. var result = -1 /* True */;
  47525. var sourceTypes = source.types;
  47526. for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
  47527. var sourceType = sourceTypes_1[_i];
  47528. var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
  47529. if (!related) {
  47530. return 0 /* False */;
  47531. }
  47532. result &= related;
  47533. }
  47534. return result;
  47535. }
  47536. function typeRelatedToSomeType(source, target, reportErrors) {
  47537. var targetTypes = target.types;
  47538. if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
  47539. return -1 /* True */;
  47540. }
  47541. for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
  47542. var type = targetTypes_1[_i];
  47543. var related = isRelatedTo(source, type, /*reportErrors*/ false);
  47544. if (related) {
  47545. return related;
  47546. }
  47547. }
  47548. if (reportErrors) {
  47549. var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
  47550. isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
  47551. }
  47552. return 0 /* False */;
  47553. }
  47554. function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
  47555. var result = -1 /* True */;
  47556. var targetTypes = target.types;
  47557. for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
  47558. var targetType = targetTypes_2[_i];
  47559. var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
  47560. if (!related) {
  47561. return 0 /* False */;
  47562. }
  47563. result &= related;
  47564. }
  47565. return result;
  47566. }
  47567. function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
  47568. var sourceTypes = source.types;
  47569. if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
  47570. return -1 /* True */;
  47571. }
  47572. var len = sourceTypes.length;
  47573. for (var i = 0; i < len; i++) {
  47574. var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
  47575. if (related) {
  47576. return related;
  47577. }
  47578. }
  47579. return 0 /* False */;
  47580. }
  47581. function eachTypeRelatedToType(source, target, reportErrors) {
  47582. var result = -1 /* True */;
  47583. var sourceTypes = source.types;
  47584. for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) {
  47585. var sourceType = sourceTypes_2[_i];
  47586. var related = isRelatedTo(sourceType, target, reportErrors);
  47587. if (!related) {
  47588. return 0 /* False */;
  47589. }
  47590. result &= related;
  47591. }
  47592. return result;
  47593. }
  47594. function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
  47595. if (sources === void 0) { sources = ts.emptyArray; }
  47596. if (targets === void 0) { targets = ts.emptyArray; }
  47597. if (variances === void 0) { variances = ts.emptyArray; }
  47598. if (sources.length !== targets.length && relation === identityRelation) {
  47599. return 0 /* False */;
  47600. }
  47601. var length = sources.length <= targets.length ? sources.length : targets.length;
  47602. var result = -1 /* True */;
  47603. for (var i = 0; i < length; i++) {
  47604. // When variance information isn't available we default to covariance. This happens
  47605. // in the process of computing variance information for recursive types and when
  47606. // comparing 'this' type arguments.
  47607. var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
  47608. var variance = varianceFlags & 7 /* VarianceMask */;
  47609. // We ignore arguments for independent type parameters (because they're never witnessed).
  47610. if (variance !== 4 /* Independent */) {
  47611. var s = sources[i];
  47612. var t = targets[i];
  47613. var related = -1 /* True */;
  47614. if (varianceFlags & 8 /* Unmeasurable */) {
  47615. // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
  47616. // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
  47617. // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
  47618. related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
  47619. }
  47620. else if (variance === 1 /* Covariant */) {
  47621. related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
  47622. }
  47623. else if (variance === 2 /* Contravariant */) {
  47624. related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
  47625. }
  47626. else if (variance === 3 /* Bivariant */) {
  47627. // In the bivariant case we first compare contravariantly without reporting
  47628. // errors. Then, if that doesn't succeed, we compare covariantly with error
  47629. // reporting. Thus, error elaboration will be based on the the covariant check,
  47630. // which is generally easier to reason about.
  47631. related = isRelatedTo(t, s, /*reportErrors*/ false);
  47632. if (!related) {
  47633. related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
  47634. }
  47635. }
  47636. else {
  47637. // In the invariant case we first compare covariantly, and only when that
  47638. // succeeds do we proceed to compare contravariantly. Thus, error elaboration
  47639. // will typically be based on the covariant check.
  47640. related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
  47641. if (related) {
  47642. related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
  47643. }
  47644. }
  47645. if (!related) {
  47646. return 0 /* False */;
  47647. }
  47648. result &= related;
  47649. }
  47650. }
  47651. return result;
  47652. }
  47653. // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
  47654. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
  47655. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
  47656. // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
  47657. // and issue an error. Otherwise, actually compare the structure of the two types.
  47658. function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
  47659. if (overflow) {
  47660. return 0 /* False */;
  47661. }
  47662. var id = getRelationKey(source, target, intersectionState, relation);
  47663. var entry = relation.get(id);
  47664. if (entry !== undefined) {
  47665. if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
  47666. // We are elaborating errors and the cached result is an unreported failure. The result will be reported
  47667. // as a failure, and should be updated as a reported failure by the bottom of this function.
  47668. }
  47669. else {
  47670. if (outofbandVarianceMarkerHandler) {
  47671. // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
  47672. var saved = entry & 24 /* ReportsMask */;
  47673. if (saved & 8 /* ReportsUnmeasurable */) {
  47674. instantiateType(source, reportUnmeasurableMarkers);
  47675. }
  47676. if (saved & 16 /* ReportsUnreliable */) {
  47677. instantiateType(source, reportUnreliableMarkers);
  47678. }
  47679. }
  47680. return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
  47681. }
  47682. }
  47683. if (!maybeKeys) {
  47684. maybeKeys = [];
  47685. sourceStack = [];
  47686. targetStack = [];
  47687. }
  47688. else {
  47689. for (var i = 0; i < maybeCount; i++) {
  47690. // If source and target are already being compared, consider them related with assumptions
  47691. if (id === maybeKeys[i]) {
  47692. return 1 /* Maybe */;
  47693. }
  47694. }
  47695. if (depth === 100) {
  47696. overflow = true;
  47697. return 0 /* False */;
  47698. }
  47699. }
  47700. var maybeStart = maybeCount;
  47701. maybeKeys[maybeCount] = id;
  47702. maybeCount++;
  47703. sourceStack[depth] = source;
  47704. targetStack[depth] = target;
  47705. depth++;
  47706. var saveExpandingFlags = expandingFlags;
  47707. if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
  47708. expandingFlags |= 1 /* Source */;
  47709. if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
  47710. expandingFlags |= 2 /* Target */;
  47711. var originalHandler;
  47712. var propagatingVarianceFlags = 0;
  47713. if (outofbandVarianceMarkerHandler) {
  47714. originalHandler = outofbandVarianceMarkerHandler;
  47715. outofbandVarianceMarkerHandler = function (onlyUnreliable) {
  47716. propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
  47717. return originalHandler(onlyUnreliable);
  47718. };
  47719. }
  47720. var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
  47721. if (outofbandVarianceMarkerHandler) {
  47722. outofbandVarianceMarkerHandler = originalHandler;
  47723. }
  47724. expandingFlags = saveExpandingFlags;
  47725. depth--;
  47726. if (result) {
  47727. if (result === -1 /* True */ || depth === 0) {
  47728. // If result is definitely true, record all maybe keys as having succeeded
  47729. for (var i = maybeStart; i < maybeCount; i++) {
  47730. relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
  47731. }
  47732. maybeCount = maybeStart;
  47733. }
  47734. }
  47735. else {
  47736. // A false result goes straight into global cache (when something is false under
  47737. // assumptions it will also be false without assumptions)
  47738. relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
  47739. maybeCount = maybeStart;
  47740. }
  47741. return result;
  47742. }
  47743. function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
  47744. var flags = source.flags & target.flags;
  47745. if (relation === identityRelation && !(flags & 524288 /* Object */)) {
  47746. if (flags & 4194304 /* Index */) {
  47747. return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
  47748. }
  47749. var result_3 = 0 /* False */;
  47750. if (flags & 8388608 /* IndexedAccess */) {
  47751. if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
  47752. if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
  47753. return result_3;
  47754. }
  47755. }
  47756. }
  47757. if (flags & 16777216 /* Conditional */) {
  47758. if (source.root.isDistributive === target.root.isDistributive) {
  47759. if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
  47760. if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
  47761. if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
  47762. if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
  47763. return result_3;
  47764. }
  47765. }
  47766. }
  47767. }
  47768. }
  47769. }
  47770. if (flags & 33554432 /* Substitution */) {
  47771. return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
  47772. }
  47773. return 0 /* False */;
  47774. }
  47775. var result;
  47776. var originalErrorInfo;
  47777. var varianceCheckFailed = false;
  47778. var saveErrorInfo = captureErrorCalculationState();
  47779. // We limit alias variance probing to only object and conditional types since their alias behavior
  47780. // is more predictable than other, interned types, which may or may not have an alias depending on
  47781. // the order in which things were checked.
  47782. if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
  47783. source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
  47784. !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
  47785. var variances = getAliasVariances(source.aliasSymbol);
  47786. if (variances === ts.emptyArray) {
  47787. return 1 /* Maybe */;
  47788. }
  47789. var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
  47790. if (varianceResult !== undefined) {
  47791. return varianceResult;
  47792. }
  47793. }
  47794. if (target.flags & 262144 /* TypeParameter */) {
  47795. // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
  47796. if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
  47797. if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
  47798. var templateType = getTemplateTypeFromMappedType(source);
  47799. var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
  47800. if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
  47801. return result;
  47802. }
  47803. }
  47804. }
  47805. }
  47806. else if (target.flags & 4194304 /* Index */) {
  47807. // A keyof S is related to a keyof T if T is related to S.
  47808. if (source.flags & 4194304 /* Index */) {
  47809. if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
  47810. return result;
  47811. }
  47812. }
  47813. // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
  47814. // simplified form of T or, if T doesn't simplify, the constraint of T.
  47815. var constraint = getSimplifiedTypeOrConstraint(target.type);
  47816. if (constraint) {
  47817. // We require Ternary.True here such that circular constraints don't cause
  47818. // false positives. For example, given 'T extends { [K in keyof T]: string }',
  47819. // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
  47820. // related to other types.
  47821. if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
  47822. return -1 /* True */;
  47823. }
  47824. }
  47825. }
  47826. else if (target.flags & 8388608 /* IndexedAccess */) {
  47827. // A type S is related to a type T[K] if S is related to C, where C is the base
  47828. // constraint of T[K] for writing.
  47829. if (relation !== identityRelation) {
  47830. var objectType = target.objectType;
  47831. var indexType = target.indexType;
  47832. var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
  47833. var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
  47834. if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
  47835. var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
  47836. var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
  47837. if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
  47838. return result;
  47839. }
  47840. }
  47841. }
  47842. }
  47843. else if (isGenericMappedType(target)) {
  47844. // A source type T is related to a target type { [P in X]: T[P] }
  47845. var template = getTemplateTypeFromMappedType(target);
  47846. var modifiers = getMappedTypeModifiers(target);
  47847. if (!(modifiers & 8 /* ExcludeOptional */)) {
  47848. if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
  47849. template.indexType === getTypeParameterFromMappedType(target)) {
  47850. return -1 /* True */;
  47851. }
  47852. if (!isGenericMappedType(source)) {
  47853. var targetConstraint = getConstraintTypeFromMappedType(target);
  47854. var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
  47855. var includeOptional = modifiers & 4 /* IncludeOptional */;
  47856. var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
  47857. // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
  47858. // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
  47859. if (includeOptional
  47860. ? !(filteredByApplicability.flags & 131072 /* Never */)
  47861. : isRelatedTo(targetConstraint, sourceKeys)) {
  47862. var typeParameter = getTypeParameterFromMappedType(target);
  47863. var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
  47864. var indexedAccessType = getIndexedAccessType(source, indexingType);
  47865. var templateType = getTemplateTypeFromMappedType(target);
  47866. if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
  47867. return result;
  47868. }
  47869. }
  47870. originalErrorInfo = errorInfo;
  47871. resetErrorInfo(saveErrorInfo);
  47872. }
  47873. }
  47874. }
  47875. if (source.flags & 8650752 /* TypeVariable */) {
  47876. if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
  47877. // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
  47878. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
  47879. result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
  47880. }
  47881. if (result) {
  47882. resetErrorInfo(saveErrorInfo);
  47883. return result;
  47884. }
  47885. }
  47886. else {
  47887. var constraint = getConstraintOfType(source);
  47888. if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
  47889. // A type variable with no constraint is not related to the non-primitive object type.
  47890. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
  47891. resetErrorInfo(saveErrorInfo);
  47892. return result;
  47893. }
  47894. }
  47895. // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed
  47896. else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
  47897. resetErrorInfo(saveErrorInfo);
  47898. return result;
  47899. }
  47900. // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
  47901. else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
  47902. resetErrorInfo(saveErrorInfo);
  47903. return result;
  47904. }
  47905. }
  47906. }
  47907. else if (source.flags & 4194304 /* Index */) {
  47908. if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
  47909. resetErrorInfo(saveErrorInfo);
  47910. return result;
  47911. }
  47912. }
  47913. else if (source.flags & 16777216 /* Conditional */) {
  47914. if (target.flags & 16777216 /* Conditional */) {
  47915. // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
  47916. // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
  47917. // and Y1 is related to Y2.
  47918. var sourceParams = source.root.inferTypeParameters;
  47919. var sourceExtends = source.extendsType;
  47920. var mapper = void 0;
  47921. if (sourceParams) {
  47922. // If the source has infer type parameters, we instantiate them in the context of the target
  47923. var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
  47924. inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
  47925. sourceExtends = instantiateType(sourceExtends, ctx.mapper);
  47926. mapper = ctx.mapper;
  47927. }
  47928. if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
  47929. (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
  47930. if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
  47931. result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
  47932. }
  47933. if (result) {
  47934. resetErrorInfo(saveErrorInfo);
  47935. return result;
  47936. }
  47937. }
  47938. }
  47939. else {
  47940. var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
  47941. if (distributiveConstraint) {
  47942. if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
  47943. resetErrorInfo(saveErrorInfo);
  47944. return result;
  47945. }
  47946. }
  47947. var defaultConstraint = getDefaultConstraintOfConditionalType(source);
  47948. if (defaultConstraint) {
  47949. if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
  47950. resetErrorInfo(saveErrorInfo);
  47951. return result;
  47952. }
  47953. }
  47954. }
  47955. }
  47956. else {
  47957. // An empty object type is related to any mapped type that includes a '?' modifier.
  47958. if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
  47959. return -1 /* True */;
  47960. }
  47961. if (isGenericMappedType(target)) {
  47962. if (isGenericMappedType(source)) {
  47963. if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
  47964. resetErrorInfo(saveErrorInfo);
  47965. return result;
  47966. }
  47967. }
  47968. return 0 /* False */;
  47969. }
  47970. var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
  47971. if (relation !== identityRelation) {
  47972. source = getApparentType(source);
  47973. }
  47974. else if (isGenericMappedType(source)) {
  47975. return 0 /* False */;
  47976. }
  47977. if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
  47978. !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
  47979. // We have type references to the same generic type, and the type references are not marker
  47980. // type references (which are intended by be compared structurally). Obtain the variance
  47981. // information for the type parameters and relate the type arguments accordingly.
  47982. var variances = getVariances(source.target);
  47983. // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
  47984. // effectively means we measure variance only from type parameter occurrences that aren't nested in
  47985. // recursive instantiations of the generic type.
  47986. if (variances === ts.emptyArray) {
  47987. return 1 /* Maybe */;
  47988. }
  47989. var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
  47990. if (varianceResult !== undefined) {
  47991. return varianceResult;
  47992. }
  47993. }
  47994. else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
  47995. if (relation !== identityRelation) {
  47996. return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
  47997. }
  47998. else {
  47999. // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
  48000. // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
  48001. return 0 /* False */;
  48002. }
  48003. }
  48004. // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
  48005. // and not `{} <- fresh({}) <- {[idx: string]: any}`
  48006. else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
  48007. return 0 /* False */;
  48008. }
  48009. // Even if relationship doesn't hold for unions, intersections, or generic type references,
  48010. // it may hold in a structural comparison.
  48011. // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
  48012. // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
  48013. // relates to X. Thus, we include intersection types on the source side here.
  48014. if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
  48015. // Report structural errors only if we haven't reported any errors yet
  48016. var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
  48017. result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
  48018. if (result) {
  48019. result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
  48020. if (result) {
  48021. result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
  48022. if (result) {
  48023. result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
  48024. if (result) {
  48025. result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
  48026. }
  48027. }
  48028. }
  48029. }
  48030. if (varianceCheckFailed && result) {
  48031. errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
  48032. }
  48033. else if (result) {
  48034. return result;
  48035. }
  48036. }
  48037. // If S is an object type and T is a discriminated union, S may be related to T if
  48038. // there exists a constituent of T for every combination of the discriminants of S
  48039. // with respect to T. We do not report errors here, as we will use the existing
  48040. // error result from checking each constituent of the union.
  48041. if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
  48042. var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
  48043. if (objectOnlyTarget.flags & 1048576 /* Union */) {
  48044. var result_4 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
  48045. if (result_4) {
  48046. return result_4;
  48047. }
  48048. }
  48049. }
  48050. }
  48051. return 0 /* False */;
  48052. function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
  48053. if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
  48054. return result;
  48055. }
  48056. if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
  48057. // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
  48058. // have to allow a structural fallback check
  48059. // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
  48060. // be assuming identity of the type parameter.
  48061. originalErrorInfo = undefined;
  48062. resetErrorInfo(saveErrorInfo);
  48063. return undefined;
  48064. }
  48065. var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
  48066. varianceCheckFailed = !allowStructuralFallback;
  48067. // The type arguments did not relate appropriately, but it may be because we have no variance
  48068. // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
  48069. // arguments). It might also be the case that the target type has a 'void' type argument for
  48070. // a covariant type parameter that is only used in return positions within the generic type
  48071. // (in which case any type argument is permitted on the source side). In those cases we proceed
  48072. // with a structural comparison. Otherwise, we know for certain the instantiations aren't
  48073. // related and we can return here.
  48074. if (variances !== ts.emptyArray && !allowStructuralFallback) {
  48075. // In some cases generic types that are covariant in regular type checking mode become
  48076. // invariant in --strictFunctionTypes mode because one or more type parameters are used in
  48077. // both co- and contravariant positions. In order to make it easier to diagnose *why* such
  48078. // types are invariant, if any of the type parameters are invariant we reset the reported
  48079. // errors and instead force a structural comparison (which will include elaborations that
  48080. // reveal the reason).
  48081. // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
  48082. // we can return `False` early here to skip calculating the structural error message we don't need.
  48083. if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
  48084. return 0 /* False */;
  48085. }
  48086. // We remember the original error information so we can restore it in case the structural
  48087. // comparison unexpectedly succeeds. This can happen when the structural comparison result
  48088. // is a Ternary.Maybe for example caused by the recursion depth limiter.
  48089. originalErrorInfo = errorInfo;
  48090. resetErrorInfo(saveErrorInfo);
  48091. }
  48092. }
  48093. }
  48094. function reportUnmeasurableMarkers(p) {
  48095. if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
  48096. outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
  48097. }
  48098. return p;
  48099. }
  48100. function reportUnreliableMarkers(p) {
  48101. if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
  48102. outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
  48103. }
  48104. return p;
  48105. }
  48106. // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
  48107. // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
  48108. // that S and T are contra-variant whereas X and Y are co-variant.
  48109. function mappedTypeRelatedTo(source, target, reportErrors) {
  48110. var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
  48111. getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
  48112. if (modifiersRelated) {
  48113. var result_5;
  48114. var targetConstraint = getConstraintTypeFromMappedType(target);
  48115. var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers);
  48116. if (result_5 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
  48117. var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
  48118. return result_5 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
  48119. }
  48120. }
  48121. return 0 /* False */;
  48122. }
  48123. function typeRelatedToDiscriminatedType(source, target) {
  48124. // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
  48125. // a. If the number of combinations is above a set limit, the comparison is too complex.
  48126. // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
  48127. // a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
  48128. // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
  48129. // 'target' are related to a property in 'source'.
  48130. //
  48131. // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
  48132. // for examples.
  48133. var sourceProperties = getPropertiesOfType(source);
  48134. var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
  48135. if (!sourcePropertiesFiltered)
  48136. return 0 /* False */;
  48137. // Though we could compute the number of combinations as we generate
  48138. // the matrix, this would incur additional memory overhead due to
  48139. // array allocations. To reduce this overhead, we first compute
  48140. // the number of combinations to ensure we will not surpass our
  48141. // fixed limit before incurring the cost of any allocations:
  48142. var numCombinations = 1;
  48143. for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
  48144. var sourceProperty = sourcePropertiesFiltered_1[_i];
  48145. numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
  48146. if (numCombinations > 25) {
  48147. // We've reached the complexity limit.
  48148. return 0 /* False */;
  48149. }
  48150. }
  48151. // Compute the set of types for each discriminant property.
  48152. var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
  48153. var excludedProperties = ts.createUnderscoreEscapedMap();
  48154. for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
  48155. var sourceProperty = sourcePropertiesFiltered[i];
  48156. var sourcePropertyType = getTypeOfSymbol(sourceProperty);
  48157. sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
  48158. ? sourcePropertyType.types
  48159. : [sourcePropertyType];
  48160. excludedProperties.set(sourceProperty.escapedName, true);
  48161. }
  48162. // Match each combination of the cartesian product of discriminant properties to one or more
  48163. // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
  48164. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
  48165. var matchingTypes = [];
  48166. var _loop_12 = function (combination) {
  48167. var hasMatch = false;
  48168. outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
  48169. var type = _a[_i];
  48170. var _loop_13 = function (i) {
  48171. var sourceProperty = sourcePropertiesFiltered[i];
  48172. var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
  48173. if (!targetProperty)
  48174. return "continue-outer";
  48175. if (sourceProperty === targetProperty)
  48176. return "continue";
  48177. // We compare the source property to the target in the context of a single discriminant type.
  48178. var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */);
  48179. // If the target property could not be found, or if the properties were not related,
  48180. // then this constituent is not a match.
  48181. if (!related) {
  48182. return "continue-outer";
  48183. }
  48184. };
  48185. for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
  48186. var state_6 = _loop_13(i);
  48187. switch (state_6) {
  48188. case "continue-outer": continue outer;
  48189. }
  48190. }
  48191. ts.pushIfUnique(matchingTypes, type, ts.equateValues);
  48192. hasMatch = true;
  48193. }
  48194. if (!hasMatch) {
  48195. return { value: 0 /* False */ };
  48196. }
  48197. };
  48198. for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
  48199. var combination = discriminantCombinations_1[_a];
  48200. var state_5 = _loop_12(combination);
  48201. if (typeof state_5 === "object")
  48202. return state_5.value;
  48203. }
  48204. // Compare the remaining non-discriminant properties of each match.
  48205. var result = -1 /* True */;
  48206. for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
  48207. var type = matchingTypes_1[_b];
  48208. result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
  48209. if (result) {
  48210. result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
  48211. if (result) {
  48212. result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
  48213. if (result) {
  48214. result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
  48215. if (result) {
  48216. result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
  48217. }
  48218. }
  48219. }
  48220. }
  48221. if (!result) {
  48222. return result;
  48223. }
  48224. }
  48225. return result;
  48226. }
  48227. function excludeProperties(properties, excludedProperties) {
  48228. if (!excludedProperties || properties.length === 0)
  48229. return properties;
  48230. var result;
  48231. for (var i = 0; i < properties.length; i++) {
  48232. if (!excludedProperties.has(properties[i].escapedName)) {
  48233. if (result) {
  48234. result.push(properties[i]);
  48235. }
  48236. }
  48237. else if (!result) {
  48238. result = properties.slice(0, i);
  48239. }
  48240. }
  48241. return result || properties;
  48242. }
  48243. function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
  48244. var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
  48245. var source = getTypeOfSourceProperty(sourceProp);
  48246. if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
  48247. // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
  48248. var links = getSymbolLinks(targetProp);
  48249. ts.Debug.assertDefined(links.deferralParent);
  48250. ts.Debug.assertDefined(links.deferralConstituents);
  48251. var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
  48252. var result_6 = unionParent ? 0 /* False */ : -1 /* True */;
  48253. var targetTypes = links.deferralConstituents;
  48254. for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
  48255. var targetType = targetTypes_3[_i];
  48256. var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
  48257. if (!unionParent) {
  48258. if (!related) {
  48259. // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
  48260. return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
  48261. }
  48262. result_6 &= related;
  48263. }
  48264. else {
  48265. if (related) {
  48266. return related;
  48267. }
  48268. }
  48269. }
  48270. if (unionParent && !result_6 && targetIsOptional) {
  48271. result_6 = isRelatedTo(source, undefinedType);
  48272. }
  48273. if (unionParent && !result_6 && reportErrors) {
  48274. // The easiest way to get the right errors here is to un-defer (which may be costly)
  48275. // If it turns out this is too costly too often, we can replicate the error handling logic within
  48276. // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
  48277. // type on which to hand discriminable properties, which we are expressly trying to avoid here)
  48278. return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
  48279. }
  48280. return result_6;
  48281. }
  48282. else {
  48283. return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
  48284. }
  48285. }
  48286. function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
  48287. var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
  48288. var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
  48289. if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
  48290. var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration;
  48291. if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) {
  48292. if (reportErrors) {
  48293. reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source));
  48294. }
  48295. return 0 /* False */;
  48296. }
  48297. if (hasDifferingDeclarations) {
  48298. if (reportErrors) {
  48299. if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
  48300. reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
  48301. }
  48302. else {
  48303. reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source));
  48304. }
  48305. }
  48306. return 0 /* False */;
  48307. }
  48308. }
  48309. else if (targetPropFlags & 16 /* Protected */) {
  48310. if (!isValidOverrideOf(sourceProp, targetProp)) {
  48311. if (reportErrors) {
  48312. reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
  48313. }
  48314. return 0 /* False */;
  48315. }
  48316. }
  48317. else if (sourcePropFlags & 16 /* Protected */) {
  48318. if (reportErrors) {
  48319. reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
  48320. }
  48321. return 0 /* False */;
  48322. }
  48323. // If the target comes from a partial union prop, allow `undefined` in the target type
  48324. var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
  48325. if (!related) {
  48326. if (reportErrors) {
  48327. reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
  48328. }
  48329. return 0 /* False */;
  48330. }
  48331. // When checking for comparability, be more lenient with optional properties.
  48332. if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
  48333. // TypeScript 1.0 spec (April 2014): 3.8.3
  48334. // S is a subtype of a type T, and T is a supertype of S if ...
  48335. // S' and T are object types and, for each member M in T..
  48336. // M is a property and S' contains a property N where
  48337. // if M is a required property, N is also a required property
  48338. // (M - property in T)
  48339. // (N - property in S)
  48340. if (reportErrors) {
  48341. reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
  48342. }
  48343. return 0 /* False */;
  48344. }
  48345. return related;
  48346. }
  48347. function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
  48348. var shouldSkipElaboration = false;
  48349. // give specific error in case where private names have the same description
  48350. if (unmatchedProperty.valueDeclaration
  48351. && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
  48352. && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
  48353. && source.symbol
  48354. && source.symbol.flags & 32 /* Class */) {
  48355. var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
  48356. var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
  48357. if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
  48358. var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
  48359. var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
  48360. reportError(ts.Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2, diagnosticName(privateIdentifierDescription), diagnosticName(sourceName.escapedText === "" ? anon : sourceName), diagnosticName(targetName.escapedText === "" ? anon : targetName));
  48361. return;
  48362. }
  48363. }
  48364. var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
  48365. if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
  48366. headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
  48367. shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
  48368. }
  48369. if (props.length === 1) {
  48370. var propName = symbolToString(unmatchedProperty);
  48371. reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
  48372. if (ts.length(unmatchedProperty.declarations)) {
  48373. associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
  48374. }
  48375. if (shouldSkipElaboration && errorInfo) {
  48376. overrideNextErrorInfo++;
  48377. }
  48378. }
  48379. else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
  48380. if (props.length > 5) { // arbitrary cutoff for too-long list form
  48381. reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source), typeToString(target), ts.map(props.slice(0, 4), function (p) { return symbolToString(p); }).join(", "), props.length - 4);
  48382. }
  48383. else {
  48384. reportError(ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source), typeToString(target), ts.map(props, function (p) { return symbolToString(p); }).join(", "));
  48385. }
  48386. if (shouldSkipElaboration && errorInfo) {
  48387. overrideNextErrorInfo++;
  48388. }
  48389. }
  48390. // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
  48391. }
  48392. function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
  48393. if (relation === identityRelation) {
  48394. return propertiesIdenticalTo(source, target, excludedProperties);
  48395. }
  48396. var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
  48397. var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
  48398. if (unmatchedProperty) {
  48399. if (reportErrors) {
  48400. reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
  48401. }
  48402. return 0 /* False */;
  48403. }
  48404. if (isObjectLiteralType(target)) {
  48405. for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
  48406. var sourceProp = _a[_i];
  48407. if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
  48408. var sourceType = getTypeOfSymbol(sourceProp);
  48409. if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
  48410. if (reportErrors) {
  48411. reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
  48412. }
  48413. return 0 /* False */;
  48414. }
  48415. }
  48416. }
  48417. }
  48418. var result = -1 /* True */;
  48419. if (isTupleType(target)) {
  48420. var targetRestType = getRestTypeOfTupleType(target);
  48421. if (targetRestType) {
  48422. if (!isTupleType(source)) {
  48423. return 0 /* False */;
  48424. }
  48425. var sourceRestType = getRestTypeOfTupleType(source);
  48426. if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
  48427. if (reportErrors) {
  48428. reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
  48429. }
  48430. return 0 /* False */;
  48431. }
  48432. var targetCount = getTypeReferenceArity(target) - 1;
  48433. var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
  48434. var sourceTypeArguments = getTypeArguments(source);
  48435. for (var i = targetCount; i < sourceCount; i++) {
  48436. var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
  48437. if (!related) {
  48438. if (reportErrors) {
  48439. reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
  48440. }
  48441. return 0 /* False */;
  48442. }
  48443. result &= related;
  48444. }
  48445. }
  48446. }
  48447. // We only call this for union target types when we're attempting to do excess property checking - in those cases, we want to get _all possible props_
  48448. // from the target union, across all members
  48449. var properties = getPropertiesOfType(target);
  48450. var numericNamesOnly = isTupleType(source) && isTupleType(target);
  48451. for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
  48452. var targetProp = _c[_b];
  48453. var name = targetProp.escapedName;
  48454. if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
  48455. var sourceProp = getPropertyOfType(source, name);
  48456. if (sourceProp && sourceProp !== targetProp) {
  48457. var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState);
  48458. if (!related) {
  48459. return 0 /* False */;
  48460. }
  48461. result &= related;
  48462. }
  48463. }
  48464. }
  48465. return result;
  48466. }
  48467. function propertiesIdenticalTo(source, target, excludedProperties) {
  48468. if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
  48469. return 0 /* False */;
  48470. }
  48471. var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
  48472. var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
  48473. if (sourceProperties.length !== targetProperties.length) {
  48474. return 0 /* False */;
  48475. }
  48476. var result = -1 /* True */;
  48477. for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
  48478. var sourceProp = sourceProperties_1[_i];
  48479. var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
  48480. if (!targetProp) {
  48481. return 0 /* False */;
  48482. }
  48483. var related = compareProperties(sourceProp, targetProp, isRelatedTo);
  48484. if (!related) {
  48485. return 0 /* False */;
  48486. }
  48487. result &= related;
  48488. }
  48489. return result;
  48490. }
  48491. function signaturesRelatedTo(source, target, kind, reportErrors) {
  48492. if (relation === identityRelation) {
  48493. return signaturesIdenticalTo(source, target, kind);
  48494. }
  48495. if (target === anyFunctionType || source === anyFunctionType) {
  48496. return -1 /* True */;
  48497. }
  48498. var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
  48499. var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
  48500. var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
  48501. 0 /* Call */ : kind);
  48502. var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
  48503. 0 /* Call */ : kind);
  48504. if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
  48505. if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
  48506. // An abstract constructor type is not assignable to a non-abstract constructor type
  48507. // as it would otherwise be possible to new an abstract class. Note that the assignability
  48508. // check we perform for an extends clause excludes construct signatures from the target,
  48509. // so this check never proceeds.
  48510. if (reportErrors) {
  48511. reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
  48512. }
  48513. return 0 /* False */;
  48514. }
  48515. if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
  48516. return 0 /* False */;
  48517. }
  48518. }
  48519. var result = -1 /* True */;
  48520. var saveErrorInfo = captureErrorCalculationState();
  48521. var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
  48522. if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
  48523. // We have instantiations of the same anonymous type (which typically will be the type of a
  48524. // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
  48525. // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
  48526. // as they are known to always be the same.
  48527. for (var i = 0; i < targetSignatures.length; i++) {
  48528. var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
  48529. if (!related) {
  48530. return 0 /* False */;
  48531. }
  48532. result &= related;
  48533. }
  48534. }
  48535. else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
  48536. // For simple functions (functions with a single signature) we only erase type parameters for
  48537. // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
  48538. // in the context of the target signature before checking the relationship. Ideally we'd do
  48539. // this regardless of the number of signatures, but the potential costs are prohibitive due
  48540. // to the quadratic nature of the logic below.
  48541. var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
  48542. result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
  48543. }
  48544. else {
  48545. outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
  48546. var t = targetSignatures_1[_i];
  48547. // Only elaborate errors from the first failure
  48548. var shouldElaborateErrors = reportErrors;
  48549. for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
  48550. var s = sourceSignatures_1[_a];
  48551. var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
  48552. if (related) {
  48553. result &= related;
  48554. resetErrorInfo(saveErrorInfo);
  48555. continue outer;
  48556. }
  48557. shouldElaborateErrors = false;
  48558. }
  48559. if (shouldElaborateErrors) {
  48560. reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
  48561. }
  48562. return 0 /* False */;
  48563. }
  48564. }
  48565. return result;
  48566. }
  48567. function reportIncompatibleCallSignatureReturn(siga, sigb) {
  48568. if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
  48569. return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
  48570. }
  48571. return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
  48572. }
  48573. function reportIncompatibleConstructSignatureReturn(siga, sigb) {
  48574. if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
  48575. return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
  48576. }
  48577. return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
  48578. }
  48579. /**
  48580. * See signatureAssignableTo, compareSignaturesIdentical
  48581. */
  48582. function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
  48583. return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers);
  48584. }
  48585. function signaturesIdenticalTo(source, target, kind) {
  48586. var sourceSignatures = getSignaturesOfType(source, kind);
  48587. var targetSignatures = getSignaturesOfType(target, kind);
  48588. if (sourceSignatures.length !== targetSignatures.length) {
  48589. return 0 /* False */;
  48590. }
  48591. var result = -1 /* True */;
  48592. for (var i = 0; i < sourceSignatures.length; i++) {
  48593. var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
  48594. if (!related) {
  48595. return 0 /* False */;
  48596. }
  48597. result &= related;
  48598. }
  48599. return result;
  48600. }
  48601. function eachPropertyRelatedTo(source, target, kind, reportErrors) {
  48602. var result = -1 /* True */;
  48603. var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
  48604. for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
  48605. var prop = props_2[_i];
  48606. // Skip over ignored JSX and symbol-named members
  48607. if (isIgnoredJsxProperty(source, prop)) {
  48608. continue;
  48609. }
  48610. var nameType = getSymbolLinks(prop).nameType;
  48611. if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
  48612. continue;
  48613. }
  48614. if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
  48615. var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
  48616. if (!related) {
  48617. if (reportErrors) {
  48618. reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
  48619. }
  48620. return 0 /* False */;
  48621. }
  48622. result &= related;
  48623. }
  48624. }
  48625. return result;
  48626. }
  48627. function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
  48628. var related = isRelatedTo(sourceType, targetType, reportErrors);
  48629. if (!related && reportErrors) {
  48630. reportError(ts.Diagnostics.Index_signatures_are_incompatible);
  48631. }
  48632. return related;
  48633. }
  48634. function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
  48635. if (relation === identityRelation) {
  48636. return indexTypesIdenticalTo(source, target, kind);
  48637. }
  48638. var targetType = getIndexTypeOfType(target, kind);
  48639. if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
  48640. // Index signature of type any permits assignment from everything but primitives
  48641. return -1 /* True */;
  48642. }
  48643. if (isGenericMappedType(source)) {
  48644. // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
  48645. // if T is related to U.
  48646. return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
  48647. }
  48648. var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
  48649. if (indexType) {
  48650. return indexTypeRelatedTo(indexType, targetType, reportErrors);
  48651. }
  48652. if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
  48653. // Intersection constituents are never considered to have an inferred index signature
  48654. var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
  48655. if (related && kind === 0 /* String */) {
  48656. var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
  48657. if (numberIndexType) {
  48658. related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
  48659. }
  48660. }
  48661. return related;
  48662. }
  48663. if (reportErrors) {
  48664. reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
  48665. }
  48666. return 0 /* False */;
  48667. }
  48668. function indexTypesIdenticalTo(source, target, indexKind) {
  48669. var targetInfo = getIndexInfoOfType(target, indexKind);
  48670. var sourceInfo = getIndexInfoOfType(source, indexKind);
  48671. if (!sourceInfo && !targetInfo) {
  48672. return -1 /* True */;
  48673. }
  48674. if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
  48675. return isRelatedTo(sourceInfo.type, targetInfo.type);
  48676. }
  48677. return 0 /* False */;
  48678. }
  48679. function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
  48680. if (!sourceSignature.declaration || !targetSignature.declaration) {
  48681. return true;
  48682. }
  48683. var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
  48684. var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
  48685. // A public, protected and private signature is assignable to a private signature.
  48686. if (targetAccessibility === 8 /* Private */) {
  48687. return true;
  48688. }
  48689. // A public and protected signature is assignable to a protected signature.
  48690. if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
  48691. return true;
  48692. }
  48693. // Only a public signature is assignable to public signature.
  48694. if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
  48695. return true;
  48696. }
  48697. if (reportErrors) {
  48698. reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
  48699. }
  48700. return false;
  48701. }
  48702. }
  48703. function getBestMatchingType(source, target, isRelatedTo) {
  48704. if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
  48705. return findMatchingDiscriminantType(source, target, isRelatedTo) ||
  48706. findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
  48707. findBestTypeForObjectLiteral(source, target) ||
  48708. findBestTypeForInvokable(source, target) ||
  48709. findMostOverlappyType(source, target);
  48710. }
  48711. function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) {
  48712. // undefined=unknown, true=discriminated, false=not discriminated
  48713. // The state of each type progresses from left to right. Discriminated types stop at 'true'.
  48714. var discriminable = target.types.map(function (_) { return undefined; });
  48715. for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
  48716. var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
  48717. var i = 0;
  48718. for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
  48719. var type = _c[_b];
  48720. var targetType = getTypeOfPropertyOfType(type, propertyName);
  48721. if (targetType && related(getDiscriminatingType(), targetType)) {
  48722. discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
  48723. }
  48724. else {
  48725. discriminable[i] = false;
  48726. }
  48727. i++;
  48728. }
  48729. }
  48730. var match = discriminable.indexOf(/*searchElement*/ true);
  48731. // make sure exactly 1 matches before returning it
  48732. return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
  48733. }
  48734. /**
  48735. * A type is 'weak' if it is an object type with at least one optional property
  48736. * and no required properties, call/construct signatures or index signatures
  48737. */
  48738. function isWeakType(type) {
  48739. if (type.flags & 524288 /* Object */) {
  48740. var resolved = resolveStructuredTypeMembers(type);
  48741. return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
  48742. !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
  48743. resolved.properties.length > 0 &&
  48744. ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
  48745. }
  48746. if (type.flags & 2097152 /* Intersection */) {
  48747. return ts.every(type.types, isWeakType);
  48748. }
  48749. return false;
  48750. }
  48751. function hasCommonProperties(source, target, isComparingJsxAttributes) {
  48752. for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
  48753. var prop = _a[_i];
  48754. if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
  48755. return true;
  48756. }
  48757. }
  48758. return false;
  48759. }
  48760. // Return a type reference where the source type parameter is replaced with the target marker
  48761. // type, and flag the result as a marker type reference.
  48762. function getMarkerTypeReference(type, source, target) {
  48763. var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
  48764. result.objectFlags |= 8192 /* MarkerType */;
  48765. return result;
  48766. }
  48767. function getAliasVariances(symbol) {
  48768. var links = getSymbolLinks(symbol);
  48769. return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
  48770. var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
  48771. type.aliasTypeArgumentsContainsMarker = true;
  48772. return type;
  48773. });
  48774. }
  48775. // Return an array containing the variance of each type parameter. The variance is effectively
  48776. // a digest of the type comparisons that occur for each type argument when instantiations of the
  48777. // generic type are structurally compared. We infer the variance information by comparing
  48778. // instantiations of the generic type for type arguments with known relations. The function
  48779. // returns the emptyArray singleton when invoked recursively for the given generic type.
  48780. function getVariancesWorker(typeParameters, cache, createMarkerType) {
  48781. if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
  48782. var variances = cache.variances;
  48783. if (!variances) {
  48784. // The emptyArray singleton is used to signal a recursive invocation.
  48785. cache.variances = ts.emptyArray;
  48786. variances = [];
  48787. var _loop_14 = function (tp) {
  48788. var unmeasurable = false;
  48789. var unreliable = false;
  48790. var oldHandler = outofbandVarianceMarkerHandler;
  48791. outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
  48792. // We first compare instantiations where the type parameter is replaced with
  48793. // marker types that have a known subtype relationship. From this we can infer
  48794. // invariance, covariance, contravariance or bivariance.
  48795. var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
  48796. var typeWithSub = createMarkerType(cache, tp, markerSubType);
  48797. var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
  48798. (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
  48799. // If the instantiations appear to be related bivariantly it may be because the
  48800. // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
  48801. // type). To determine this we compare instantiations where the type parameter is
  48802. // replaced with marker types that are known to be unrelated.
  48803. if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
  48804. variance = 4 /* Independent */;
  48805. }
  48806. outofbandVarianceMarkerHandler = oldHandler;
  48807. if (unmeasurable || unreliable) {
  48808. if (unmeasurable) {
  48809. variance |= 8 /* Unmeasurable */;
  48810. }
  48811. if (unreliable) {
  48812. variance |= 16 /* Unreliable */;
  48813. }
  48814. }
  48815. variances.push(variance);
  48816. };
  48817. for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
  48818. var tp = typeParameters_1[_i];
  48819. _loop_14(tp);
  48820. }
  48821. cache.variances = variances;
  48822. }
  48823. return variances;
  48824. }
  48825. function getVariances(type) {
  48826. // Arrays and tuples are known to be covariant, no need to spend time computing this.
  48827. if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
  48828. return arrayVariances;
  48829. }
  48830. return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
  48831. }
  48832. // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
  48833. // See comment at call in recursiveTypeRelatedTo for when this case matters.
  48834. function hasCovariantVoidArgument(typeArguments, variances) {
  48835. for (var i = 0; i < variances.length; i++) {
  48836. if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
  48837. return true;
  48838. }
  48839. }
  48840. return false;
  48841. }
  48842. function isUnconstrainedTypeParameter(type) {
  48843. return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
  48844. }
  48845. function isNonDeferredTypeReference(type) {
  48846. return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
  48847. }
  48848. function isTypeReferenceWithGenericArguments(type) {
  48849. return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
  48850. }
  48851. /**
  48852. * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
  48853. * where A.id=111 and number.id=12
  48854. */
  48855. function getTypeReferenceId(type, typeParameters, depth) {
  48856. if (depth === void 0) { depth = 0; }
  48857. var result = "" + type.target.id;
  48858. for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
  48859. var t = _a[_i];
  48860. if (isUnconstrainedTypeParameter(t)) {
  48861. var index = typeParameters.indexOf(t);
  48862. if (index < 0) {
  48863. index = typeParameters.length;
  48864. typeParameters.push(t);
  48865. }
  48866. result += "=" + index;
  48867. }
  48868. else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
  48869. result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
  48870. }
  48871. else {
  48872. result += "-" + t.id;
  48873. }
  48874. }
  48875. return result;
  48876. }
  48877. /**
  48878. * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
  48879. * For other cases, the types ids are used.
  48880. */
  48881. function getRelationKey(source, target, intersectionState, relation) {
  48882. if (relation === identityRelation && source.id > target.id) {
  48883. var temp = source;
  48884. source = target;
  48885. target = temp;
  48886. }
  48887. var postFix = intersectionState ? ":" + intersectionState : "";
  48888. if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
  48889. var typeParameters = [];
  48890. return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
  48891. }
  48892. return source.id + "," + target.id + postFix;
  48893. }
  48894. // Invoke the callback for each underlying property symbol of the given symbol and return the first
  48895. // value that isn't undefined.
  48896. function forEachProperty(prop, callback) {
  48897. if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
  48898. for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
  48899. var t = _a[_i];
  48900. var p = getPropertyOfType(t, prop.escapedName);
  48901. var result = p && forEachProperty(p, callback);
  48902. if (result) {
  48903. return result;
  48904. }
  48905. }
  48906. return undefined;
  48907. }
  48908. return callback(prop);
  48909. }
  48910. // Return the declaring class type of a property or undefined if property not declared in class
  48911. function getDeclaringClass(prop) {
  48912. return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
  48913. }
  48914. // Return true if some underlying source property is declared in a class that derives
  48915. // from the given base class.
  48916. function isPropertyInClassDerivedFrom(prop, baseClass) {
  48917. return forEachProperty(prop, function (sp) {
  48918. var sourceClass = getDeclaringClass(sp);
  48919. return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
  48920. });
  48921. }
  48922. // Return true if source property is a valid override of protected parts of target property.
  48923. function isValidOverrideOf(sourceProp, targetProp) {
  48924. return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
  48925. !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
  48926. }
  48927. // Return true if the given class derives from each of the declaring classes of the protected
  48928. // constituents of the given property.
  48929. function isClassDerivedFromDeclaringClasses(checkClass, prop) {
  48930. return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
  48931. !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
  48932. }
  48933. // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
  48934. // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
  48935. // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
  48936. // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
  48937. // levels, but unequal at some level beyond that.
  48938. // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
  48939. // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
  48940. // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
  48941. function isDeeplyNestedType(type, stack, depth) {
  48942. // We track all object types that have an associated symbol (representing the origin of the type)
  48943. if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
  48944. var symbol = type.symbol;
  48945. if (symbol) {
  48946. var count = 0;
  48947. for (var i = 0; i < depth; i++) {
  48948. var t = stack[i];
  48949. if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
  48950. count++;
  48951. if (count >= 5)
  48952. return true;
  48953. }
  48954. }
  48955. }
  48956. }
  48957. if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
  48958. var root = getRootObjectTypeFromIndexedAccessChain(type);
  48959. var count = 0;
  48960. for (var i = 0; i < depth; i++) {
  48961. var t = stack[i];
  48962. if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
  48963. count++;
  48964. if (count >= 5)
  48965. return true;
  48966. }
  48967. }
  48968. }
  48969. return false;
  48970. }
  48971. /**
  48972. * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
  48973. */
  48974. function getRootObjectTypeFromIndexedAccessChain(type) {
  48975. var t = type;
  48976. while (t.flags & 8388608 /* IndexedAccess */) {
  48977. t = t.objectType;
  48978. }
  48979. return t;
  48980. }
  48981. function isPropertyIdenticalTo(sourceProp, targetProp) {
  48982. return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
  48983. }
  48984. function compareProperties(sourceProp, targetProp, compareTypes) {
  48985. // Two members are considered identical when
  48986. // - they are public properties with identical names, optionality, and types,
  48987. // - they are private or protected properties originating in the same declaration and having identical types
  48988. if (sourceProp === targetProp) {
  48989. return -1 /* True */;
  48990. }
  48991. var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
  48992. var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
  48993. if (sourcePropAccessibility !== targetPropAccessibility) {
  48994. return 0 /* False */;
  48995. }
  48996. if (sourcePropAccessibility) {
  48997. if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
  48998. return 0 /* False */;
  48999. }
  49000. }
  49001. else {
  49002. if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
  49003. return 0 /* False */;
  49004. }
  49005. }
  49006. if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
  49007. return 0 /* False */;
  49008. }
  49009. return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
  49010. }
  49011. function isMatchingSignature(source, target, partialMatch) {
  49012. var sourceParameterCount = getParameterCount(source);
  49013. var targetParameterCount = getParameterCount(target);
  49014. var sourceMinArgumentCount = getMinArgumentCount(source);
  49015. var targetMinArgumentCount = getMinArgumentCount(target);
  49016. var sourceHasRestParameter = hasEffectiveRestParameter(source);
  49017. var targetHasRestParameter = hasEffectiveRestParameter(target);
  49018. // A source signature matches a target signature if the two signatures have the same number of required,
  49019. // optional, and rest parameters.
  49020. if (sourceParameterCount === targetParameterCount &&
  49021. sourceMinArgumentCount === targetMinArgumentCount &&
  49022. sourceHasRestParameter === targetHasRestParameter) {
  49023. return true;
  49024. }
  49025. // A source signature partially matches a target signature if the target signature has no fewer required
  49026. // parameters
  49027. if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
  49028. return true;
  49029. }
  49030. return false;
  49031. }
  49032. /**
  49033. * See signatureRelatedTo, compareSignaturesIdentical
  49034. */
  49035. function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
  49036. // TODO (drosen): De-duplicate code between related functions.
  49037. if (source === target) {
  49038. return -1 /* True */;
  49039. }
  49040. if (!(isMatchingSignature(source, target, partialMatch))) {
  49041. return 0 /* False */;
  49042. }
  49043. // Check that the two signatures have the same number of type parameters.
  49044. if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
  49045. return 0 /* False */;
  49046. }
  49047. // Check that type parameter constraints and defaults match. If they do, instantiate the source
  49048. // signature with the type parameters of the target signature and continue the comparison.
  49049. if (target.typeParameters) {
  49050. var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
  49051. for (var i = 0; i < target.typeParameters.length; i++) {
  49052. var s = source.typeParameters[i];
  49053. var t = target.typeParameters[i];
  49054. if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
  49055. compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
  49056. return 0 /* False */;
  49057. }
  49058. }
  49059. source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
  49060. }
  49061. var result = -1 /* True */;
  49062. if (!ignoreThisTypes) {
  49063. var sourceThisType = getThisTypeOfSignature(source);
  49064. if (sourceThisType) {
  49065. var targetThisType = getThisTypeOfSignature(target);
  49066. if (targetThisType) {
  49067. var related = compareTypes(sourceThisType, targetThisType);
  49068. if (!related) {
  49069. return 0 /* False */;
  49070. }
  49071. result &= related;
  49072. }
  49073. }
  49074. }
  49075. var targetLen = getParameterCount(target);
  49076. for (var i = 0; i < targetLen; i++) {
  49077. var s = getTypeAtPosition(source, i);
  49078. var t = getTypeAtPosition(target, i);
  49079. var related = compareTypes(t, s);
  49080. if (!related) {
  49081. return 0 /* False */;
  49082. }
  49083. result &= related;
  49084. }
  49085. if (!ignoreReturnTypes) {
  49086. var sourceTypePredicate = getTypePredicateOfSignature(source);
  49087. var targetTypePredicate = getTypePredicateOfSignature(target);
  49088. result &= sourceTypePredicate || targetTypePredicate ?
  49089. compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
  49090. compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
  49091. }
  49092. return result;
  49093. }
  49094. function compareTypePredicatesIdentical(source, target, compareTypes) {
  49095. return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
  49096. source.type === target.type ? -1 /* True */ :
  49097. source.type && target.type ? compareTypes(source.type, target.type) :
  49098. 0 /* False */;
  49099. }
  49100. function literalTypesWithSameBaseType(types) {
  49101. var commonBaseType;
  49102. for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
  49103. var t = types_11[_i];
  49104. var baseType = getBaseTypeOfLiteralType(t);
  49105. if (!commonBaseType) {
  49106. commonBaseType = baseType;
  49107. }
  49108. if (baseType === t || baseType !== commonBaseType) {
  49109. return false;
  49110. }
  49111. }
  49112. return true;
  49113. }
  49114. // When the candidate types are all literal types with the same base type, return a union
  49115. // of those literal types. Otherwise, return the leftmost type for which no type to the
  49116. // right is a supertype.
  49117. function getSupertypeOrUnion(types) {
  49118. return literalTypesWithSameBaseType(types) ?
  49119. getUnionType(types) :
  49120. ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
  49121. }
  49122. function getCommonSupertype(types) {
  49123. if (!strictNullChecks) {
  49124. return getSupertypeOrUnion(types);
  49125. }
  49126. var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
  49127. return primaryTypes.length ?
  49128. getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
  49129. getUnionType(types, 2 /* Subtype */);
  49130. }
  49131. // Return the leftmost type for which no type to the right is a subtype.
  49132. function getCommonSubtype(types) {
  49133. return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
  49134. }
  49135. function isArrayType(type) {
  49136. return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
  49137. }
  49138. function isReadonlyArrayType(type) {
  49139. return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
  49140. }
  49141. function isMutableArrayOrTuple(type) {
  49142. return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
  49143. }
  49144. function getElementTypeOfArrayType(type) {
  49145. return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
  49146. }
  49147. function isArrayLikeType(type) {
  49148. // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
  49149. // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
  49150. return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
  49151. }
  49152. function isEmptyArrayLiteralType(type) {
  49153. var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
  49154. return elementType === undefinedWideningType || elementType === implicitNeverType;
  49155. }
  49156. function isTupleLikeType(type) {
  49157. return isTupleType(type) || !!getPropertyOfType(type, "0");
  49158. }
  49159. function isArrayOrTupleLikeType(type) {
  49160. return isArrayLikeType(type) || isTupleLikeType(type);
  49161. }
  49162. function getTupleElementType(type, index) {
  49163. var propType = getTypeOfPropertyOfType(type, "" + index);
  49164. if (propType) {
  49165. return propType;
  49166. }
  49167. if (everyType(type, isTupleType)) {
  49168. return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
  49169. }
  49170. return undefined;
  49171. }
  49172. function isNeitherUnitTypeNorNever(type) {
  49173. return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
  49174. }
  49175. function isUnitType(type) {
  49176. return !!(type.flags & 109440 /* Unit */);
  49177. }
  49178. function isLiteralType(type) {
  49179. return type.flags & 16 /* Boolean */ ? true :
  49180. type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
  49181. isUnitType(type);
  49182. }
  49183. function getBaseTypeOfLiteralType(type) {
  49184. return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
  49185. type.flags & 128 /* StringLiteral */ ? stringType :
  49186. type.flags & 256 /* NumberLiteral */ ? numberType :
  49187. type.flags & 2048 /* BigIntLiteral */ ? bigintType :
  49188. type.flags & 512 /* BooleanLiteral */ ? booleanType :
  49189. type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
  49190. type;
  49191. }
  49192. function getWidenedLiteralType(type) {
  49193. return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
  49194. type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
  49195. type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
  49196. type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
  49197. type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
  49198. type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
  49199. type;
  49200. }
  49201. function getWidenedUniqueESSymbolType(type) {
  49202. return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
  49203. type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
  49204. type;
  49205. }
  49206. function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
  49207. if (!isLiteralOfContextualType(type, contextualType)) {
  49208. type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
  49209. }
  49210. return type;
  49211. }
  49212. function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
  49213. if (type && isUnitType(type)) {
  49214. var contextualType = !contextualSignatureReturnType ? undefined :
  49215. isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
  49216. contextualSignatureReturnType;
  49217. type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
  49218. }
  49219. return type;
  49220. }
  49221. function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
  49222. if (type && isUnitType(type)) {
  49223. var contextualType = !contextualSignatureReturnType ? undefined :
  49224. getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
  49225. type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
  49226. }
  49227. return type;
  49228. }
  49229. /**
  49230. * Check if a Type was written as a tuple type literal.
  49231. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
  49232. */
  49233. function isTupleType(type) {
  49234. return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
  49235. }
  49236. function getRestTypeOfTupleType(type) {
  49237. return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
  49238. }
  49239. function getRestArrayTypeOfTupleType(type) {
  49240. var restType = getRestTypeOfTupleType(type);
  49241. return restType && createArrayType(restType);
  49242. }
  49243. function getLengthOfTupleType(type) {
  49244. return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
  49245. }
  49246. function isZeroBigInt(_a) {
  49247. var value = _a.value;
  49248. return value.base10Value === "0";
  49249. }
  49250. function getFalsyFlagsOfTypes(types) {
  49251. var result = 0;
  49252. for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
  49253. var t = types_12[_i];
  49254. result |= getFalsyFlags(t);
  49255. }
  49256. return result;
  49257. }
  49258. // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
  49259. // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
  49260. // no flags for all other types (including non-falsy literal types).
  49261. function getFalsyFlags(type) {
  49262. return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
  49263. type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
  49264. type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
  49265. type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
  49266. type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
  49267. type.flags & 117724 /* PossiblyFalsy */;
  49268. }
  49269. function removeDefinitelyFalsyTypes(type) {
  49270. return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
  49271. filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
  49272. type;
  49273. }
  49274. function extractDefinitelyFalsyTypes(type) {
  49275. return mapType(type, getDefinitelyFalsyPartOfType);
  49276. }
  49277. function getDefinitelyFalsyPartOfType(type) {
  49278. return type.flags & 4 /* String */ ? emptyStringType :
  49279. type.flags & 8 /* Number */ ? zeroType :
  49280. type.flags & 64 /* BigInt */ ? zeroBigIntType :
  49281. type === regularFalseType ||
  49282. type === falseType ||
  49283. type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
  49284. type.flags & 128 /* StringLiteral */ && type.value === "" ||
  49285. type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
  49286. type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
  49287. neverType;
  49288. }
  49289. /**
  49290. * Add undefined or null or both to a type if they are missing.
  49291. * @param type - type to add undefined and/or null to if not present
  49292. * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
  49293. */
  49294. function getNullableType(type, flags) {
  49295. var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
  49296. return missing === 0 ? type :
  49297. missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
  49298. missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
  49299. getUnionType([type, undefinedType, nullType]);
  49300. }
  49301. function getOptionalType(type) {
  49302. ts.Debug.assert(strictNullChecks);
  49303. return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
  49304. }
  49305. function getGlobalNonNullableTypeInstantiation(type) {
  49306. if (!deferredGlobalNonNullableTypeAlias) {
  49307. deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
  49308. }
  49309. // Use NonNullable global type alias if available to improve quick info/declaration emit
  49310. if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
  49311. return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
  49312. }
  49313. return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
  49314. }
  49315. function getNonNullableType(type) {
  49316. return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
  49317. }
  49318. function addOptionalTypeMarker(type) {
  49319. return strictNullChecks ? getUnionType([type, optionalType]) : type;
  49320. }
  49321. function isNotOptionalTypeMarker(type) {
  49322. return type !== optionalType;
  49323. }
  49324. function removeOptionalTypeMarker(type) {
  49325. return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
  49326. }
  49327. function propagateOptionalTypeMarker(type, node, wasOptional) {
  49328. return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
  49329. }
  49330. function getOptionalExpressionType(exprType, expression) {
  49331. return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
  49332. ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
  49333. exprType;
  49334. }
  49335. /**
  49336. * Is source potentially coercible to target type under `==`.
  49337. * Assumes that `source` is a constituent of a union, hence
  49338. * the boolean literal flag on the LHS, but not on the RHS.
  49339. *
  49340. * This does not fully replicate the semantics of `==`. The
  49341. * intention is to catch cases that are clearly not right.
  49342. *
  49343. * Comparing (string | number) to number should not remove the
  49344. * string element.
  49345. *
  49346. * Comparing (string | number) to 1 will remove the string
  49347. * element, though this is not sound. This is a pragmatic
  49348. * choice.
  49349. *
  49350. * @see narrowTypeByEquality
  49351. *
  49352. * @param source
  49353. * @param target
  49354. */
  49355. function isCoercibleUnderDoubleEquals(source, target) {
  49356. return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
  49357. && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
  49358. }
  49359. /**
  49360. * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
  49361. * with no call or construct signatures.
  49362. */
  49363. function isObjectTypeWithInferableIndex(type) {
  49364. return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
  49365. !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
  49366. !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
  49367. }
  49368. function createSymbolWithType(source, type) {
  49369. var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
  49370. symbol.declarations = source.declarations;
  49371. symbol.parent = source.parent;
  49372. symbol.type = type;
  49373. symbol.target = source;
  49374. if (source.valueDeclaration) {
  49375. symbol.valueDeclaration = source.valueDeclaration;
  49376. }
  49377. var nameType = getSymbolLinks(source).nameType;
  49378. if (nameType) {
  49379. symbol.nameType = nameType;
  49380. }
  49381. return symbol;
  49382. }
  49383. function transformTypeOfMembers(type, f) {
  49384. var members = ts.createSymbolTable();
  49385. for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
  49386. var property = _a[_i];
  49387. var original = getTypeOfSymbol(property);
  49388. var updated = f(original);
  49389. members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
  49390. }
  49391. return members;
  49392. }
  49393. /**
  49394. * If the the provided object literal is subject to the excess properties check,
  49395. * create a new that is exempt. Recursively mark object literal members as exempt.
  49396. * Leave signatures alone since they are not subject to the check.
  49397. */
  49398. function getRegularTypeOfObjectLiteral(type) {
  49399. if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
  49400. return type;
  49401. }
  49402. var regularType = type.regularType;
  49403. if (regularType) {
  49404. return regularType;
  49405. }
  49406. var resolved = type;
  49407. var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
  49408. var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
  49409. regularNew.flags = resolved.flags;
  49410. regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
  49411. type.regularType = regularNew;
  49412. return regularNew;
  49413. }
  49414. function createWideningContext(parent, propertyName, siblings) {
  49415. return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
  49416. }
  49417. function getSiblingsOfContext(context) {
  49418. if (!context.siblings) {
  49419. var siblings_1 = [];
  49420. for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
  49421. var type = _a[_i];
  49422. if (isObjectLiteralType(type)) {
  49423. var prop = getPropertyOfObjectType(type, context.propertyName);
  49424. if (prop) {
  49425. forEachType(getTypeOfSymbol(prop), function (t) {
  49426. siblings_1.push(t);
  49427. });
  49428. }
  49429. }
  49430. }
  49431. context.siblings = siblings_1;
  49432. }
  49433. return context.siblings;
  49434. }
  49435. function getPropertiesOfContext(context) {
  49436. if (!context.resolvedProperties) {
  49437. var names = ts.createMap();
  49438. for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
  49439. var t = _a[_i];
  49440. if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
  49441. for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
  49442. var prop = _c[_b];
  49443. names.set(prop.escapedName, prop);
  49444. }
  49445. }
  49446. }
  49447. context.resolvedProperties = ts.arrayFrom(names.values());
  49448. }
  49449. return context.resolvedProperties;
  49450. }
  49451. function getWidenedProperty(prop, context) {
  49452. if (!(prop.flags & 4 /* Property */)) {
  49453. // Since get accessors already widen their return value there is no need to
  49454. // widen accessor based properties here.
  49455. return prop;
  49456. }
  49457. var original = getTypeOfSymbol(prop);
  49458. var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
  49459. var widened = getWidenedTypeWithContext(original, propContext);
  49460. return widened === original ? prop : createSymbolWithType(prop, widened);
  49461. }
  49462. function getUndefinedProperty(prop) {
  49463. var cached = undefinedProperties.get(prop.escapedName);
  49464. if (cached) {
  49465. return cached;
  49466. }
  49467. var result = createSymbolWithType(prop, undefinedType);
  49468. result.flags |= 16777216 /* Optional */;
  49469. undefinedProperties.set(prop.escapedName, result);
  49470. return result;
  49471. }
  49472. function getWidenedTypeOfObjectLiteral(type, context) {
  49473. var members = ts.createSymbolTable();
  49474. for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
  49475. var prop = _a[_i];
  49476. members.set(prop.escapedName, getWidenedProperty(prop, context));
  49477. }
  49478. if (context) {
  49479. for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
  49480. var prop = _c[_b];
  49481. if (!members.has(prop.escapedName)) {
  49482. members.set(prop.escapedName, getUndefinedProperty(prop));
  49483. }
  49484. }
  49485. }
  49486. var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
  49487. var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
  49488. var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
  49489. result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
  49490. return result;
  49491. }
  49492. function getWidenedType(type) {
  49493. return getWidenedTypeWithContext(type, /*context*/ undefined);
  49494. }
  49495. function getWidenedTypeWithContext(type, context) {
  49496. if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
  49497. if (context === undefined && type.widened) {
  49498. return type.widened;
  49499. }
  49500. var result = void 0;
  49501. if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
  49502. result = anyType;
  49503. }
  49504. else if (isObjectLiteralType(type)) {
  49505. result = getWidenedTypeOfObjectLiteral(type, context);
  49506. }
  49507. else if (type.flags & 1048576 /* Union */) {
  49508. var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
  49509. var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
  49510. // Widening an empty object literal transitions from a highly restrictive type to
  49511. // a highly inclusive one. For that reason we perform subtype reduction here if the
  49512. // union includes empty object types (e.g. reducing {} | string to just {}).
  49513. result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
  49514. }
  49515. else if (type.flags & 2097152 /* Intersection */) {
  49516. result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
  49517. }
  49518. else if (isArrayType(type) || isTupleType(type)) {
  49519. result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
  49520. }
  49521. if (result && context === undefined) {
  49522. type.widened = result;
  49523. }
  49524. return result || type;
  49525. }
  49526. return type;
  49527. }
  49528. /**
  49529. * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
  49530. * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
  49531. * getWidenedType. But in some cases getWidenedType is called without reporting errors
  49532. * (type argument inference is an example).
  49533. *
  49534. * The return value indicates whether an error was in fact reported. The particular circumstances
  49535. * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
  49536. * an object literal property (arbitrarily deeply), this function reports an error. If no error is
  49537. * reported, reportImplicitAnyError is a suitable fallback to report a general error.
  49538. */
  49539. function reportWideningErrorsInType(type) {
  49540. var errorReported = false;
  49541. if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
  49542. if (type.flags & 1048576 /* Union */) {
  49543. if (ts.some(type.types, isEmptyObjectType)) {
  49544. errorReported = true;
  49545. }
  49546. else {
  49547. for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
  49548. var t = _a[_i];
  49549. if (reportWideningErrorsInType(t)) {
  49550. errorReported = true;
  49551. }
  49552. }
  49553. }
  49554. }
  49555. if (isArrayType(type) || isTupleType(type)) {
  49556. for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
  49557. var t = _c[_b];
  49558. if (reportWideningErrorsInType(t)) {
  49559. errorReported = true;
  49560. }
  49561. }
  49562. }
  49563. if (isObjectLiteralType(type)) {
  49564. for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
  49565. var p = _e[_d];
  49566. var t = getTypeOfSymbol(p);
  49567. if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
  49568. if (!reportWideningErrorsInType(t)) {
  49569. error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
  49570. }
  49571. errorReported = true;
  49572. }
  49573. }
  49574. }
  49575. }
  49576. return errorReported;
  49577. }
  49578. function reportImplicitAny(declaration, type, wideningKind) {
  49579. var typeAsString = typeToString(getWidenedType(type));
  49580. if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
  49581. // Only report implicit any errors/suggestions in TS and ts-check JS files
  49582. return;
  49583. }
  49584. var diagnostic;
  49585. switch (declaration.kind) {
  49586. case 209 /* BinaryExpression */:
  49587. case 159 /* PropertyDeclaration */:
  49588. case 158 /* PropertySignature */:
  49589. diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
  49590. break;
  49591. case 156 /* Parameter */:
  49592. var param = declaration;
  49593. if (ts.isIdentifier(param.name) &&
  49594. (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
  49595. param.parent.parameters.indexOf(param) > -1 &&
  49596. (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
  49597. param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
  49598. var newName = "arg" + param.parent.parameters.indexOf(param);
  49599. errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
  49600. return;
  49601. }
  49602. diagnostic = declaration.dotDotDotToken ?
  49603. noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
  49604. noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
  49605. break;
  49606. case 191 /* BindingElement */:
  49607. diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
  49608. if (!noImplicitAny) {
  49609. // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
  49610. return;
  49611. }
  49612. break;
  49613. case 300 /* JSDocFunctionType */:
  49614. error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
  49615. return;
  49616. case 244 /* FunctionDeclaration */:
  49617. case 161 /* MethodDeclaration */:
  49618. case 160 /* MethodSignature */:
  49619. case 163 /* GetAccessor */:
  49620. case 164 /* SetAccessor */:
  49621. case 201 /* FunctionExpression */:
  49622. case 202 /* ArrowFunction */:
  49623. if (noImplicitAny && !declaration.name) {
  49624. if (wideningKind === 1 /* GeneratorYield */) {
  49625. error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
  49626. }
  49627. else {
  49628. error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
  49629. }
  49630. return;
  49631. }
  49632. diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
  49633. wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
  49634. ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
  49635. break;
  49636. case 186 /* MappedType */:
  49637. if (noImplicitAny) {
  49638. error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
  49639. }
  49640. return;
  49641. default:
  49642. diagnostic = noImplicitAny ? ts.Diagnostics.Variable_0_implicitly_has_an_1_type : ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
  49643. }
  49644. errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
  49645. }
  49646. function reportErrorsFromWidening(declaration, type, wideningKind) {
  49647. if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
  49648. // Report implicit any error within type if possible, otherwise report error on declaration
  49649. if (!reportWideningErrorsInType(type)) {
  49650. reportImplicitAny(declaration, type, wideningKind);
  49651. }
  49652. }
  49653. }
  49654. function applyToParameterTypes(source, target, callback) {
  49655. var sourceCount = getParameterCount(source);
  49656. var targetCount = getParameterCount(target);
  49657. var sourceRestType = getEffectiveRestType(source);
  49658. var targetRestType = getEffectiveRestType(target);
  49659. var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
  49660. var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
  49661. var sourceThisType = getThisTypeOfSignature(source);
  49662. if (sourceThisType) {
  49663. var targetThisType = getThisTypeOfSignature(target);
  49664. if (targetThisType) {
  49665. callback(sourceThisType, targetThisType);
  49666. }
  49667. }
  49668. for (var i = 0; i < paramCount; i++) {
  49669. callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
  49670. }
  49671. if (targetRestType) {
  49672. callback(getRestTypeAtPosition(source, paramCount), targetRestType);
  49673. }
  49674. }
  49675. function applyToReturnTypes(source, target, callback) {
  49676. var sourceTypePredicate = getTypePredicateOfSignature(source);
  49677. var targetTypePredicate = getTypePredicateOfSignature(target);
  49678. if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
  49679. callback(sourceTypePredicate.type, targetTypePredicate.type);
  49680. }
  49681. else {
  49682. callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
  49683. }
  49684. }
  49685. function createInferenceContext(typeParameters, signature, flags, compareTypes) {
  49686. return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
  49687. }
  49688. function cloneInferenceContext(context, extraFlags) {
  49689. if (extraFlags === void 0) { extraFlags = 0; }
  49690. return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
  49691. }
  49692. function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
  49693. var context = {
  49694. inferences: inferences,
  49695. signature: signature,
  49696. flags: flags,
  49697. compareTypes: compareTypes,
  49698. mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
  49699. nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
  49700. };
  49701. return context;
  49702. }
  49703. function mapToInferredType(context, t, fix) {
  49704. var inferences = context.inferences;
  49705. for (var i = 0; i < inferences.length; i++) {
  49706. var inference = inferences[i];
  49707. if (t === inference.typeParameter) {
  49708. if (fix && !inference.isFixed) {
  49709. clearCachedInferences(inferences);
  49710. inference.isFixed = true;
  49711. }
  49712. return getInferredType(context, i);
  49713. }
  49714. }
  49715. return t;
  49716. }
  49717. function clearCachedInferences(inferences) {
  49718. for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
  49719. var inference = inferences_1[_i];
  49720. if (!inference.isFixed) {
  49721. inference.inferredType = undefined;
  49722. }
  49723. }
  49724. }
  49725. function createInferenceInfo(typeParameter) {
  49726. return {
  49727. typeParameter: typeParameter,
  49728. candidates: undefined,
  49729. contraCandidates: undefined,
  49730. inferredType: undefined,
  49731. priority: undefined,
  49732. topLevel: true,
  49733. isFixed: false
  49734. };
  49735. }
  49736. function cloneInferenceInfo(inference) {
  49737. return {
  49738. typeParameter: inference.typeParameter,
  49739. candidates: inference.candidates && inference.candidates.slice(),
  49740. contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
  49741. inferredType: inference.inferredType,
  49742. priority: inference.priority,
  49743. topLevel: inference.topLevel,
  49744. isFixed: inference.isFixed
  49745. };
  49746. }
  49747. function cloneInferredPartOfContext(context) {
  49748. var inferences = ts.filter(context.inferences, hasInferenceCandidates);
  49749. return inferences.length ?
  49750. createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
  49751. undefined;
  49752. }
  49753. function getMapperFromContext(context) {
  49754. return context && context.mapper;
  49755. }
  49756. // Return true if the given type could possibly reference a type parameter for which
  49757. // we perform type inference (i.e. a type parameter of a generic function). We cache
  49758. // results for union and intersection types for performance reasons.
  49759. function couldContainTypeVariables(type) {
  49760. var objectFlags = ts.getObjectFlags(type);
  49761. return !!(type.flags & 63176704 /* Instantiable */ ||
  49762. objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
  49763. objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
  49764. objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
  49765. type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type));
  49766. }
  49767. function couldUnionOrIntersectionContainTypeVariables(type) {
  49768. if (type.couldContainTypeVariables === undefined) {
  49769. type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables);
  49770. }
  49771. return type.couldContainTypeVariables;
  49772. }
  49773. function isTypeParameterAtTopLevel(type, typeParameter) {
  49774. return !!(type === typeParameter ||
  49775. type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
  49776. type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
  49777. isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
  49778. }
  49779. /** Create an object with properties named in the string literal type. Every property has type `any` */
  49780. function createEmptyObjectTypeFromStringLiteral(type) {
  49781. var members = ts.createSymbolTable();
  49782. forEachType(type, function (t) {
  49783. if (!(t.flags & 128 /* StringLiteral */)) {
  49784. return;
  49785. }
  49786. var name = ts.escapeLeadingUnderscores(t.value);
  49787. var literalProp = createSymbol(4 /* Property */, name);
  49788. literalProp.type = anyType;
  49789. if (t.symbol) {
  49790. literalProp.declarations = t.symbol.declarations;
  49791. literalProp.valueDeclaration = t.symbol.valueDeclaration;
  49792. }
  49793. members.set(name, literalProp);
  49794. });
  49795. var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
  49796. return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
  49797. }
  49798. /**
  49799. * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
  49800. * an object type with the same set of properties as the source type, where the type of each
  49801. * property is computed by inferring from the source property type to X for the type
  49802. * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
  49803. */
  49804. function inferTypeForHomomorphicMappedType(source, target, constraint) {
  49805. var key = source.id + "," + target.id + "," + constraint.id;
  49806. if (reverseMappedCache.has(key)) {
  49807. return reverseMappedCache.get(key);
  49808. }
  49809. reverseMappedCache.set(key, undefined);
  49810. var type = createReverseMappedType(source, target, constraint);
  49811. reverseMappedCache.set(key, type);
  49812. return type;
  49813. }
  49814. // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
  49815. // an object literal type with at least one property of an inferable type. For example, an object
  49816. // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
  49817. // arrow function, but is considered partially inferable because property 'a' has an inferable type.
  49818. function isPartiallyInferableType(type) {
  49819. return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
  49820. isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
  49821. }
  49822. function createReverseMappedType(source, target, constraint) {
  49823. // We consider a source type reverse mappable if it has a string index signature or if
  49824. // it has one or more properties and is of a partially inferable type.
  49825. if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
  49826. return undefined;
  49827. }
  49828. // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
  49829. // applied to the element type(s).
  49830. if (isArrayType(source)) {
  49831. return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
  49832. }
  49833. if (isTupleType(source)) {
  49834. var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
  49835. var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
  49836. getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
  49837. return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
  49838. }
  49839. // For all other object types we infer a new object type where the reverse mapping has been
  49840. // applied to the type of each property.
  49841. var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
  49842. reversed.source = source;
  49843. reversed.mappedType = target;
  49844. reversed.constraintType = constraint;
  49845. return reversed;
  49846. }
  49847. function getTypeOfReverseMappedSymbol(symbol) {
  49848. return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
  49849. }
  49850. function inferReverseMappedType(sourceType, target, constraint) {
  49851. var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
  49852. var templateType = getTemplateTypeFromMappedType(target);
  49853. var inference = createInferenceInfo(typeParameter);
  49854. inferTypes([inference], sourceType, templateType);
  49855. return getTypeFromInference(inference) || unknownType;
  49856. }
  49857. function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
  49858. var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
  49859. return __generator(this, function (_a) {
  49860. switch (_a.label) {
  49861. case 0:
  49862. properties = getPropertiesOfType(target);
  49863. _i = 0, properties_2 = properties;
  49864. _a.label = 1;
  49865. case 1:
  49866. if (!(_i < properties_2.length)) return [3 /*break*/, 6];
  49867. targetProp = properties_2[_i];
  49868. // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
  49869. if (isStaticPrivateIdentifierProperty(targetProp)) {
  49870. return [3 /*break*/, 5];
  49871. }
  49872. if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
  49873. sourceProp = getPropertyOfType(source, targetProp.escapedName);
  49874. if (!!sourceProp) return [3 /*break*/, 3];
  49875. return [4 /*yield*/, targetProp];
  49876. case 2:
  49877. _a.sent();
  49878. return [3 /*break*/, 5];
  49879. case 3:
  49880. if (!matchDiscriminantProperties) return [3 /*break*/, 5];
  49881. targetType = getTypeOfSymbol(targetProp);
  49882. if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
  49883. sourceType = getTypeOfSymbol(sourceProp);
  49884. if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
  49885. return [4 /*yield*/, targetProp];
  49886. case 4:
  49887. _a.sent();
  49888. _a.label = 5;
  49889. case 5:
  49890. _i++;
  49891. return [3 /*break*/, 1];
  49892. case 6: return [2 /*return*/];
  49893. }
  49894. });
  49895. }
  49896. function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
  49897. var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
  49898. if (!result.done)
  49899. return result.value;
  49900. }
  49901. function tupleTypesDefinitelyUnrelated(source, target) {
  49902. return target.target.minLength > source.target.minLength ||
  49903. !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
  49904. }
  49905. function typesDefinitelyUnrelated(source, target) {
  49906. // Two tuple types with incompatible arities are definitely unrelated.
  49907. // Two object types that each have a property that is unmatched in the other are definitely unrelated.
  49908. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
  49909. !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
  49910. !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
  49911. }
  49912. function getTypeFromInference(inference) {
  49913. return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
  49914. inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
  49915. undefined;
  49916. }
  49917. function hasSkipDirectInferenceFlag(node) {
  49918. return !!getNodeLinks(node).skipDirectInference;
  49919. }
  49920. function isFromInferenceBlockedSource(type) {
  49921. return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
  49922. }
  49923. function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
  49924. if (priority === void 0) { priority = 0; }
  49925. if (contravariant === void 0) { contravariant = false; }
  49926. var symbolStack;
  49927. var visited;
  49928. var bivariant = false;
  49929. var propagationType;
  49930. var inferencePriority = 512 /* MaxValue */;
  49931. var allowComplexConstraintInference = true;
  49932. inferFromTypes(originalSource, originalTarget);
  49933. function inferFromTypes(source, target) {
  49934. if (!couldContainTypeVariables(target)) {
  49935. return;
  49936. }
  49937. if (source === wildcardType) {
  49938. // We are inferring from an 'any' type. We want to infer this type for every type parameter
  49939. // referenced in the target type, so we record it as the propagation type and infer from the
  49940. // target to itself. Then, as we find candidates we substitute the propagation type.
  49941. var savePropagationType = propagationType;
  49942. propagationType = source;
  49943. inferFromTypes(target, target);
  49944. propagationType = savePropagationType;
  49945. return;
  49946. }
  49947. if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
  49948. // Source and target are types originating in the same generic type alias declaration.
  49949. // Simply infer from source type arguments to target type arguments.
  49950. inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
  49951. return;
  49952. }
  49953. if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
  49954. // When source and target are the same union or intersection type, just relate each constituent
  49955. // type to itself.
  49956. for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
  49957. var t = _a[_i];
  49958. inferFromTypes(t, t);
  49959. }
  49960. return;
  49961. }
  49962. if (target.flags & 1048576 /* Union */) {
  49963. // First, infer between identically matching source and target constituents and remove the
  49964. // matching types.
  49965. var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
  49966. // Next, infer between closely matching source and target constituents and remove
  49967. // the matching types. Types closely match when they are instantiations of the same
  49968. // object type or instantiations of the same type alias.
  49969. var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
  49970. if (targets.length === 0) {
  49971. return;
  49972. }
  49973. target = getUnionType(targets);
  49974. if (sources.length === 0) {
  49975. // All source constituents have been matched and there is nothing further to infer from.
  49976. // However, simply making no inferences is undesirable because it could ultimately mean
  49977. // inferring a type parameter constraint. Instead, make a lower priority inference from
  49978. // the full source to whatever remains in the target. For example, when inferring from
  49979. // string to 'string | T', make a lower priority inference of string for T.
  49980. inferWithPriority(source, target, 1 /* NakedTypeVariable */);
  49981. return;
  49982. }
  49983. source = getUnionType(sources);
  49984. }
  49985. else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
  49986. // We reduce intersection types only when they contain naked type parameters. For example, when
  49987. // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
  49988. // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
  49989. // string[] on the source side and infer string for T.
  49990. // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
  49991. // in such scenarios.
  49992. if (!(source.flags & 1048576 /* Union */)) {
  49993. // Infer between identically matching source and target constituents and remove the matching types.
  49994. var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
  49995. if (sources.length === 0 || targets.length === 0) {
  49996. return;
  49997. }
  49998. source = getIntersectionType(sources);
  49999. target = getIntersectionType(targets);
  50000. }
  50001. }
  50002. else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
  50003. target = getActualTypeVariable(target);
  50004. }
  50005. if (target.flags & 8650752 /* TypeVariable */) {
  50006. // If target is a type parameter, make an inference, unless the source type contains
  50007. // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
  50008. // Because the anyFunctionType is internal, it should not be exposed to the user by adding
  50009. // it as an inference candidate. Hopefully, a better candidate will come along that does
  50010. // not contain anyFunctionType when we come back to this argument for its second round
  50011. // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
  50012. // when constructing types from type parameters that had no inference candidates).
  50013. if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
  50014. (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
  50015. return;
  50016. }
  50017. var inference = getInferenceInfoForType(target);
  50018. if (inference) {
  50019. if (!inference.isFixed) {
  50020. if (inference.priority === undefined || priority < inference.priority) {
  50021. inference.candidates = undefined;
  50022. inference.contraCandidates = undefined;
  50023. inference.topLevel = true;
  50024. inference.priority = priority;
  50025. }
  50026. if (priority === inference.priority) {
  50027. var candidate = propagationType || source;
  50028. // We make contravariant inferences only if we are in a pure contravariant position,
  50029. // i.e. only if we have not descended into a bivariant position.
  50030. if (contravariant && !bivariant) {
  50031. if (!ts.contains(inference.contraCandidates, candidate)) {
  50032. inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
  50033. clearCachedInferences(inferences);
  50034. }
  50035. }
  50036. else if (!ts.contains(inference.candidates, candidate)) {
  50037. inference.candidates = ts.append(inference.candidates, candidate);
  50038. clearCachedInferences(inferences);
  50039. }
  50040. }
  50041. if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
  50042. inference.topLevel = false;
  50043. clearCachedInferences(inferences);
  50044. }
  50045. }
  50046. inferencePriority = Math.min(inferencePriority, priority);
  50047. return;
  50048. }
  50049. else {
  50050. // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
  50051. var simplified = getSimplifiedType(target, /*writing*/ false);
  50052. if (simplified !== target) {
  50053. invokeOnce(source, simplified, inferFromTypes);
  50054. }
  50055. else if (target.flags & 8388608 /* IndexedAccess */) {
  50056. var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
  50057. // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
  50058. // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
  50059. if (indexType.flags & 63176704 /* Instantiable */) {
  50060. var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
  50061. if (simplified_1 && simplified_1 !== target) {
  50062. invokeOnce(source, simplified_1, inferFromTypes);
  50063. }
  50064. }
  50065. }
  50066. }
  50067. }
  50068. if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
  50069. !(source.node && target.node)) {
  50070. // If source and target are references to the same generic type, infer from type arguments
  50071. inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
  50072. }
  50073. else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
  50074. contravariant = !contravariant;
  50075. inferFromTypes(source.type, target.type);
  50076. contravariant = !contravariant;
  50077. }
  50078. else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
  50079. var empty = createEmptyObjectTypeFromStringLiteral(source);
  50080. contravariant = !contravariant;
  50081. inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
  50082. contravariant = !contravariant;
  50083. }
  50084. else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
  50085. inferFromTypes(source.objectType, target.objectType);
  50086. inferFromTypes(source.indexType, target.indexType);
  50087. }
  50088. else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
  50089. inferFromTypes(source.checkType, target.checkType);
  50090. inferFromTypes(source.extendsType, target.extendsType);
  50091. inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
  50092. inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
  50093. }
  50094. else if (target.flags & 16777216 /* Conditional */) {
  50095. var savePriority = priority;
  50096. priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
  50097. var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
  50098. inferToMultipleTypes(source, targetTypes, target.flags);
  50099. priority = savePriority;
  50100. }
  50101. else if (target.flags & 3145728 /* UnionOrIntersection */) {
  50102. inferToMultipleTypes(source, target.types, target.flags);
  50103. }
  50104. else if (source.flags & 1048576 /* Union */) {
  50105. // Source is a union or intersection type, infer from each constituent type
  50106. var sourceTypes = source.types;
  50107. for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
  50108. var sourceType = sourceTypes_3[_e];
  50109. inferFromTypes(sourceType, target);
  50110. }
  50111. }
  50112. else {
  50113. if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
  50114. var apparentSource = getApparentType(source);
  50115. // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
  50116. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
  50117. // with the simplified source.
  50118. if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
  50119. // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
  50120. // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
  50121. // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
  50122. // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
  50123. // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
  50124. // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
  50125. // remove this `allowComplexConstraintInference` flag.
  50126. allowComplexConstraintInference = false;
  50127. return inferFromTypes(apparentSource, target);
  50128. }
  50129. source = apparentSource;
  50130. }
  50131. if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
  50132. invokeOnce(source, target, inferFromObjectTypes);
  50133. }
  50134. }
  50135. if (source.flags & 25165824 /* Simplifiable */) {
  50136. var simplified = getSimplifiedType(source, contravariant);
  50137. if (simplified !== source) {
  50138. inferFromTypes(simplified, target);
  50139. }
  50140. }
  50141. }
  50142. function inferWithPriority(source, target, newPriority) {
  50143. var savePriority = priority;
  50144. priority |= newPriority;
  50145. inferFromTypes(source, target);
  50146. priority = savePriority;
  50147. }
  50148. function invokeOnce(source, target, action) {
  50149. var key = source.id + "," + target.id;
  50150. var status = visited && visited.get(key);
  50151. if (status !== undefined) {
  50152. inferencePriority = Math.min(inferencePriority, status);
  50153. return;
  50154. }
  50155. (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
  50156. var saveInferencePriority = inferencePriority;
  50157. inferencePriority = 512 /* MaxValue */;
  50158. action(source, target);
  50159. visited.set(key, inferencePriority);
  50160. inferencePriority = Math.min(inferencePriority, saveInferencePriority);
  50161. }
  50162. function inferFromMatchingTypes(sources, targets, matches) {
  50163. var matchedSources;
  50164. var matchedTargets;
  50165. for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
  50166. var t = targets_1[_i];
  50167. for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
  50168. var s = sources_1[_a];
  50169. if (matches(s, t)) {
  50170. inferFromTypes(s, t);
  50171. matchedSources = ts.appendIfUnique(matchedSources, s);
  50172. matchedTargets = ts.appendIfUnique(matchedTargets, t);
  50173. }
  50174. }
  50175. }
  50176. return [
  50177. matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
  50178. matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
  50179. ];
  50180. }
  50181. function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
  50182. var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
  50183. for (var i = 0; i < count; i++) {
  50184. if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
  50185. inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
  50186. }
  50187. else {
  50188. inferFromTypes(sourceTypes[i], targetTypes[i]);
  50189. }
  50190. }
  50191. }
  50192. function inferFromContravariantTypes(source, target) {
  50193. if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
  50194. contravariant = !contravariant;
  50195. inferFromTypes(source, target);
  50196. contravariant = !contravariant;
  50197. }
  50198. else {
  50199. inferFromTypes(source, target);
  50200. }
  50201. }
  50202. function getInferenceInfoForType(type) {
  50203. if (type.flags & 8650752 /* TypeVariable */) {
  50204. for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
  50205. var inference = inferences_2[_i];
  50206. if (type === inference.typeParameter) {
  50207. return inference;
  50208. }
  50209. }
  50210. }
  50211. return undefined;
  50212. }
  50213. function getSingleTypeVariableFromIntersectionTypes(types) {
  50214. var typeVariable;
  50215. for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
  50216. var type = types_13[_i];
  50217. var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
  50218. if (!t || typeVariable && t !== typeVariable) {
  50219. return undefined;
  50220. }
  50221. typeVariable = t;
  50222. }
  50223. return typeVariable;
  50224. }
  50225. function inferToMultipleTypes(source, targets, targetFlags) {
  50226. var typeVariableCount = 0;
  50227. if (targetFlags & 1048576 /* Union */) {
  50228. var nakedTypeVariable = void 0;
  50229. var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
  50230. var matched_1 = new Array(sources.length);
  50231. var inferenceCircularity = false;
  50232. // First infer to types that are not naked type variables. For each source type we
  50233. // track whether inferences were made from that particular type to some target with
  50234. // equal priority (i.e. of equal quality) to what we would infer for a naked type
  50235. // parameter.
  50236. for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
  50237. var t = targets_2[_i];
  50238. if (getInferenceInfoForType(t)) {
  50239. nakedTypeVariable = t;
  50240. typeVariableCount++;
  50241. }
  50242. else {
  50243. for (var i = 0; i < sources.length; i++) {
  50244. var saveInferencePriority = inferencePriority;
  50245. inferencePriority = 512 /* MaxValue */;
  50246. inferFromTypes(sources[i], t);
  50247. if (inferencePriority === priority)
  50248. matched_1[i] = true;
  50249. inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
  50250. inferencePriority = Math.min(inferencePriority, saveInferencePriority);
  50251. }
  50252. }
  50253. }
  50254. if (typeVariableCount === 0) {
  50255. // If every target is an intersection of types containing a single naked type variable,
  50256. // make a lower priority inference to that type variable. This handles inferring from
  50257. // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
  50258. var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
  50259. if (intersectionTypeVariable) {
  50260. inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
  50261. }
  50262. return;
  50263. }
  50264. // If the target has a single naked type variable and no inference circularities were
  50265. // encountered above (meaning we explored the types fully), create a union of the source
  50266. // types from which no inferences have been made so far and infer from that union to the
  50267. // naked type variable.
  50268. if (typeVariableCount === 1 && !inferenceCircularity) {
  50269. var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
  50270. if (unmatched.length) {
  50271. inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
  50272. return;
  50273. }
  50274. }
  50275. }
  50276. else {
  50277. // We infer from types that are not naked type variables first so that inferences we
  50278. // make from nested naked type variables and given slightly higher priority by virtue
  50279. // of being first in the candidates array.
  50280. for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
  50281. var t = targets_3[_a];
  50282. if (getInferenceInfoForType(t)) {
  50283. typeVariableCount++;
  50284. }
  50285. else {
  50286. inferFromTypes(source, t);
  50287. }
  50288. }
  50289. }
  50290. // Inferences directly to naked type variables are given lower priority as they are
  50291. // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
  50292. // we want to infer string for T, not Promise<string> | string. For intersection types
  50293. // we only infer to single naked type variables.
  50294. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
  50295. for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
  50296. var t = targets_4[_b];
  50297. if (getInferenceInfoForType(t)) {
  50298. inferWithPriority(source, t, 1 /* NakedTypeVariable */);
  50299. }
  50300. }
  50301. }
  50302. }
  50303. function inferToMappedType(source, target, constraintType) {
  50304. if (constraintType.flags & 1048576 /* Union */) {
  50305. var result = false;
  50306. for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
  50307. var type = _a[_i];
  50308. result = inferToMappedType(source, target, type) || result;
  50309. }
  50310. return result;
  50311. }
  50312. if (constraintType.flags & 4194304 /* Index */) {
  50313. // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
  50314. // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
  50315. // type and then make a secondary inference from that type to T. We make a secondary inference
  50316. // such that direct inferences to T get priority over inferences to Partial<T>, for example.
  50317. var inference = getInferenceInfoForType(constraintType.type);
  50318. if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
  50319. var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
  50320. if (inferredType) {
  50321. // We assign a lower priority to inferences made from types containing non-inferrable
  50322. // types because we may only have a partial result (i.e. we may have failed to make
  50323. // reverse inferences for some properties).
  50324. inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
  50325. 4 /* PartialHomomorphicMappedType */ :
  50326. 2 /* HomomorphicMappedType */);
  50327. }
  50328. }
  50329. return true;
  50330. }
  50331. if (constraintType.flags & 262144 /* TypeParameter */) {
  50332. // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
  50333. // parameter. First infer from 'keyof S' to K.
  50334. inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
  50335. // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
  50336. // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
  50337. // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
  50338. // Pick<T, K>.
  50339. var extendedConstraint = getConstraintOfType(constraintType);
  50340. if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
  50341. return true;
  50342. }
  50343. // If no inferences can be made to K's constraint, infer from a union of the property types
  50344. // in the source to the template type X.
  50345. var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
  50346. var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
  50347. var numberIndexInfo = getNonEnumNumberIndexInfo(source);
  50348. var numberIndexType = numberIndexInfo && numberIndexInfo.type;
  50349. inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
  50350. return true;
  50351. }
  50352. return false;
  50353. }
  50354. function inferFromObjectTypes(source, target) {
  50355. // If we are already processing another target type with the same associated symbol (such as
  50356. // an instantiation of the same generic type), we do not explore this target as it would yield
  50357. // no further inferences. We exclude the static side of classes from this check since it shares
  50358. // its symbol with the instance side which would lead to false positives.
  50359. var isNonConstructorObject = target.flags & 524288 /* Object */ &&
  50360. !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
  50361. var symbol = isNonConstructorObject ? target.symbol : undefined;
  50362. if (symbol) {
  50363. if (ts.contains(symbolStack, symbol)) {
  50364. inferencePriority = -1 /* Circularity */;
  50365. return;
  50366. }
  50367. (symbolStack || (symbolStack = [])).push(symbol);
  50368. inferFromObjectTypesWorker(source, target);
  50369. symbolStack.pop();
  50370. }
  50371. else {
  50372. inferFromObjectTypesWorker(source, target);
  50373. }
  50374. }
  50375. function inferFromObjectTypesWorker(source, target) {
  50376. if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
  50377. // If source and target are references to the same generic type, infer from type arguments
  50378. inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
  50379. return;
  50380. }
  50381. if (isGenericMappedType(source) && isGenericMappedType(target)) {
  50382. // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
  50383. // from S to T and from X to Y.
  50384. inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
  50385. inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
  50386. }
  50387. if (ts.getObjectFlags(target) & 32 /* Mapped */) {
  50388. var constraintType = getConstraintTypeFromMappedType(target);
  50389. if (inferToMappedType(source, target, constraintType)) {
  50390. return;
  50391. }
  50392. }
  50393. // Infer from the members of source and target only if the two types are possibly related
  50394. if (!typesDefinitelyUnrelated(source, target)) {
  50395. inferFromProperties(source, target);
  50396. inferFromSignatures(source, target, 0 /* Call */);
  50397. inferFromSignatures(source, target, 1 /* Construct */);
  50398. inferFromIndexTypes(source, target);
  50399. }
  50400. }
  50401. function inferFromProperties(source, target) {
  50402. if (isArrayType(source) || isTupleType(source)) {
  50403. if (isTupleType(target)) {
  50404. var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
  50405. var targetLength = getLengthOfTupleType(target);
  50406. var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
  50407. var targetRestType = getRestTypeOfTupleType(target);
  50408. var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
  50409. for (var i = 0; i < fixedLength; i++) {
  50410. inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
  50411. }
  50412. if (targetRestType) {
  50413. var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
  50414. if (sourceRestType) {
  50415. types.push(sourceRestType);
  50416. }
  50417. if (types.length) {
  50418. inferFromTypes(getUnionType(types), targetRestType);
  50419. }
  50420. }
  50421. return;
  50422. }
  50423. if (isArrayType(target)) {
  50424. inferFromIndexTypes(source, target);
  50425. return;
  50426. }
  50427. }
  50428. var properties = getPropertiesOfObjectType(target);
  50429. for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
  50430. var targetProp = properties_3[_i];
  50431. var sourceProp = getPropertyOfType(source, targetProp.escapedName);
  50432. if (sourceProp) {
  50433. inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
  50434. }
  50435. }
  50436. }
  50437. function inferFromSignatures(source, target, kind) {
  50438. var sourceSignatures = getSignaturesOfType(source, kind);
  50439. var targetSignatures = getSignaturesOfType(target, kind);
  50440. var sourceLen = sourceSignatures.length;
  50441. var targetLen = targetSignatures.length;
  50442. var len = sourceLen < targetLen ? sourceLen : targetLen;
  50443. var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
  50444. for (var i = 0; i < len; i++) {
  50445. inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
  50446. }
  50447. }
  50448. function inferFromSignature(source, target, skipParameters) {
  50449. if (!skipParameters) {
  50450. var saveBivariant = bivariant;
  50451. var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
  50452. // Once we descend into a bivariant signature we remain bivariant for all nested inferences
  50453. bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
  50454. applyToParameterTypes(source, target, inferFromContravariantTypes);
  50455. bivariant = saveBivariant;
  50456. }
  50457. applyToReturnTypes(source, target, inferFromTypes);
  50458. }
  50459. function inferFromIndexTypes(source, target) {
  50460. var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
  50461. if (targetStringIndexType) {
  50462. var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
  50463. getImplicitIndexTypeOfType(source, 0 /* String */);
  50464. if (sourceIndexType) {
  50465. inferFromTypes(sourceIndexType, targetStringIndexType);
  50466. }
  50467. }
  50468. var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
  50469. if (targetNumberIndexType) {
  50470. var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
  50471. getIndexTypeOfType(source, 0 /* String */) ||
  50472. getImplicitIndexTypeOfType(source, 1 /* Number */);
  50473. if (sourceIndexType) {
  50474. inferFromTypes(sourceIndexType, targetNumberIndexType);
  50475. }
  50476. }
  50477. }
  50478. }
  50479. function isTypeOrBaseIdenticalTo(s, t) {
  50480. return isTypeIdenticalTo(s, t) || !!(s.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) && isTypeIdenticalTo(getBaseTypeOfLiteralType(s), t);
  50481. }
  50482. function isTypeCloselyMatchedBy(s, t) {
  50483. return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
  50484. s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
  50485. }
  50486. function hasPrimitiveConstraint(type) {
  50487. var constraint = getConstraintOfTypeParameter(type);
  50488. return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
  50489. }
  50490. function isObjectLiteralType(type) {
  50491. return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
  50492. }
  50493. function isObjectOrArrayLiteralType(type) {
  50494. return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
  50495. }
  50496. function unionObjectAndArrayLiteralCandidates(candidates) {
  50497. if (candidates.length > 1) {
  50498. var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
  50499. if (objectLiterals.length) {
  50500. var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
  50501. return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
  50502. }
  50503. }
  50504. return candidates;
  50505. }
  50506. function getContravariantInference(inference) {
  50507. return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
  50508. }
  50509. function getCovariantInference(inference, signature) {
  50510. // Extract all object and array literal types and replace them with a single widened and normalized type.
  50511. var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
  50512. // We widen inferred literal types if
  50513. // all inferences were made to top-level occurrences of the type parameter, and
  50514. // the type parameter has no constraint or its constraint includes no primitive or literal types, and
  50515. // the type parameter was fixed during inference or does not occur at top-level in the return type.
  50516. var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
  50517. var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
  50518. (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
  50519. var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
  50520. widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
  50521. candidates;
  50522. // If all inferences were made from a position that implies a combined result, infer a union type.
  50523. // Otherwise, infer a common supertype.
  50524. var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
  50525. getUnionType(baseCandidates, 2 /* Subtype */) :
  50526. getCommonSupertype(baseCandidates);
  50527. return getWidenedType(unwidenedType);
  50528. }
  50529. function getInferredType(context, index) {
  50530. var inference = context.inferences[index];
  50531. if (!inference.inferredType) {
  50532. var inferredType = void 0;
  50533. var signature = context.signature;
  50534. if (signature) {
  50535. var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
  50536. if (inference.contraCandidates) {
  50537. var inferredContravariantType = getContravariantInference(inference);
  50538. // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
  50539. // unless the co-variant inference is a subtype and not 'never'.
  50540. inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
  50541. isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
  50542. inferredCovariantType : inferredContravariantType;
  50543. }
  50544. else if (inferredCovariantType) {
  50545. inferredType = inferredCovariantType;
  50546. }
  50547. else if (context.flags & 1 /* NoDefault */) {
  50548. // We use silentNeverType as the wildcard that signals no inferences.
  50549. inferredType = silentNeverType;
  50550. }
  50551. else {
  50552. // Infer either the default or the empty object type when no inferences were
  50553. // made. It is important to remember that in this case, inference still
  50554. // succeeds, meaning there is no error for not having inference candidates. An
  50555. // inference error only occurs when there are *conflicting* candidates, i.e.
  50556. // candidates with no common supertype.
  50557. var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
  50558. if (defaultType) {
  50559. // Instantiate the default type. Any forward reference to a type
  50560. // parameter should be instantiated to the empty object type.
  50561. inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
  50562. }
  50563. }
  50564. }
  50565. else {
  50566. inferredType = getTypeFromInference(inference);
  50567. }
  50568. inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
  50569. var constraint = getConstraintOfTypeParameter(inference.typeParameter);
  50570. if (constraint) {
  50571. var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
  50572. if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
  50573. inference.inferredType = inferredType = instantiatedConstraint;
  50574. }
  50575. }
  50576. }
  50577. return inference.inferredType;
  50578. }
  50579. function getDefaultTypeArgumentType(isInJavaScriptFile) {
  50580. return isInJavaScriptFile ? anyType : unknownType;
  50581. }
  50582. function getInferredTypes(context) {
  50583. var result = [];
  50584. for (var i = 0; i < context.inferences.length; i++) {
  50585. result.push(getInferredType(context, i));
  50586. }
  50587. return result;
  50588. }
  50589. // EXPRESSION TYPE CHECKING
  50590. function getCannotFindNameDiagnosticForName(node) {
  50591. switch (node.escapedText) {
  50592. case "document":
  50593. case "console":
  50594. return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
  50595. case "$":
  50596. return compilerOptions.types
  50597. ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
  50598. : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
  50599. case "describe":
  50600. case "suite":
  50601. case "it":
  50602. case "test":
  50603. return compilerOptions.types
  50604. ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
  50605. : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
  50606. case "process":
  50607. case "require":
  50608. case "Buffer":
  50609. case "module":
  50610. return compilerOptions.types
  50611. ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
  50612. : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
  50613. case "Map":
  50614. case "Set":
  50615. case "Promise":
  50616. case "Symbol":
  50617. case "WeakMap":
  50618. case "WeakSet":
  50619. case "Iterator":
  50620. case "AsyncIterator":
  50621. return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later;
  50622. default:
  50623. if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
  50624. return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
  50625. }
  50626. else {
  50627. return ts.Diagnostics.Cannot_find_name_0;
  50628. }
  50629. }
  50630. }
  50631. function getResolvedSymbol(node) {
  50632. var links = getNodeLinks(node);
  50633. if (!links.resolvedSymbol) {
  50634. links.resolvedSymbol = !ts.nodeIsMissing(node) &&
  50635. resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node),
  50636. /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
  50637. }
  50638. return links.resolvedSymbol;
  50639. }
  50640. function isInTypeQuery(node) {
  50641. // TypeScript 1.0 spec (April 2014): 3.6.3
  50642. // A type query consists of the keyword typeof followed by an expression.
  50643. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
  50644. return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
  50645. }
  50646. // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
  50647. // separated by dots). The key consists of the id of the symbol referenced by the
  50648. // leftmost identifier followed by zero or more property names separated by dots.
  50649. // The result is undefined if the reference isn't a dotted name. We prefix nodes
  50650. // occurring in an apparent type position with '@' because the control flow type
  50651. // of such nodes may be based on the apparent type instead of the declared type.
  50652. function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
  50653. switch (node.kind) {
  50654. case 75 /* Identifier */:
  50655. var symbol = getResolvedSymbol(node);
  50656. return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
  50657. case 104 /* ThisKeyword */:
  50658. return "0";
  50659. case 218 /* NonNullExpression */:
  50660. case 200 /* ParenthesizedExpression */:
  50661. return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
  50662. case 194 /* PropertyAccessExpression */:
  50663. case 195 /* ElementAccessExpression */:
  50664. var propName = getAccessedPropertyName(node);
  50665. if (propName !== undefined) {
  50666. var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
  50667. return key && key + "." + propName;
  50668. }
  50669. }
  50670. return undefined;
  50671. }
  50672. function isMatchingReference(source, target) {
  50673. switch (target.kind) {
  50674. case 200 /* ParenthesizedExpression */:
  50675. case 218 /* NonNullExpression */:
  50676. return isMatchingReference(source, target.expression);
  50677. }
  50678. switch (source.kind) {
  50679. case 75 /* Identifier */:
  50680. return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
  50681. (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
  50682. getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
  50683. case 104 /* ThisKeyword */:
  50684. return target.kind === 104 /* ThisKeyword */;
  50685. case 102 /* SuperKeyword */:
  50686. return target.kind === 102 /* SuperKeyword */;
  50687. case 218 /* NonNullExpression */:
  50688. case 200 /* ParenthesizedExpression */:
  50689. return isMatchingReference(source.expression, target);
  50690. case 194 /* PropertyAccessExpression */:
  50691. case 195 /* ElementAccessExpression */:
  50692. return ts.isAccessExpression(target) &&
  50693. getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
  50694. isMatchingReference(source.expression, target.expression);
  50695. }
  50696. return false;
  50697. }
  50698. function getAccessedPropertyName(access) {
  50699. return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
  50700. ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
  50701. undefined;
  50702. }
  50703. function containsMatchingReference(source, target) {
  50704. while (ts.isAccessExpression(source)) {
  50705. source = source.expression;
  50706. if (isMatchingReference(source, target)) {
  50707. return true;
  50708. }
  50709. }
  50710. return false;
  50711. }
  50712. function optionalChainContainsReference(source, target) {
  50713. while (ts.isOptionalChain(source)) {
  50714. source = source.expression;
  50715. if (isMatchingReference(source, target)) {
  50716. return true;
  50717. }
  50718. }
  50719. return false;
  50720. }
  50721. function isDiscriminantProperty(type, name) {
  50722. if (type && type.flags & 1048576 /* Union */) {
  50723. var prop = getUnionOrIntersectionProperty(type, name);
  50724. if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
  50725. if (prop.isDiscriminantProperty === undefined) {
  50726. prop.isDiscriminantProperty =
  50727. (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
  50728. !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
  50729. }
  50730. return !!prop.isDiscriminantProperty;
  50731. }
  50732. }
  50733. return false;
  50734. }
  50735. function isSyntheticThisPropertyAccess(expr) {
  50736. return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
  50737. }
  50738. function findDiscriminantProperties(sourceProperties, target) {
  50739. var result;
  50740. for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
  50741. var sourceProperty = sourceProperties_2[_i];
  50742. if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
  50743. if (result) {
  50744. result.push(sourceProperty);
  50745. continue;
  50746. }
  50747. result = [sourceProperty];
  50748. }
  50749. }
  50750. return result;
  50751. }
  50752. function isOrContainsMatchingReference(source, target) {
  50753. return isMatchingReference(source, target) || containsMatchingReference(source, target);
  50754. }
  50755. function hasMatchingArgument(callExpression, reference) {
  50756. if (callExpression.arguments) {
  50757. for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
  50758. var argument = _a[_i];
  50759. if (isOrContainsMatchingReference(reference, argument)) {
  50760. return true;
  50761. }
  50762. }
  50763. }
  50764. if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
  50765. isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
  50766. return true;
  50767. }
  50768. return false;
  50769. }
  50770. function getFlowNodeId(flow) {
  50771. if (!flow.id || flow.id < 0) {
  50772. flow.id = nextFlowId;
  50773. nextFlowId++;
  50774. }
  50775. return flow.id;
  50776. }
  50777. function typeMaybeAssignableTo(source, target) {
  50778. if (!(source.flags & 1048576 /* Union */)) {
  50779. return isTypeAssignableTo(source, target);
  50780. }
  50781. for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
  50782. var t = _a[_i];
  50783. if (isTypeAssignableTo(t, target)) {
  50784. return true;
  50785. }
  50786. }
  50787. return false;
  50788. }
  50789. // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
  50790. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
  50791. // we remove type string.
  50792. function getAssignmentReducedType(declaredType, assignedType) {
  50793. if (declaredType !== assignedType) {
  50794. if (assignedType.flags & 131072 /* Never */) {
  50795. return assignedType;
  50796. }
  50797. var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
  50798. if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
  50799. reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
  50800. }
  50801. // Our crude heuristic produces an invalid result in some cases: see GH#26130.
  50802. // For now, when that happens, we give up and don't narrow at all. (This also
  50803. // means we'll never narrow for erroneous assignments where the assigned type
  50804. // is not assignable to the declared type.)
  50805. if (isTypeAssignableTo(assignedType, reducedType)) {
  50806. return reducedType;
  50807. }
  50808. }
  50809. return declaredType;
  50810. }
  50811. function getTypeFactsOfTypes(types) {
  50812. var result = 0 /* None */;
  50813. for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
  50814. var t = types_14[_i];
  50815. result |= getTypeFacts(t);
  50816. }
  50817. return result;
  50818. }
  50819. function isFunctionObjectType(type) {
  50820. // We do a quick check for a "bind" property before performing the more expensive subtype
  50821. // check. This gives us a quicker out in the common case where an object type is not a function.
  50822. var resolved = resolveStructuredTypeMembers(type);
  50823. return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
  50824. resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
  50825. }
  50826. function getTypeFacts(type) {
  50827. var flags = type.flags;
  50828. if (flags & 4 /* String */) {
  50829. return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
  50830. }
  50831. if (flags & 128 /* StringLiteral */) {
  50832. var isEmpty = type.value === "";
  50833. return strictNullChecks ?
  50834. isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
  50835. isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
  50836. }
  50837. if (flags & (8 /* Number */ | 32 /* Enum */)) {
  50838. return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
  50839. }
  50840. if (flags & 256 /* NumberLiteral */) {
  50841. var isZero = type.value === 0;
  50842. return strictNullChecks ?
  50843. isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
  50844. isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
  50845. }
  50846. if (flags & 64 /* BigInt */) {
  50847. return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
  50848. }
  50849. if (flags & 2048 /* BigIntLiteral */) {
  50850. var isZero = isZeroBigInt(type);
  50851. return strictNullChecks ?
  50852. isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
  50853. isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
  50854. }
  50855. if (flags & 16 /* Boolean */) {
  50856. return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
  50857. }
  50858. if (flags & 528 /* BooleanLike */) {
  50859. return strictNullChecks ?
  50860. (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
  50861. (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
  50862. }
  50863. if (flags & 524288 /* Object */) {
  50864. return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
  50865. strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
  50866. isFunctionObjectType(type) ?
  50867. strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
  50868. strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
  50869. }
  50870. if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
  50871. return 9830144 /* UndefinedFacts */;
  50872. }
  50873. if (flags & 65536 /* Null */) {
  50874. return 9363232 /* NullFacts */;
  50875. }
  50876. if (flags & 12288 /* ESSymbolLike */) {
  50877. return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
  50878. }
  50879. if (flags & 67108864 /* NonPrimitive */) {
  50880. return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
  50881. }
  50882. if (flags & 63176704 /* Instantiable */) {
  50883. return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
  50884. }
  50885. if (flags & 3145728 /* UnionOrIntersection */) {
  50886. return getTypeFactsOfTypes(type.types);
  50887. }
  50888. return 16777215 /* All */;
  50889. }
  50890. function getTypeWithFacts(type, include) {
  50891. return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
  50892. }
  50893. function getTypeWithDefault(type, defaultExpression) {
  50894. if (defaultExpression) {
  50895. var defaultType = getTypeOfExpression(defaultExpression);
  50896. return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
  50897. }
  50898. return type;
  50899. }
  50900. function getTypeOfDestructuredProperty(type, name) {
  50901. var nameType = getLiteralTypeFromPropertyName(name);
  50902. if (!isTypeUsableAsPropertyName(nameType))
  50903. return errorType;
  50904. var text = getPropertyNameFromType(nameType);
  50905. return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
  50906. isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
  50907. getIndexTypeOfType(type, 0 /* String */) ||
  50908. errorType;
  50909. }
  50910. function getTypeOfDestructuredArrayElement(type, index) {
  50911. return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
  50912. checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
  50913. errorType;
  50914. }
  50915. function getTypeOfDestructuredSpreadExpression(type) {
  50916. return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
  50917. }
  50918. function getAssignedTypeOfBinaryExpression(node) {
  50919. var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
  50920. node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
  50921. return isDestructuringDefaultAssignment ?
  50922. getTypeWithDefault(getAssignedType(node), node.right) :
  50923. getTypeOfExpression(node.right);
  50924. }
  50925. function isDestructuringAssignmentTarget(parent) {
  50926. return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
  50927. parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
  50928. }
  50929. function getAssignedTypeOfArrayLiteralElement(node, element) {
  50930. return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
  50931. }
  50932. function getAssignedTypeOfSpreadExpression(node) {
  50933. return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
  50934. }
  50935. function getAssignedTypeOfPropertyAssignment(node) {
  50936. return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
  50937. }
  50938. function getAssignedTypeOfShorthandPropertyAssignment(node) {
  50939. return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
  50940. }
  50941. function getAssignedType(node) {
  50942. var parent = node.parent;
  50943. switch (parent.kind) {
  50944. case 231 /* ForInStatement */:
  50945. return stringType;
  50946. case 232 /* ForOfStatement */:
  50947. return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType;
  50948. case 209 /* BinaryExpression */:
  50949. return getAssignedTypeOfBinaryExpression(parent);
  50950. case 203 /* DeleteExpression */:
  50951. return undefinedType;
  50952. case 192 /* ArrayLiteralExpression */:
  50953. return getAssignedTypeOfArrayLiteralElement(parent, node);
  50954. case 213 /* SpreadElement */:
  50955. return getAssignedTypeOfSpreadExpression(parent);
  50956. case 281 /* PropertyAssignment */:
  50957. return getAssignedTypeOfPropertyAssignment(parent);
  50958. case 282 /* ShorthandPropertyAssignment */:
  50959. return getAssignedTypeOfShorthandPropertyAssignment(parent);
  50960. }
  50961. return errorType;
  50962. }
  50963. function getInitialTypeOfBindingElement(node) {
  50964. var pattern = node.parent;
  50965. var parentType = getInitialType(pattern.parent);
  50966. var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
  50967. getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
  50968. !node.dotDotDotToken ?
  50969. getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
  50970. getTypeOfDestructuredSpreadExpression(parentType);
  50971. return getTypeWithDefault(type, node.initializer);
  50972. }
  50973. function getTypeOfInitializer(node) {
  50974. // Return the cached type if one is available. If the type of the variable was inferred
  50975. // from its initializer, we'll already have cached the type. Otherwise we compute it now
  50976. // without caching such that transient types are reflected.
  50977. var links = getNodeLinks(node);
  50978. return links.resolvedType || getTypeOfExpression(node);
  50979. }
  50980. function getInitialTypeOfVariableDeclaration(node) {
  50981. if (node.initializer) {
  50982. return getTypeOfInitializer(node.initializer);
  50983. }
  50984. if (node.parent.parent.kind === 231 /* ForInStatement */) {
  50985. return stringType;
  50986. }
  50987. if (node.parent.parent.kind === 232 /* ForOfStatement */) {
  50988. return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType;
  50989. }
  50990. return errorType;
  50991. }
  50992. function getInitialType(node) {
  50993. return node.kind === 242 /* VariableDeclaration */ ?
  50994. getInitialTypeOfVariableDeclaration(node) :
  50995. getInitialTypeOfBindingElement(node);
  50996. }
  50997. function isEmptyArrayAssignment(node) {
  50998. return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
  50999. isEmptyArrayLiteral(node.initializer) ||
  51000. node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
  51001. isEmptyArrayLiteral(node.parent.right);
  51002. }
  51003. function getReferenceCandidate(node) {
  51004. switch (node.kind) {
  51005. case 200 /* ParenthesizedExpression */:
  51006. return getReferenceCandidate(node.expression);
  51007. case 209 /* BinaryExpression */:
  51008. switch (node.operatorToken.kind) {
  51009. case 62 /* EqualsToken */:
  51010. return getReferenceCandidate(node.left);
  51011. case 27 /* CommaToken */:
  51012. return getReferenceCandidate(node.right);
  51013. }
  51014. }
  51015. return node;
  51016. }
  51017. function getReferenceRoot(node) {
  51018. var parent = node.parent;
  51019. return parent.kind === 200 /* ParenthesizedExpression */ ||
  51020. parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
  51021. parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
  51022. getReferenceRoot(parent) : node;
  51023. }
  51024. function getTypeOfSwitchClause(clause) {
  51025. if (clause.kind === 277 /* CaseClause */) {
  51026. return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
  51027. }
  51028. return neverType;
  51029. }
  51030. function getSwitchClauseTypes(switchStatement) {
  51031. var links = getNodeLinks(switchStatement);
  51032. if (!links.switchTypes) {
  51033. links.switchTypes = [];
  51034. for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
  51035. var clause = _a[_i];
  51036. links.switchTypes.push(getTypeOfSwitchClause(clause));
  51037. }
  51038. }
  51039. return links.switchTypes;
  51040. }
  51041. // Get the types from all cases in a switch on `typeof`. An
  51042. // `undefined` element denotes an explicit `default` clause.
  51043. function getSwitchClauseTypeOfWitnesses(switchStatement) {
  51044. var witnesses = [];
  51045. for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
  51046. var clause = _a[_i];
  51047. if (clause.kind === 277 /* CaseClause */) {
  51048. if (ts.isStringLiteralLike(clause.expression)) {
  51049. witnesses.push(clause.expression.text);
  51050. continue;
  51051. }
  51052. return ts.emptyArray;
  51053. }
  51054. witnesses.push(/*explicitDefaultStatement*/ undefined);
  51055. }
  51056. return witnesses;
  51057. }
  51058. function eachTypeContainedIn(source, types) {
  51059. return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
  51060. }
  51061. function isTypeSubsetOf(source, target) {
  51062. return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
  51063. }
  51064. function isTypeSubsetOfUnion(source, target) {
  51065. if (source.flags & 1048576 /* Union */) {
  51066. for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
  51067. var t = _a[_i];
  51068. if (!containsType(target.types, t)) {
  51069. return false;
  51070. }
  51071. }
  51072. return true;
  51073. }
  51074. if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
  51075. return true;
  51076. }
  51077. return containsType(target.types, source);
  51078. }
  51079. function forEachType(type, f) {
  51080. return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
  51081. }
  51082. function everyType(type, f) {
  51083. return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
  51084. }
  51085. function filterType(type, f) {
  51086. if (type.flags & 1048576 /* Union */) {
  51087. var types = type.types;
  51088. var filtered = ts.filter(types, f);
  51089. return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
  51090. }
  51091. return f(type) ? type : neverType;
  51092. }
  51093. function countTypes(type) {
  51094. return type.flags & 1048576 /* Union */ ? type.types.length : 1;
  51095. }
  51096. function mapType(type, mapper, noReductions) {
  51097. if (type.flags & 131072 /* Never */) {
  51098. return type;
  51099. }
  51100. if (!(type.flags & 1048576 /* Union */)) {
  51101. return mapper(type);
  51102. }
  51103. var mappedTypes;
  51104. for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
  51105. var t = _a[_i];
  51106. var mapped = mapper(t);
  51107. if (mapped) {
  51108. if (!mappedTypes) {
  51109. mappedTypes = [mapped];
  51110. }
  51111. else {
  51112. mappedTypes.push(mapped);
  51113. }
  51114. }
  51115. }
  51116. return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
  51117. }
  51118. function extractTypesOfKind(type, kind) {
  51119. return filterType(type, function (t) { return (t.flags & kind) !== 0; });
  51120. }
  51121. // Return a new type in which occurrences of the string and number primitive types in
  51122. // typeWithPrimitives have been replaced with occurrences of string literals and numeric
  51123. // literals in typeWithLiterals, respectively.
  51124. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
  51125. if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
  51126. isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
  51127. isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
  51128. return mapType(typeWithPrimitives, function (t) {
  51129. return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
  51130. t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
  51131. t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
  51132. });
  51133. }
  51134. return typeWithPrimitives;
  51135. }
  51136. function isIncomplete(flowType) {
  51137. return flowType.flags === 0;
  51138. }
  51139. function getTypeFromFlowType(flowType) {
  51140. return flowType.flags === 0 ? flowType.type : flowType;
  51141. }
  51142. function createFlowType(type, incomplete) {
  51143. return incomplete ? { flags: 0, type: type } : type;
  51144. }
  51145. // An evolving array type tracks the element types that have so far been seen in an
  51146. // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
  51147. // array types are ultimately converted into manifest array types (using getFinalArrayType)
  51148. // and never escape the getFlowTypeOfReference function.
  51149. function createEvolvingArrayType(elementType) {
  51150. var result = createObjectType(256 /* EvolvingArray */);
  51151. result.elementType = elementType;
  51152. return result;
  51153. }
  51154. function getEvolvingArrayType(elementType) {
  51155. return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
  51156. }
  51157. // When adding evolving array element types we do not perform subtype reduction. Instead,
  51158. // we defer subtype reduction until the evolving array type is finalized into a manifest
  51159. // array type.
  51160. function addEvolvingArrayElementType(evolvingArrayType, node) {
  51161. var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
  51162. return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
  51163. }
  51164. function createFinalArrayType(elementType) {
  51165. return elementType.flags & 131072 /* Never */ ?
  51166. autoArrayType :
  51167. createArrayType(elementType.flags & 1048576 /* Union */ ?
  51168. getUnionType(elementType.types, 2 /* Subtype */) :
  51169. elementType);
  51170. }
  51171. // We perform subtype reduction upon obtaining the final array type from an evolving array type.
  51172. function getFinalArrayType(evolvingArrayType) {
  51173. return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
  51174. }
  51175. function finalizeEvolvingArrayType(type) {
  51176. return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
  51177. }
  51178. function getElementTypeOfEvolvingArrayType(type) {
  51179. return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
  51180. }
  51181. function isEvolvingArrayTypeList(types) {
  51182. var hasEvolvingArrayType = false;
  51183. for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
  51184. var t = types_15[_i];
  51185. if (!(t.flags & 131072 /* Never */)) {
  51186. if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
  51187. return false;
  51188. }
  51189. hasEvolvingArrayType = true;
  51190. }
  51191. }
  51192. return hasEvolvingArrayType;
  51193. }
  51194. // At flow control branch or loop junctions, if the type along every antecedent code path
  51195. // is an evolving array type, we construct a combined evolving array type. Otherwise we
  51196. // finalize all evolving array types.
  51197. function getUnionOrEvolvingArrayType(types, subtypeReduction) {
  51198. return isEvolvingArrayTypeList(types) ?
  51199. getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
  51200. getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
  51201. }
  51202. // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
  51203. // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
  51204. function isEvolvingArrayOperationTarget(node) {
  51205. var root = getReferenceRoot(node);
  51206. var parent = root.parent;
  51207. var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
  51208. parent.parent.kind === 196 /* CallExpression */
  51209. && ts.isIdentifier(parent.name)
  51210. && ts.isPushOrUnshiftIdentifier(parent.name));
  51211. var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
  51212. parent.expression === root &&
  51213. parent.parent.kind === 209 /* BinaryExpression */ &&
  51214. parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
  51215. parent.parent.left === parent &&
  51216. !ts.isAssignmentTarget(parent.parent) &&
  51217. isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
  51218. return isLengthPushOrUnshift || isElementAssignment;
  51219. }
  51220. function isDeclarationWithExplicitTypeAnnotation(declaration) {
  51221. return !!(declaration && (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
  51222. declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
  51223. ts.getEffectiveTypeAnnotationNode(declaration));
  51224. }
  51225. function getExplicitTypeOfSymbol(symbol, diagnostic) {
  51226. if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
  51227. return getTypeOfSymbol(symbol);
  51228. }
  51229. if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
  51230. if (isDeclarationWithExplicitTypeAnnotation(symbol.valueDeclaration)) {
  51231. return getTypeOfSymbol(symbol);
  51232. }
  51233. if (diagnostic && symbol.valueDeclaration) {
  51234. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(symbol.valueDeclaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
  51235. }
  51236. }
  51237. }
  51238. // We require the dotted function name in an assertion expression to be comprised of identifiers
  51239. // that reference function, method, class or value module symbols; or variable, property or
  51240. // parameter symbols with declarations that have explicit type annotations. Such references are
  51241. // resolvable with no possibility of triggering circularities in control flow analysis.
  51242. function getTypeOfDottedName(node, diagnostic) {
  51243. if (!(node.flags & 16777216 /* InWithStatement */)) {
  51244. switch (node.kind) {
  51245. case 75 /* Identifier */:
  51246. var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
  51247. return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
  51248. case 104 /* ThisKeyword */:
  51249. return getExplicitThisType(node);
  51250. case 102 /* SuperKeyword */:
  51251. return checkSuperExpression(node);
  51252. case 194 /* PropertyAccessExpression */:
  51253. var type = getTypeOfDottedName(node.expression, diagnostic);
  51254. var prop = type && getPropertyOfType(type, node.name.escapedText);
  51255. return prop && getExplicitTypeOfSymbol(prop, diagnostic);
  51256. case 200 /* ParenthesizedExpression */:
  51257. return getTypeOfDottedName(node.expression, diagnostic);
  51258. }
  51259. }
  51260. }
  51261. function getEffectsSignature(node) {
  51262. var links = getNodeLinks(node);
  51263. var signature = links.effectsSignature;
  51264. if (signature === undefined) {
  51265. // A call expression parented by an expression statement is a potential assertion. Other call
  51266. // expressions are potential type predicate function calls. In order to avoid triggering
  51267. // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
  51268. // target expression of an assertion.
  51269. var funcType = void 0;
  51270. if (node.parent.kind === 226 /* ExpressionStatement */) {
  51271. funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
  51272. }
  51273. else if (node.expression.kind !== 102 /* SuperKeyword */) {
  51274. if (ts.isOptionalChain(node)) {
  51275. funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
  51276. }
  51277. else {
  51278. funcType = checkNonNullExpression(node.expression);
  51279. }
  51280. }
  51281. var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
  51282. var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
  51283. ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
  51284. undefined;
  51285. signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
  51286. }
  51287. return signature === unknownSignature ? undefined : signature;
  51288. }
  51289. function hasTypePredicateOrNeverReturnType(signature) {
  51290. return !!(getTypePredicateOfSignature(signature) ||
  51291. signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
  51292. }
  51293. function getTypePredicateArgument(predicate, callExpression) {
  51294. if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
  51295. return callExpression.arguments[predicate.parameterIndex];
  51296. }
  51297. var invokedExpression = ts.skipParentheses(callExpression.expression);
  51298. return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
  51299. }
  51300. function reportFlowControlError(node) {
  51301. var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
  51302. var sourceFile = ts.getSourceFileOfNode(node);
  51303. var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
  51304. diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
  51305. }
  51306. function isReachableFlowNode(flow) {
  51307. var result = isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false);
  51308. lastFlowNode = flow;
  51309. lastFlowNodeReachable = result;
  51310. return result;
  51311. }
  51312. function isUnlockedReachableFlowNode(flow) {
  51313. return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false);
  51314. }
  51315. function isFalseExpression(expr) {
  51316. var node = ts.skipParentheses(expr);
  51317. return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
  51318. node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
  51319. }
  51320. function isReachableFlowNodeWorker(flow, noCacheCheck) {
  51321. while (true) {
  51322. if (flow === lastFlowNode) {
  51323. return lastFlowNodeReachable;
  51324. }
  51325. var flags = flow.flags;
  51326. if (flags & 2048 /* Shared */) {
  51327. if (!noCacheCheck) {
  51328. var id = getFlowNodeId(flow);
  51329. var reachable = flowNodeReachable[id];
  51330. return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ true));
  51331. }
  51332. noCacheCheck = false;
  51333. }
  51334. if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 4096 /* PreFinally */)) {
  51335. flow = flow.antecedent;
  51336. }
  51337. else if (flags & 512 /* Call */) {
  51338. var signature = getEffectsSignature(flow.node);
  51339. if (signature) {
  51340. var predicate = getTypePredicateOfSignature(signature);
  51341. if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
  51342. var predicateArgument = flow.node.arguments[predicate.parameterIndex];
  51343. if (predicateArgument && isFalseExpression(predicateArgument)) {
  51344. return false;
  51345. }
  51346. }
  51347. if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
  51348. return false;
  51349. }
  51350. }
  51351. flow = flow.antecedent;
  51352. }
  51353. else if (flags & 4 /* BranchLabel */) {
  51354. // A branching point is reachable if any branch is reachable.
  51355. return ts.some(flow.antecedents, isUnlockedReachableFlowNode);
  51356. }
  51357. else if (flags & 8 /* LoopLabel */) {
  51358. // A loop is reachable if the control flow path that leads to the top is reachable.
  51359. flow = flow.antecedents[0];
  51360. }
  51361. else if (flags & 128 /* SwitchClause */) {
  51362. // The control flow path representing an unmatched value in a switch statement with
  51363. // no default clause is unreachable if the switch statement is exhaustive.
  51364. if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
  51365. return false;
  51366. }
  51367. flow = flow.antecedent;
  51368. }
  51369. else if (flags & 8192 /* AfterFinally */) {
  51370. // Cache is unreliable once we start locking nodes
  51371. lastFlowNode = undefined;
  51372. flow.locked = true;
  51373. var result = isReachableFlowNodeWorker(flow.antecedent, /*skipCacheCheck*/ false);
  51374. flow.locked = false;
  51375. return result;
  51376. }
  51377. else {
  51378. return !(flags & 1 /* Unreachable */);
  51379. }
  51380. }
  51381. }
  51382. function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
  51383. if (initialType === void 0) { initialType = declaredType; }
  51384. var key;
  51385. var keySet = false;
  51386. var flowDepth = 0;
  51387. if (flowAnalysisDisabled) {
  51388. return errorType;
  51389. }
  51390. if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
  51391. return declaredType;
  51392. }
  51393. flowInvocationCount++;
  51394. var sharedFlowStart = sharedFlowCount;
  51395. var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
  51396. sharedFlowCount = sharedFlowStart;
  51397. // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
  51398. // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
  51399. // on empty arrays are possible without implicit any errors and new element types can be inferred without
  51400. // type mismatch errors.
  51401. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
  51402. if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
  51403. return declaredType;
  51404. }
  51405. return resultType;
  51406. function getOrSetCacheKey() {
  51407. if (keySet) {
  51408. return key;
  51409. }
  51410. keySet = true;
  51411. return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
  51412. }
  51413. function getTypeAtFlowNode(flow) {
  51414. if (flowDepth === 2000) {
  51415. // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
  51416. // and disable further control flow analysis in the containing function or module body.
  51417. flowAnalysisDisabled = true;
  51418. reportFlowControlError(reference);
  51419. return errorType;
  51420. }
  51421. flowDepth++;
  51422. while (true) {
  51423. var flags = flow.flags;
  51424. if (flags & 2048 /* Shared */) {
  51425. // We cache results of flow type resolution for shared nodes that were previously visited in
  51426. // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
  51427. // antecedent of more than one node.
  51428. for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
  51429. if (sharedFlowNodes[i] === flow) {
  51430. flowDepth--;
  51431. return sharedFlowTypes[i];
  51432. }
  51433. }
  51434. }
  51435. var type = void 0;
  51436. if (flags & 8192 /* AfterFinally */) {
  51437. // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement
  51438. flow.locked = true;
  51439. type = getTypeAtFlowNode(flow.antecedent);
  51440. flow.locked = false;
  51441. }
  51442. else if (flags & 4096 /* PreFinally */) {
  51443. // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel
  51444. // so here just redirect to antecedent
  51445. flow = flow.antecedent;
  51446. continue;
  51447. }
  51448. else if (flags & 16 /* Assignment */) {
  51449. type = getTypeAtFlowAssignment(flow);
  51450. if (!type) {
  51451. flow = flow.antecedent;
  51452. continue;
  51453. }
  51454. }
  51455. else if (flags & 512 /* Call */) {
  51456. type = getTypeAtFlowCall(flow);
  51457. if (!type) {
  51458. flow = flow.antecedent;
  51459. continue;
  51460. }
  51461. }
  51462. else if (flags & 96 /* Condition */) {
  51463. type = getTypeAtFlowCondition(flow);
  51464. }
  51465. else if (flags & 128 /* SwitchClause */) {
  51466. type = getTypeAtSwitchClause(flow);
  51467. }
  51468. else if (flags & 12 /* Label */) {
  51469. if (flow.antecedents.length === 1) {
  51470. flow = flow.antecedents[0];
  51471. continue;
  51472. }
  51473. type = flags & 4 /* BranchLabel */ ?
  51474. getTypeAtFlowBranchLabel(flow) :
  51475. getTypeAtFlowLoopLabel(flow);
  51476. }
  51477. else if (flags & 256 /* ArrayMutation */) {
  51478. type = getTypeAtFlowArrayMutation(flow);
  51479. if (!type) {
  51480. flow = flow.antecedent;
  51481. continue;
  51482. }
  51483. }
  51484. else if (flags & 2 /* Start */) {
  51485. // Check if we should continue with the control flow of the containing function.
  51486. var container = flow.node;
  51487. if (container && container !== flowContainer &&
  51488. reference.kind !== 194 /* PropertyAccessExpression */ &&
  51489. reference.kind !== 195 /* ElementAccessExpression */ &&
  51490. reference.kind !== 104 /* ThisKeyword */) {
  51491. flow = container.flowNode;
  51492. continue;
  51493. }
  51494. // At the top of the flow we have the initial type.
  51495. type = initialType;
  51496. }
  51497. else {
  51498. // Unreachable code errors are reported in the binding phase. Here we
  51499. // simply return the non-auto declared type to reduce follow-on errors.
  51500. type = convertAutoToAny(declaredType);
  51501. }
  51502. if (flags & 2048 /* Shared */) {
  51503. // Record visited node and the associated type in the cache.
  51504. sharedFlowNodes[sharedFlowCount] = flow;
  51505. sharedFlowTypes[sharedFlowCount] = type;
  51506. sharedFlowCount++;
  51507. }
  51508. flowDepth--;
  51509. return type;
  51510. }
  51511. }
  51512. function getInitialOrAssignedType(flow) {
  51513. var node = flow.node;
  51514. return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
  51515. getInitialType(node) :
  51516. getAssignedType(node), reference);
  51517. }
  51518. function getTypeAtFlowAssignment(flow) {
  51519. var node = flow.node;
  51520. // Assignments only narrow the computed type if the declared type is a union type. Thus, we
  51521. // only need to evaluate the assigned type if the declared type is a union type.
  51522. if (isMatchingReference(reference, node)) {
  51523. if (!isReachableFlowNode(flow)) {
  51524. return unreachableNeverType;
  51525. }
  51526. if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
  51527. var flowType = getTypeAtFlowNode(flow.antecedent);
  51528. return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
  51529. }
  51530. if (declaredType === autoType || declaredType === autoArrayType) {
  51531. if (isEmptyArrayAssignment(node)) {
  51532. return getEvolvingArrayType(neverType);
  51533. }
  51534. var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
  51535. return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
  51536. }
  51537. if (declaredType.flags & 1048576 /* Union */) {
  51538. return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
  51539. }
  51540. return declaredType;
  51541. }
  51542. // We didn't have a direct match. However, if the reference is a dotted name, this
  51543. // may be an assignment to a left hand part of the reference. For example, for a
  51544. // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
  51545. // return the declared type.
  51546. if (containsMatchingReference(reference, node)) {
  51547. if (!isReachableFlowNode(flow)) {
  51548. return unreachableNeverType;
  51549. }
  51550. // A matching dotted name might also be an expando property on a function *expression*,
  51551. // in which case we continue control flow analysis back to the function's declaration
  51552. if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
  51553. var init = ts.getDeclaredExpandoInitializer(node);
  51554. if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
  51555. return getTypeAtFlowNode(flow.antecedent);
  51556. }
  51557. }
  51558. return declaredType;
  51559. }
  51560. // for (const _ in ref) acts as a nonnull on ref
  51561. if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
  51562. return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
  51563. }
  51564. // Assignment doesn't affect reference
  51565. return undefined;
  51566. }
  51567. function narrowTypeByAssertion(type, expr) {
  51568. var node = ts.skipParentheses(expr);
  51569. if (node.kind === 91 /* FalseKeyword */) {
  51570. return unreachableNeverType;
  51571. }
  51572. if (node.kind === 209 /* BinaryExpression */) {
  51573. if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
  51574. return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
  51575. }
  51576. if (node.operatorToken.kind === 56 /* BarBarToken */) {
  51577. return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
  51578. }
  51579. }
  51580. return narrowType(type, node, /*assumeTrue*/ true);
  51581. }
  51582. function getTypeAtFlowCall(flow) {
  51583. var signature = getEffectsSignature(flow.node);
  51584. if (signature) {
  51585. var predicate = getTypePredicateOfSignature(signature);
  51586. if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
  51587. var flowType = getTypeAtFlowNode(flow.antecedent);
  51588. var type = getTypeFromFlowType(flowType);
  51589. var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
  51590. predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
  51591. type;
  51592. return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
  51593. }
  51594. if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
  51595. return unreachableNeverType;
  51596. }
  51597. }
  51598. return undefined;
  51599. }
  51600. function getTypeAtFlowArrayMutation(flow) {
  51601. if (declaredType === autoType || declaredType === autoArrayType) {
  51602. var node = flow.node;
  51603. var expr = node.kind === 196 /* CallExpression */ ?
  51604. node.expression.expression :
  51605. node.left.expression;
  51606. if (isMatchingReference(reference, getReferenceCandidate(expr))) {
  51607. var flowType = getTypeAtFlowNode(flow.antecedent);
  51608. var type = getTypeFromFlowType(flowType);
  51609. if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
  51610. var evolvedType_1 = type;
  51611. if (node.kind === 196 /* CallExpression */) {
  51612. for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
  51613. var arg = _a[_i];
  51614. evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
  51615. }
  51616. }
  51617. else {
  51618. // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time)
  51619. var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
  51620. if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
  51621. evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
  51622. }
  51623. }
  51624. return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
  51625. }
  51626. return flowType;
  51627. }
  51628. }
  51629. return undefined;
  51630. }
  51631. function getTypeAtFlowCondition(flow) {
  51632. var flowType = getTypeAtFlowNode(flow.antecedent);
  51633. var type = getTypeFromFlowType(flowType);
  51634. if (type.flags & 131072 /* Never */) {
  51635. return flowType;
  51636. }
  51637. // If we have an antecedent type (meaning we're reachable in some way), we first
  51638. // attempt to narrow the antecedent type. If that produces the never type, and if
  51639. // the antecedent type is incomplete (i.e. a transient type in a loop), then we
  51640. // take the type guard as an indication that control *could* reach here once we
  51641. // have the complete type. We proceed by switching to the silent never type which
  51642. // doesn't report errors when operators are applied to it. Note that this is the
  51643. // *only* place a silent never type is ever generated.
  51644. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
  51645. var nonEvolvingType = finalizeEvolvingArrayType(type);
  51646. var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
  51647. if (narrowedType === nonEvolvingType) {
  51648. return flowType;
  51649. }
  51650. var incomplete = isIncomplete(flowType);
  51651. var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
  51652. return createFlowType(resultType, incomplete);
  51653. }
  51654. function getTypeAtSwitchClause(flow) {
  51655. var expr = flow.switchStatement.expression;
  51656. var flowType = getTypeAtFlowNode(flow.antecedent);
  51657. var type = getTypeFromFlowType(flowType);
  51658. if (isMatchingReference(reference, expr)) {
  51659. type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
  51660. }
  51661. else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
  51662. type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
  51663. }
  51664. else {
  51665. if (strictNullChecks) {
  51666. if (optionalChainContainsReference(expr, reference)) {
  51667. type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
  51668. }
  51669. else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
  51670. type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
  51671. }
  51672. }
  51673. if (isMatchingReferenceDiscriminant(expr, type)) {
  51674. type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
  51675. }
  51676. }
  51677. return createFlowType(type, isIncomplete(flowType));
  51678. }
  51679. function getTypeAtFlowBranchLabel(flow) {
  51680. var antecedentTypes = [];
  51681. var subtypeReduction = false;
  51682. var seenIncomplete = false;
  51683. var bypassFlow;
  51684. for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
  51685. var antecedent = _a[_i];
  51686. if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) {
  51687. // if flow correspond to branch from pre-try to finally and this branch is locked - this means that
  51688. // we initially have started following the flow outside the finally block.
  51689. // in this case we should ignore this branch.
  51690. continue;
  51691. }
  51692. if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
  51693. // The antecedent is the bypass branch of a potentially exhaustive switch statement.
  51694. bypassFlow = antecedent;
  51695. continue;
  51696. }
  51697. var flowType = getTypeAtFlowNode(antecedent);
  51698. var type = getTypeFromFlowType(flowType);
  51699. // If the type at a particular antecedent path is the declared type and the
  51700. // reference is known to always be assigned (i.e. when declared and initial types
  51701. // are the same), there is no reason to process more antecedents since the only
  51702. // possible outcome is subtypes that will be removed in the final union type anyway.
  51703. if (type === declaredType && declaredType === initialType) {
  51704. return type;
  51705. }
  51706. ts.pushIfUnique(antecedentTypes, type);
  51707. // If an antecedent type is not a subset of the declared type, we need to perform
  51708. // subtype reduction. This happens when a "foreign" type is injected into the control
  51709. // flow using the instanceof operator or a user defined type predicate.
  51710. if (!isTypeSubsetOf(type, declaredType)) {
  51711. subtypeReduction = true;
  51712. }
  51713. if (isIncomplete(flowType)) {
  51714. seenIncomplete = true;
  51715. }
  51716. }
  51717. if (bypassFlow) {
  51718. var flowType = getTypeAtFlowNode(bypassFlow);
  51719. var type = getTypeFromFlowType(flowType);
  51720. // If the bypass flow contributes a type we haven't seen yet and the switch statement
  51721. // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
  51722. // the risk of circularities, we only want to perform them when they make a difference.
  51723. if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
  51724. if (type === declaredType && declaredType === initialType) {
  51725. return type;
  51726. }
  51727. antecedentTypes.push(type);
  51728. if (!isTypeSubsetOf(type, declaredType)) {
  51729. subtypeReduction = true;
  51730. }
  51731. if (isIncomplete(flowType)) {
  51732. seenIncomplete = true;
  51733. }
  51734. }
  51735. }
  51736. return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
  51737. }
  51738. function getTypeAtFlowLoopLabel(flow) {
  51739. // If we have previously computed the control flow type for the reference at
  51740. // this flow loop junction, return the cached type.
  51741. var id = getFlowNodeId(flow);
  51742. var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
  51743. var key = getOrSetCacheKey();
  51744. if (!key) {
  51745. // No cache key is generated when binding patterns are in unnarrowable situations
  51746. return declaredType;
  51747. }
  51748. var cached = cache.get(key);
  51749. if (cached) {
  51750. return cached;
  51751. }
  51752. // If this flow loop junction and reference are already being processed, return
  51753. // the union of the types computed for each branch so far, marked as incomplete.
  51754. // It is possible to see an empty array in cases where loops are nested and the
  51755. // back edge of the outer loop reaches an inner loop that is already being analyzed.
  51756. // In such cases we restart the analysis of the inner loop, which will then see
  51757. // a non-empty in-process array for the outer loop and eventually terminate because
  51758. // the first antecedent of a loop junction is always the non-looping control flow
  51759. // path that leads to the top.
  51760. for (var i = flowLoopStart; i < flowLoopCount; i++) {
  51761. if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
  51762. return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
  51763. }
  51764. }
  51765. // Add the flow loop junction and reference to the in-process stack and analyze
  51766. // each antecedent code path.
  51767. var antecedentTypes = [];
  51768. var subtypeReduction = false;
  51769. var firstAntecedentType;
  51770. for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
  51771. var antecedent = _a[_i];
  51772. var flowType = void 0;
  51773. if (!firstAntecedentType) {
  51774. // The first antecedent of a loop junction is always the non-looping control
  51775. // flow path that leads to the top.
  51776. flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
  51777. }
  51778. else {
  51779. // All but the first antecedent are the looping control flow paths that lead
  51780. // back to the loop junction. We track these on the flow loop stack.
  51781. flowLoopNodes[flowLoopCount] = flow;
  51782. flowLoopKeys[flowLoopCount] = key;
  51783. flowLoopTypes[flowLoopCount] = antecedentTypes;
  51784. flowLoopCount++;
  51785. var saveFlowTypeCache = flowTypeCache;
  51786. flowTypeCache = undefined;
  51787. flowType = getTypeAtFlowNode(antecedent);
  51788. flowTypeCache = saveFlowTypeCache;
  51789. flowLoopCount--;
  51790. // If we see a value appear in the cache it is a sign that control flow analysis
  51791. // was restarted and completed by checkExpressionCached. We can simply pick up
  51792. // the resulting type and bail out.
  51793. var cached_1 = cache.get(key);
  51794. if (cached_1) {
  51795. return cached_1;
  51796. }
  51797. }
  51798. var type = getTypeFromFlowType(flowType);
  51799. ts.pushIfUnique(antecedentTypes, type);
  51800. // If an antecedent type is not a subset of the declared type, we need to perform
  51801. // subtype reduction. This happens when a "foreign" type is injected into the control
  51802. // flow using the instanceof operator or a user defined type predicate.
  51803. if (!isTypeSubsetOf(type, declaredType)) {
  51804. subtypeReduction = true;
  51805. }
  51806. // If the type at a particular antecedent path is the declared type there is no
  51807. // reason to process more antecedents since the only possible outcome is subtypes
  51808. // that will be removed in the final union type anyway.
  51809. if (type === declaredType) {
  51810. break;
  51811. }
  51812. }
  51813. // The result is incomplete if the first antecedent (the non-looping control flow path)
  51814. // is incomplete.
  51815. var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
  51816. if (isIncomplete(firstAntecedentType)) {
  51817. return createFlowType(result, /*incomplete*/ true);
  51818. }
  51819. cache.set(key, result);
  51820. return result;
  51821. }
  51822. function isMatchingReferenceDiscriminant(expr, computedType) {
  51823. if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
  51824. return false;
  51825. }
  51826. var name = getAccessedPropertyName(expr);
  51827. if (name === undefined) {
  51828. return false;
  51829. }
  51830. return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
  51831. }
  51832. function narrowTypeByDiscriminant(type, access, narrowType) {
  51833. var propName = getAccessedPropertyName(access);
  51834. if (propName === undefined) {
  51835. return type;
  51836. }
  51837. var propType = getTypeOfPropertyOfType(type, propName);
  51838. if (!propType) {
  51839. return type;
  51840. }
  51841. var narrowedPropType = narrowType(propType);
  51842. return filterType(type, function (t) {
  51843. var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
  51844. return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
  51845. });
  51846. }
  51847. function narrowTypeByTruthiness(type, expr, assumeTrue) {
  51848. if (isMatchingReference(reference, expr)) {
  51849. return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
  51850. }
  51851. if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
  51852. type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
  51853. }
  51854. if (isMatchingReferenceDiscriminant(expr, declaredType)) {
  51855. return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
  51856. }
  51857. return type;
  51858. }
  51859. function isTypePresencePossible(type, propName, assumeTrue) {
  51860. if (getIndexInfoOfType(type, 0 /* String */)) {
  51861. return true;
  51862. }
  51863. var prop = getPropertyOfType(type, propName);
  51864. if (prop) {
  51865. return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
  51866. }
  51867. return !assumeTrue;
  51868. }
  51869. function narrowByInKeyword(type, literal, assumeTrue) {
  51870. if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
  51871. var propName_1 = ts.escapeLeadingUnderscores(literal.text);
  51872. return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
  51873. }
  51874. return type;
  51875. }
  51876. function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
  51877. switch (expr.operatorToken.kind) {
  51878. case 62 /* EqualsToken */:
  51879. return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
  51880. case 34 /* EqualsEqualsToken */:
  51881. case 35 /* ExclamationEqualsToken */:
  51882. case 36 /* EqualsEqualsEqualsToken */:
  51883. case 37 /* ExclamationEqualsEqualsToken */:
  51884. var operator_1 = expr.operatorToken.kind;
  51885. var left_1 = getReferenceCandidate(expr.left);
  51886. var right_1 = getReferenceCandidate(expr.right);
  51887. if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
  51888. return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
  51889. }
  51890. if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
  51891. return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
  51892. }
  51893. if (isMatchingReference(reference, left_1)) {
  51894. return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
  51895. }
  51896. if (isMatchingReference(reference, right_1)) {
  51897. return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
  51898. }
  51899. if (strictNullChecks) {
  51900. if (optionalChainContainsReference(left_1, reference)) {
  51901. type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
  51902. }
  51903. else if (optionalChainContainsReference(right_1, reference)) {
  51904. type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
  51905. }
  51906. }
  51907. if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
  51908. return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
  51909. }
  51910. if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
  51911. return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
  51912. }
  51913. break;
  51914. case 98 /* InstanceOfKeyword */:
  51915. return narrowTypeByInstanceof(type, expr, assumeTrue);
  51916. case 97 /* InKeyword */:
  51917. var target = getReferenceCandidate(expr.right);
  51918. if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
  51919. return narrowByInKeyword(type, expr.left, assumeTrue);
  51920. }
  51921. break;
  51922. case 27 /* CommaToken */:
  51923. return narrowType(type, expr.right, assumeTrue);
  51924. }
  51925. return type;
  51926. }
  51927. function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
  51928. // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
  51929. // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
  51930. // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
  51931. // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
  51932. // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
  51933. // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
  51934. // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
  51935. // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
  51936. // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
  51937. var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
  51938. var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
  51939. var valueType = getTypeOfExpression(value);
  51940. // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
  51941. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
  51942. equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
  51943. return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
  51944. }
  51945. function narrowTypeByEquality(type, operator, value, assumeTrue) {
  51946. if (type.flags & 1 /* Any */) {
  51947. return type;
  51948. }
  51949. if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
  51950. assumeTrue = !assumeTrue;
  51951. }
  51952. var valueType = getTypeOfExpression(value);
  51953. if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
  51954. if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
  51955. return valueType;
  51956. }
  51957. if (valueType.flags & 524288 /* Object */) {
  51958. return nonPrimitiveType;
  51959. }
  51960. return type;
  51961. }
  51962. if (valueType.flags & 98304 /* Nullable */) {
  51963. if (!strictNullChecks) {
  51964. return type;
  51965. }
  51966. var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
  51967. var facts = doubleEquals ?
  51968. assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
  51969. valueType.flags & 65536 /* Null */ ?
  51970. assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
  51971. assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
  51972. return getTypeWithFacts(type, facts);
  51973. }
  51974. if (type.flags & 67637251 /* NotUnionOrUnit */) {
  51975. return type;
  51976. }
  51977. if (assumeTrue) {
  51978. var filterFn = operator === 34 /* EqualsEqualsToken */ ?
  51979. (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
  51980. function (t) { return areTypesComparable(t, valueType); };
  51981. var narrowedType = filterType(type, filterFn);
  51982. return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
  51983. }
  51984. if (isUnitType(valueType)) {
  51985. var regularType_1 = getRegularTypeOfLiteralType(valueType);
  51986. return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; });
  51987. }
  51988. return type;
  51989. }
  51990. function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
  51991. // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
  51992. if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
  51993. assumeTrue = !assumeTrue;
  51994. }
  51995. var target = getReferenceCandidate(typeOfExpr.expression);
  51996. if (!isMatchingReference(reference, target)) {
  51997. if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
  51998. return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
  51999. }
  52000. // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
  52001. // narrowed type of 'y' to its declared type.
  52002. if (containsMatchingReference(reference, target)) {
  52003. return declaredType;
  52004. }
  52005. return type;
  52006. }
  52007. if (type.flags & 1 /* Any */ && literal.text === "function") {
  52008. return type;
  52009. }
  52010. var facts = assumeTrue ?
  52011. typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
  52012. typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
  52013. return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
  52014. function narrowTypeForTypeof(type) {
  52015. if (type.flags & 2 /* Unknown */ && literal.text === "object") {
  52016. return getUnionType([nonPrimitiveType, nullType]);
  52017. }
  52018. // We narrow a non-union type to an exact primitive type if the non-union type
  52019. // is a supertype of that primitive type. For example, type 'any' can be narrowed
  52020. // to one of the primitive types.
  52021. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
  52022. if (targetType) {
  52023. if (isTypeSubtypeOf(type, targetType)) {
  52024. return type;
  52025. }
  52026. if (isTypeSubtypeOf(targetType, type)) {
  52027. return targetType;
  52028. }
  52029. if (type.flags & 63176704 /* Instantiable */) {
  52030. var constraint = getBaseConstraintOfType(type) || anyType;
  52031. if (isTypeSubtypeOf(targetType, constraint)) {
  52032. return getIntersectionType([type, targetType]);
  52033. }
  52034. }
  52035. }
  52036. return type;
  52037. }
  52038. }
  52039. function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
  52040. var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
  52041. return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
  52042. }
  52043. function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
  52044. // We only narrow if all case expressions specify
  52045. // values with unit types, except for the case where
  52046. // `type` is unknown. In this instance we map object
  52047. // types to the nonPrimitive type and narrow with that.
  52048. var switchTypes = getSwitchClauseTypes(switchStatement);
  52049. if (!switchTypes.length) {
  52050. return type;
  52051. }
  52052. var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
  52053. var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
  52054. if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
  52055. var groundClauseTypes = void 0;
  52056. for (var i = 0; i < clauseTypes.length; i += 1) {
  52057. var t = clauseTypes[i];
  52058. if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
  52059. if (groundClauseTypes !== undefined) {
  52060. groundClauseTypes.push(t);
  52061. }
  52062. }
  52063. else if (t.flags & 524288 /* Object */) {
  52064. if (groundClauseTypes === undefined) {
  52065. groundClauseTypes = clauseTypes.slice(0, i);
  52066. }
  52067. groundClauseTypes.push(nonPrimitiveType);
  52068. }
  52069. else {
  52070. return type;
  52071. }
  52072. }
  52073. return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
  52074. }
  52075. var discriminantType = getUnionType(clauseTypes);
  52076. var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
  52077. replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
  52078. if (!hasDefaultClause) {
  52079. return caseType;
  52080. }
  52081. var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
  52082. return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
  52083. }
  52084. function getImpliedTypeFromTypeofCase(type, text) {
  52085. switch (text) {
  52086. case "function":
  52087. return type.flags & 1 /* Any */ ? type : globalFunctionType;
  52088. case "object":
  52089. return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
  52090. default:
  52091. return typeofTypesByName.get(text) || type;
  52092. }
  52093. }
  52094. function narrowTypeForTypeofSwitch(candidate) {
  52095. return function (type) {
  52096. if (isTypeSubtypeOf(candidate, type)) {
  52097. return candidate;
  52098. }
  52099. if (type.flags & 63176704 /* Instantiable */) {
  52100. var constraint = getBaseConstraintOfType(type) || anyType;
  52101. if (isTypeSubtypeOf(candidate, constraint)) {
  52102. return getIntersectionType([type, candidate]);
  52103. }
  52104. }
  52105. return type;
  52106. };
  52107. }
  52108. function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
  52109. var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
  52110. if (!switchWitnesses.length) {
  52111. return type;
  52112. }
  52113. // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
  52114. var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
  52115. var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
  52116. var clauseWitnesses;
  52117. var switchFacts;
  52118. if (defaultCaseLocation > -1) {
  52119. // We no longer need the undefined denoting an
  52120. // explicit default case. Remove the undefined and
  52121. // fix-up clauseStart and clauseEnd. This means
  52122. // that we don't have to worry about undefined
  52123. // in the witness array.
  52124. var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
  52125. // The adjusted clause start and end after removing the `default` statement.
  52126. var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
  52127. var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
  52128. clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
  52129. switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
  52130. }
  52131. else {
  52132. clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
  52133. switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
  52134. }
  52135. if (hasDefaultClause) {
  52136. return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
  52137. }
  52138. /*
  52139. The implied type is the raw type suggested by a
  52140. value being caught in this clause.
  52141. When the clause contains a default case we ignore
  52142. the implied type and try to narrow using any facts
  52143. we can learn: see `switchFacts`.
  52144. Example:
  52145. switch (typeof x) {
  52146. case 'number':
  52147. case 'string': break;
  52148. default: break;
  52149. case 'number':
  52150. case 'boolean': break
  52151. }
  52152. In the first clause (case `number` and `string`) the
  52153. implied type is number | string.
  52154. In the default clause we de not compute an implied type.
  52155. In the third clause (case `number` and `boolean`)
  52156. the naive implied type is number | boolean, however
  52157. we use the type facts to narrow the implied type to
  52158. boolean. We know that number cannot be selected
  52159. because it is caught in the first clause.
  52160. */
  52161. var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
  52162. if (impliedType.flags & 1048576 /* Union */) {
  52163. impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
  52164. }
  52165. return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
  52166. }
  52167. function narrowTypeByInstanceof(type, expr, assumeTrue) {
  52168. var left = getReferenceCandidate(expr.left);
  52169. if (!isMatchingReference(reference, left)) {
  52170. if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
  52171. return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
  52172. }
  52173. // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
  52174. // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
  52175. // references might reference a different 'y' property. However, we make an exception
  52176. // for property accesses where x is a synthetic 'this' expression, indicating that we
  52177. // were called from isPropertyInitializedInConstructor. Without this exception,
  52178. // initializations of 'this' properties that occur before a 'this instanceof XXX'
  52179. // check would not be considered.
  52180. if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
  52181. return declaredType;
  52182. }
  52183. return type;
  52184. }
  52185. // Check that right operand is a function type with a prototype property
  52186. var rightType = getTypeOfExpression(expr.right);
  52187. if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
  52188. return type;
  52189. }
  52190. var targetType;
  52191. var prototypeProperty = getPropertyOfType(rightType, "prototype");
  52192. if (prototypeProperty) {
  52193. // Target type is type of the prototype property
  52194. var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
  52195. if (!isTypeAny(prototypePropertyType)) {
  52196. targetType = prototypePropertyType;
  52197. }
  52198. }
  52199. // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
  52200. if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
  52201. return type;
  52202. }
  52203. if (!targetType) {
  52204. var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
  52205. targetType = constructSignatures.length ?
  52206. getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
  52207. emptyObjectType;
  52208. }
  52209. return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
  52210. }
  52211. function getNarrowedType(type, candidate, assumeTrue, isRelated) {
  52212. if (!assumeTrue) {
  52213. return filterType(type, function (t) { return !isRelated(t, candidate); });
  52214. }
  52215. // If the current type is a union type, remove all constituents that couldn't be instances of
  52216. // the candidate type. If one or more constituents remain, return a union of those.
  52217. if (type.flags & 1048576 /* Union */) {
  52218. var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
  52219. if (!(assignableType.flags & 131072 /* Never */)) {
  52220. return assignableType;
  52221. }
  52222. }
  52223. // If the candidate type is a subtype of the target type, narrow to the candidate type.
  52224. // Otherwise, if the target type is assignable to the candidate type, keep the target type.
  52225. // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
  52226. // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
  52227. // two types.
  52228. return isTypeSubtypeOf(candidate, type) ? candidate :
  52229. isTypeAssignableTo(type, candidate) ? type :
  52230. isTypeAssignableTo(candidate, type) ? candidate :
  52231. getIntersectionType([type, candidate]);
  52232. }
  52233. function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
  52234. if (hasMatchingArgument(callExpression, reference)) {
  52235. var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
  52236. var predicate = signature && getTypePredicateOfSignature(signature);
  52237. if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
  52238. return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
  52239. }
  52240. }
  52241. return type;
  52242. }
  52243. function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
  52244. // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
  52245. if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
  52246. var predicateArgument = getTypePredicateArgument(predicate, callExpression);
  52247. if (predicateArgument) {
  52248. if (isMatchingReference(reference, predicateArgument)) {
  52249. return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
  52250. }
  52251. if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
  52252. !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
  52253. return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
  52254. }
  52255. if (containsMatchingReference(reference, predicateArgument)) {
  52256. return declaredType;
  52257. }
  52258. }
  52259. }
  52260. return type;
  52261. }
  52262. // Narrow the given type based on the given expression having the assumed boolean value. The returned type
  52263. // will be a subtype or the same type as the argument.
  52264. function narrowType(type, expr, assumeTrue) {
  52265. // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
  52266. if (ts.isExpressionOfOptionalChainRoot(expr) ||
  52267. ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
  52268. return narrowTypeByOptionality(type, expr, assumeTrue);
  52269. }
  52270. switch (expr.kind) {
  52271. case 75 /* Identifier */:
  52272. case 104 /* ThisKeyword */:
  52273. case 102 /* SuperKeyword */:
  52274. case 194 /* PropertyAccessExpression */:
  52275. case 195 /* ElementAccessExpression */:
  52276. return narrowTypeByTruthiness(type, expr, assumeTrue);
  52277. case 196 /* CallExpression */:
  52278. return narrowTypeByCallExpression(type, expr, assumeTrue);
  52279. case 200 /* ParenthesizedExpression */:
  52280. return narrowType(type, expr.expression, assumeTrue);
  52281. case 209 /* BinaryExpression */:
  52282. return narrowTypeByBinaryExpression(type, expr, assumeTrue);
  52283. case 207 /* PrefixUnaryExpression */:
  52284. if (expr.operator === 53 /* ExclamationToken */) {
  52285. return narrowType(type, expr.operand, !assumeTrue);
  52286. }
  52287. break;
  52288. }
  52289. return type;
  52290. }
  52291. function narrowTypeByOptionality(type, expr, assumePresent) {
  52292. if (isMatchingReference(reference, expr)) {
  52293. return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
  52294. }
  52295. if (isMatchingReferenceDiscriminant(expr, declaredType)) {
  52296. return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
  52297. }
  52298. return type;
  52299. }
  52300. }
  52301. function getTypeOfSymbolAtLocation(symbol, location) {
  52302. symbol = symbol.exportSymbol || symbol;
  52303. // If we have an identifier or a property access at the given location, if the location is
  52304. // an dotted name expression, and if the location is not an assignment target, obtain the type
  52305. // of the expression (which will reflect control flow analysis). If the expression indeed
  52306. // resolved to the given symbol, return the narrowed type.
  52307. if (location.kind === 75 /* Identifier */) {
  52308. if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
  52309. location = location.parent;
  52310. }
  52311. if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
  52312. var type = getTypeOfExpression(location);
  52313. if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
  52314. return type;
  52315. }
  52316. }
  52317. }
  52318. // The location isn't a reference to the given symbol, meaning we're being asked
  52319. // a hypothetical question of what type the symbol would have if there was a reference
  52320. // to it at the given location. Since we have no control flow information for the
  52321. // hypothetical reference (control flow information is created and attached by the
  52322. // binder), we simply return the declared type of the symbol.
  52323. return getTypeOfSymbol(symbol);
  52324. }
  52325. function getControlFlowContainer(node) {
  52326. return ts.findAncestor(node.parent, function (node) {
  52327. return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
  52328. node.kind === 250 /* ModuleBlock */ ||
  52329. node.kind === 290 /* SourceFile */ ||
  52330. node.kind === 159 /* PropertyDeclaration */;
  52331. });
  52332. }
  52333. // Check if a parameter is assigned anywhere within its declaring function.
  52334. function isParameterAssigned(symbol) {
  52335. var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
  52336. var links = getNodeLinks(func);
  52337. if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
  52338. links.flags |= 8388608 /* AssignmentsMarked */;
  52339. if (!hasParentWithAssignmentsMarked(func)) {
  52340. markParameterAssignments(func);
  52341. }
  52342. }
  52343. return symbol.isAssigned || false;
  52344. }
  52345. function hasParentWithAssignmentsMarked(node) {
  52346. return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
  52347. }
  52348. function markParameterAssignments(node) {
  52349. if (node.kind === 75 /* Identifier */) {
  52350. if (ts.isAssignmentTarget(node)) {
  52351. var symbol = getResolvedSymbol(node);
  52352. if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
  52353. symbol.isAssigned = true;
  52354. }
  52355. }
  52356. }
  52357. else {
  52358. ts.forEachChild(node, markParameterAssignments);
  52359. }
  52360. }
  52361. function isConstVariable(symbol) {
  52362. return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
  52363. }
  52364. /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
  52365. function removeOptionalityFromDeclaredType(declaredType, declaration) {
  52366. var annotationIncludesUndefined = strictNullChecks &&
  52367. declaration.kind === 156 /* Parameter */ &&
  52368. declaration.initializer &&
  52369. getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
  52370. !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
  52371. return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
  52372. }
  52373. function isConstraintPosition(node) {
  52374. var parent = node.parent;
  52375. return parent.kind === 194 /* PropertyAccessExpression */ ||
  52376. parent.kind === 196 /* CallExpression */ && parent.expression === node ||
  52377. parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
  52378. parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
  52379. }
  52380. function typeHasNullableConstraint(type) {
  52381. return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
  52382. }
  52383. function getConstraintForLocation(type, node) {
  52384. // When a node is the left hand expression of a property access, element access, or call expression,
  52385. // and the type of the node includes type variables with constraints that are nullable, we fetch the
  52386. // apparent type of the node *before* performing control flow analysis such that narrowings apply to
  52387. // the constraint type.
  52388. if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
  52389. return mapType(getWidenedType(type), getBaseConstraintOrType);
  52390. }
  52391. return type;
  52392. }
  52393. function isExportOrExportExpression(location) {
  52394. return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
  52395. }
  52396. function markAliasReferenced(symbol, location) {
  52397. if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
  52398. if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
  52399. markAliasSymbolAsReferenced(symbol);
  52400. }
  52401. else {
  52402. markConstEnumAliasAsReferenced(symbol);
  52403. }
  52404. }
  52405. }
  52406. function checkIdentifier(node) {
  52407. var symbol = getResolvedSymbol(node);
  52408. if (symbol === unknownSymbol) {
  52409. return errorType;
  52410. }
  52411. // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
  52412. // Although in down-level emit of arrow function, we emit it using function expression which means that
  52413. // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
  52414. // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
  52415. // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
  52416. // can explicitly bound arguments objects
  52417. if (symbol === argumentsSymbol) {
  52418. var container = ts.getContainingFunction(node);
  52419. if (languageVersion < 2 /* ES2015 */) {
  52420. if (container.kind === 202 /* ArrowFunction */) {
  52421. error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
  52422. }
  52423. else if (ts.hasModifier(container, 256 /* Async */)) {
  52424. error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method);
  52425. }
  52426. }
  52427. getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
  52428. return getTypeOfSymbol(symbol);
  52429. }
  52430. // We should only mark aliases as referenced if there isn't a local value declaration
  52431. // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
  52432. if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
  52433. markAliasReferenced(symbol, node);
  52434. }
  52435. var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
  52436. var declaration = localOrExportSymbol.valueDeclaration;
  52437. if (localOrExportSymbol.flags & 32 /* Class */) {
  52438. // Due to the emit for class decorators, any reference to the class from inside of the class body
  52439. // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
  52440. // behavior of class names in ES6.
  52441. if (declaration.kind === 245 /* ClassDeclaration */
  52442. && ts.nodeIsDecorated(declaration)) {
  52443. var container = ts.getContainingClass(node);
  52444. while (container !== undefined) {
  52445. if (container === declaration && container.name !== node) {
  52446. getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
  52447. getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
  52448. break;
  52449. }
  52450. container = ts.getContainingClass(container);
  52451. }
  52452. }
  52453. else if (declaration.kind === 214 /* ClassExpression */) {
  52454. // When we emit a class expression with static members that contain a reference
  52455. // to the constructor in the initializer, we will need to substitute that
  52456. // binding with an alias as the class name is not in scope.
  52457. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
  52458. while (container.kind !== 290 /* SourceFile */) {
  52459. if (container.parent === declaration) {
  52460. if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
  52461. getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
  52462. getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
  52463. }
  52464. break;
  52465. }
  52466. container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
  52467. }
  52468. }
  52469. }
  52470. checkNestedBlockScopedBinding(node, symbol);
  52471. var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
  52472. var assignmentKind = ts.getAssignmentTargetKind(node);
  52473. if (assignmentKind) {
  52474. if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
  52475. !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
  52476. error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
  52477. return errorType;
  52478. }
  52479. if (isReadonlySymbol(localOrExportSymbol)) {
  52480. if (localOrExportSymbol.flags & 3 /* Variable */) {
  52481. error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
  52482. }
  52483. else {
  52484. error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
  52485. }
  52486. return errorType;
  52487. }
  52488. }
  52489. var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
  52490. // We only narrow variables and parameters occurring in a non-assignment position. For all other
  52491. // entities we simply return the declared type.
  52492. if (localOrExportSymbol.flags & 3 /* Variable */) {
  52493. if (assignmentKind === 1 /* Definite */) {
  52494. return type;
  52495. }
  52496. }
  52497. else if (isAlias) {
  52498. declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
  52499. }
  52500. else {
  52501. return type;
  52502. }
  52503. if (!declaration) {
  52504. return type;
  52505. }
  52506. // The declaration container is the innermost function that encloses the declaration of the variable
  52507. // or parameter. The flow container is the innermost function starting with which we analyze the control
  52508. // flow graph to determine the control flow based type.
  52509. var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
  52510. var declarationContainer = getControlFlowContainer(declaration);
  52511. var flowContainer = getControlFlowContainer(node);
  52512. var isOuterVariable = flowContainer !== declarationContainer;
  52513. var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
  52514. var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
  52515. // When the control flow originates in a function expression or arrow function and we are referencing
  52516. // a const variable or parameter from an outer function, we extend the origin of the control flow
  52517. // analysis to include the immediately enclosing function.
  52518. while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
  52519. flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
  52520. (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
  52521. flowContainer = getControlFlowContainer(flowContainer);
  52522. }
  52523. // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
  52524. // the entire control flow graph from the variable's declaration (i.e. when the flow container and
  52525. // declaration container are the same).
  52526. var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
  52527. type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
  52528. isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
  52529. node.parent.kind === 218 /* NonNullExpression */ ||
  52530. declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
  52531. declaration.flags & 8388608 /* Ambient */;
  52532. var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
  52533. type === autoType || type === autoArrayType ? undefinedType :
  52534. getOptionalType(type);
  52535. var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
  52536. // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
  52537. // from declaration to use, and when the variable's declared type doesn't include undefined but the
  52538. // control flow based type does include undefined.
  52539. if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
  52540. if (flowType === autoType || flowType === autoArrayType) {
  52541. if (noImplicitAny) {
  52542. error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
  52543. error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
  52544. }
  52545. return convertAutoToAny(flowType);
  52546. }
  52547. }
  52548. else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
  52549. error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
  52550. // Return the declared type to reduce follow-on errors
  52551. return type;
  52552. }
  52553. return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
  52554. }
  52555. function isInsideFunction(node, threshold) {
  52556. return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
  52557. }
  52558. function getPartOfForStatementContainingNode(node, container) {
  52559. return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
  52560. }
  52561. function checkNestedBlockScopedBinding(node, symbol) {
  52562. if (languageVersion >= 2 /* ES2015 */ ||
  52563. (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
  52564. ts.isSourceFile(symbol.valueDeclaration) ||
  52565. symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
  52566. return;
  52567. }
  52568. // 1. walk from the use site up to the declaration and check
  52569. // if there is anything function like between declaration and use-site (is binding/class is captured in function).
  52570. // 2. walk from the declaration up to the boundary of lexical environment and check
  52571. // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
  52572. var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
  52573. var usedInFunction = isInsideFunction(node.parent, container);
  52574. var current = container;
  52575. var containedInIterationStatement = false;
  52576. while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
  52577. if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
  52578. containedInIterationStatement = true;
  52579. break;
  52580. }
  52581. current = current.parent;
  52582. }
  52583. if (containedInIterationStatement) {
  52584. if (usedInFunction) {
  52585. // mark iteration statement as containing block-scoped binding captured in some function
  52586. var capturesBlockScopeBindingInLoopBody = true;
  52587. if (ts.isForStatement(container)) {
  52588. var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
  52589. if (varDeclList && varDeclList.parent === container) {
  52590. var part = getPartOfForStatementContainingNode(node.parent, container);
  52591. if (part) {
  52592. var links = getNodeLinks(part);
  52593. links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
  52594. var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
  52595. ts.pushIfUnique(capturedBindings, symbol);
  52596. if (part === container.initializer) {
  52597. capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
  52598. }
  52599. }
  52600. }
  52601. }
  52602. if (capturesBlockScopeBindingInLoopBody) {
  52603. getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
  52604. }
  52605. }
  52606. // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
  52607. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
  52608. if (ts.isForStatement(container)) {
  52609. var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
  52610. if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
  52611. getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
  52612. }
  52613. }
  52614. // set 'declared inside loop' bit on the block-scoped binding
  52615. getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
  52616. }
  52617. if (usedInFunction) {
  52618. getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
  52619. }
  52620. }
  52621. function isBindingCapturedByNode(node, decl) {
  52622. var links = getNodeLinks(node);
  52623. return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
  52624. }
  52625. function isAssignedInBodyOfForStatement(node, container) {
  52626. // skip parenthesized nodes
  52627. var current = node;
  52628. while (current.parent.kind === 200 /* ParenthesizedExpression */) {
  52629. current = current.parent;
  52630. }
  52631. // check if node is used as LHS in some assignment expression
  52632. var isAssigned = false;
  52633. if (ts.isAssignmentTarget(current)) {
  52634. isAssigned = true;
  52635. }
  52636. else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
  52637. var expr = current.parent;
  52638. isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
  52639. }
  52640. if (!isAssigned) {
  52641. return false;
  52642. }
  52643. // at this point we know that node is the target of assignment
  52644. // now check that modification happens inside the statement part of the ForStatement
  52645. return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
  52646. }
  52647. function captureLexicalThis(node, container) {
  52648. getNodeLinks(node).flags |= 2 /* LexicalThis */;
  52649. if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
  52650. var classNode = container.parent;
  52651. getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
  52652. }
  52653. else {
  52654. getNodeLinks(container).flags |= 4 /* CaptureThis */;
  52655. }
  52656. }
  52657. function findFirstSuperCall(n) {
  52658. if (ts.isSuperCall(n)) {
  52659. return n;
  52660. }
  52661. else if (ts.isFunctionLike(n)) {
  52662. return undefined;
  52663. }
  52664. return ts.forEachChild(n, findFirstSuperCall);
  52665. }
  52666. /**
  52667. * Return a cached result if super-statement is already found.
  52668. * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
  52669. *
  52670. * @param constructor constructor-function to look for super statement
  52671. */
  52672. function getSuperCallInConstructor(constructor) {
  52673. var links = getNodeLinks(constructor);
  52674. // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result
  52675. if (links.hasSuperCall === undefined) {
  52676. links.superCall = findFirstSuperCall(constructor.body);
  52677. links.hasSuperCall = links.superCall ? true : false;
  52678. }
  52679. return links.superCall;
  52680. }
  52681. /**
  52682. * Check if the given class-declaration extends null then return true.
  52683. * Otherwise, return false
  52684. * @param classDecl a class declaration to check if it extends null
  52685. */
  52686. function classDeclarationExtendsNull(classDecl) {
  52687. var classSymbol = getSymbolOfNode(classDecl);
  52688. var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
  52689. var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
  52690. return baseConstructorType === nullWideningType;
  52691. }
  52692. function checkThisBeforeSuper(node, container, diagnosticMessage) {
  52693. var containingClassDecl = container.parent;
  52694. var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
  52695. // If a containing class does not have extends clause or the class extends null
  52696. // skip checking whether super statement is called before "this" accessing.
  52697. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
  52698. var superCall = getSuperCallInConstructor(container);
  52699. // We should give an error in the following cases:
  52700. // - No super-call
  52701. // - "this" is accessing before super-call.
  52702. // i.e super(this)
  52703. // this.x; super();
  52704. // We want to make sure that super-call is done before accessing "this" so that
  52705. // "this" is not accessed as a parameter of the super-call.
  52706. if (!superCall || superCall.end > node.pos) {
  52707. // In ES6, super inside constructor of class-declaration has to precede "this" accessing
  52708. error(node, diagnosticMessage);
  52709. }
  52710. }
  52711. }
  52712. function checkThisExpression(node) {
  52713. // Stop at the first arrow function so that we can
  52714. // tell whether 'this' needs to be captured.
  52715. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
  52716. var capturedByArrowFunction = false;
  52717. if (container.kind === 162 /* Constructor */) {
  52718. checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
  52719. }
  52720. // Now skip arrow functions to get the "real" owner of 'this'.
  52721. if (container.kind === 202 /* ArrowFunction */) {
  52722. container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
  52723. capturedByArrowFunction = true;
  52724. }
  52725. switch (container.kind) {
  52726. case 249 /* ModuleDeclaration */:
  52727. error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
  52728. // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
  52729. break;
  52730. case 248 /* EnumDeclaration */:
  52731. error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
  52732. // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
  52733. break;
  52734. case 162 /* Constructor */:
  52735. if (isInConstructorArgumentInitializer(node, container)) {
  52736. error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
  52737. // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
  52738. }
  52739. break;
  52740. case 159 /* PropertyDeclaration */:
  52741. case 158 /* PropertySignature */:
  52742. if (ts.hasModifier(container, 32 /* Static */)) {
  52743. error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
  52744. // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
  52745. }
  52746. break;
  52747. case 154 /* ComputedPropertyName */:
  52748. error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
  52749. break;
  52750. }
  52751. // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
  52752. if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
  52753. captureLexicalThis(node, container);
  52754. }
  52755. var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
  52756. if (noImplicitThis) {
  52757. var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
  52758. if (type === globalThisType_1 && capturedByArrowFunction) {
  52759. error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
  52760. }
  52761. else if (!type) {
  52762. // With noImplicitThis, functions may not reference 'this' if it has type 'any'
  52763. var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
  52764. if (!ts.isSourceFile(container)) {
  52765. var outsideThis = tryGetThisTypeAt(container);
  52766. if (outsideThis && outsideThis !== globalThisType_1) {
  52767. ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
  52768. }
  52769. }
  52770. }
  52771. }
  52772. return type || anyType;
  52773. }
  52774. function tryGetThisTypeAt(node, includeGlobalThis, container) {
  52775. if (includeGlobalThis === void 0) { includeGlobalThis = true; }
  52776. if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
  52777. var isInJS = ts.isInJSFile(node);
  52778. if (ts.isFunctionLike(container) &&
  52779. (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
  52780. // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
  52781. // If this is a function in a JS file, it might be a class method.
  52782. var className = getClassNameFromPrototypeMethod(container);
  52783. if (isInJS && className) {
  52784. var classSymbol = checkExpression(className).symbol;
  52785. if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
  52786. var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
  52787. return getFlowTypeOfReference(node, classType);
  52788. }
  52789. }
  52790. // Check if it's a constructor definition, can be either a variable decl or function decl
  52791. // i.e.
  52792. // * /** @constructor */ function [name]() { ... }
  52793. // * /** @constructor */ var x = function() { ... }
  52794. else if (isInJS &&
  52795. (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
  52796. ts.getJSDocClassTag(container)) {
  52797. var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
  52798. return getFlowTypeOfReference(node, classType);
  52799. }
  52800. var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
  52801. if (thisType) {
  52802. return getFlowTypeOfReference(node, thisType);
  52803. }
  52804. }
  52805. if (ts.isClassLike(container.parent)) {
  52806. var symbol = getSymbolOfNode(container.parent);
  52807. var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
  52808. return getFlowTypeOfReference(node, type);
  52809. }
  52810. if (isInJS) {
  52811. var type = getTypeForThisExpressionFromJSDoc(container);
  52812. if (type && type !== errorType) {
  52813. return getFlowTypeOfReference(node, type);
  52814. }
  52815. }
  52816. if (ts.isSourceFile(container)) {
  52817. // look up in the source file's locals or exports
  52818. if (container.commonJsModuleIndicator) {
  52819. var fileSymbol = getSymbolOfNode(container);
  52820. return fileSymbol && getTypeOfSymbol(fileSymbol);
  52821. }
  52822. else if (includeGlobalThis) {
  52823. return getTypeOfSymbol(globalThisSymbol);
  52824. }
  52825. }
  52826. }
  52827. function getExplicitThisType(node) {
  52828. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
  52829. if (ts.isFunctionLike(container)) {
  52830. var signature = getSignatureFromDeclaration(container);
  52831. if (signature.thisParameter) {
  52832. return getExplicitTypeOfSymbol(signature.thisParameter);
  52833. }
  52834. }
  52835. if (ts.isClassLike(container.parent)) {
  52836. var symbol = getSymbolOfNode(container.parent);
  52837. return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
  52838. }
  52839. }
  52840. function getClassNameFromPrototypeMethod(container) {
  52841. // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
  52842. if (container.kind === 201 /* FunctionExpression */ &&
  52843. ts.isBinaryExpression(container.parent) &&
  52844. ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
  52845. // Get the 'x' of 'x.prototype.y = container'
  52846. return container.parent // x.prototype.y = container
  52847. .left // x.prototype.y
  52848. .expression // x.prototype
  52849. .expression; // x
  52850. }
  52851. // x.prototype = { method() { } }
  52852. else if (container.kind === 161 /* MethodDeclaration */ &&
  52853. container.parent.kind === 193 /* ObjectLiteralExpression */ &&
  52854. ts.isBinaryExpression(container.parent.parent) &&
  52855. ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
  52856. return container.parent.parent.left.expression;
  52857. }
  52858. // x.prototype = { method: function() { } }
  52859. else if (container.kind === 201 /* FunctionExpression */ &&
  52860. container.parent.kind === 281 /* PropertyAssignment */ &&
  52861. container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
  52862. ts.isBinaryExpression(container.parent.parent.parent) &&
  52863. ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
  52864. return container.parent.parent.parent.left.expression;
  52865. }
  52866. // Object.defineProperty(x, "method", { value: function() { } });
  52867. // Object.defineProperty(x, "method", { set: (x: () => void) => void });
  52868. // Object.defineProperty(x, "method", { get: () => function() { }) });
  52869. else if (container.kind === 201 /* FunctionExpression */ &&
  52870. ts.isPropertyAssignment(container.parent) &&
  52871. ts.isIdentifier(container.parent.name) &&
  52872. (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
  52873. ts.isObjectLiteralExpression(container.parent.parent) &&
  52874. ts.isCallExpression(container.parent.parent.parent) &&
  52875. container.parent.parent.parent.arguments[2] === container.parent.parent &&
  52876. ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
  52877. return container.parent.parent.parent.arguments[0].expression;
  52878. }
  52879. // Object.defineProperty(x, "method", { value() { } });
  52880. // Object.defineProperty(x, "method", { set(x: () => void) {} });
  52881. // Object.defineProperty(x, "method", { get() { return () => {} } });
  52882. else if (ts.isMethodDeclaration(container) &&
  52883. ts.isIdentifier(container.name) &&
  52884. (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
  52885. ts.isObjectLiteralExpression(container.parent) &&
  52886. ts.isCallExpression(container.parent.parent) &&
  52887. container.parent.parent.arguments[2] === container.parent &&
  52888. ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
  52889. return container.parent.parent.arguments[0].expression;
  52890. }
  52891. }
  52892. function getTypeForThisExpressionFromJSDoc(node) {
  52893. var jsdocType = ts.getJSDocType(node);
  52894. if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
  52895. var jsDocFunctionType = jsdocType;
  52896. if (jsDocFunctionType.parameters.length > 0 &&
  52897. jsDocFunctionType.parameters[0].name &&
  52898. jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
  52899. return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
  52900. }
  52901. }
  52902. var thisTag = ts.getJSDocThisTag(node);
  52903. if (thisTag && thisTag.typeExpression) {
  52904. return getTypeFromTypeNode(thisTag.typeExpression);
  52905. }
  52906. }
  52907. function isInConstructorArgumentInitializer(node, constructorDecl) {
  52908. return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
  52909. }
  52910. function checkSuperExpression(node) {
  52911. var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
  52912. var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
  52913. var needToCaptureLexicalThis = false;
  52914. // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
  52915. if (!isCallExpression) {
  52916. while (container && container.kind === 202 /* ArrowFunction */) {
  52917. container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
  52918. needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
  52919. }
  52920. }
  52921. var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
  52922. var nodeCheckFlag = 0;
  52923. if (!canUseSuperExpression) {
  52924. // issue more specific error if super is used in computed property name
  52925. // class A { foo() { return "1" }}
  52926. // class B {
  52927. // [super.foo()]() {}
  52928. // }
  52929. var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
  52930. if (current && current.kind === 154 /* ComputedPropertyName */) {
  52931. error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
  52932. }
  52933. else if (isCallExpression) {
  52934. error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
  52935. }
  52936. else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
  52937. error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
  52938. }
  52939. else {
  52940. error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
  52941. }
  52942. return errorType;
  52943. }
  52944. if (!isCallExpression && container.kind === 162 /* Constructor */) {
  52945. checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
  52946. }
  52947. if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
  52948. nodeCheckFlag = 512 /* SuperStatic */;
  52949. }
  52950. else {
  52951. nodeCheckFlag = 256 /* SuperInstance */;
  52952. }
  52953. getNodeLinks(node).flags |= nodeCheckFlag;
  52954. // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
  52955. // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
  52956. // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
  52957. // uses an arrow function, which is permitted to reference `super`.
  52958. //
  52959. // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
  52960. // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
  52961. // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
  52962. //
  52963. // The simplest case is reading a value, in which case we will emit something like the following:
  52964. //
  52965. // // ts
  52966. // ...
  52967. // async asyncMethod() {
  52968. // let x = await super.asyncMethod();
  52969. // return x;
  52970. // }
  52971. // ...
  52972. //
  52973. // // js
  52974. // ...
  52975. // asyncMethod() {
  52976. // const _super = Object.create(null, {
  52977. // asyncMethod: { get: () => super.asyncMethod },
  52978. // });
  52979. // return __awaiter(this, arguments, Promise, function *() {
  52980. // let x = yield _super.asyncMethod.call(this);
  52981. // return x;
  52982. // });
  52983. // }
  52984. // ...
  52985. //
  52986. // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
  52987. // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
  52988. //
  52989. // // ts
  52990. // ...
  52991. // async asyncMethod(ar: Promise<any[]>) {
  52992. // [super.a, super.b] = await ar;
  52993. // }
  52994. // ...
  52995. //
  52996. // // js
  52997. // ...
  52998. // asyncMethod(ar) {
  52999. // const _super = Object.create(null, {
  53000. // a: { get: () => super.a, set: (v) => super.a = v },
  53001. // b: { get: () => super.b, set: (v) => super.b = v }
  53002. // };
  53003. // return __awaiter(this, arguments, Promise, function *() {
  53004. // [_super.a, _super.b] = yield ar;
  53005. // });
  53006. // }
  53007. // ...
  53008. //
  53009. // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
  53010. // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
  53011. //
  53012. // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
  53013. if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
  53014. if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
  53015. getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
  53016. }
  53017. else {
  53018. getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
  53019. }
  53020. }
  53021. if (needToCaptureLexicalThis) {
  53022. // call expressions are allowed only in constructors so they should always capture correct 'this'
  53023. // super property access expressions can also appear in arrow functions -
  53024. // in this case they should also use correct lexical this
  53025. captureLexicalThis(node.parent, container);
  53026. }
  53027. if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
  53028. if (languageVersion < 2 /* ES2015 */) {
  53029. error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
  53030. return errorType;
  53031. }
  53032. else {
  53033. // for object literal assume that type of 'super' is 'any'
  53034. return anyType;
  53035. }
  53036. }
  53037. // at this point the only legal case for parent is ClassLikeDeclaration
  53038. var classLikeDeclaration = container.parent;
  53039. if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
  53040. error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
  53041. return errorType;
  53042. }
  53043. var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
  53044. var baseClassType = classType && getBaseTypes(classType)[0];
  53045. if (!baseClassType) {
  53046. return errorType;
  53047. }
  53048. if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
  53049. // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
  53050. error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
  53051. return errorType;
  53052. }
  53053. return nodeCheckFlag === 512 /* SuperStatic */
  53054. ? getBaseConstructorTypeOfClass(classType)
  53055. : getTypeWithThisArgument(baseClassType, classType.thisType);
  53056. function isLegalUsageOfSuperExpression(container) {
  53057. if (!container) {
  53058. return false;
  53059. }
  53060. if (isCallExpression) {
  53061. // TS 1.0 SPEC (April 2014): 4.8.1
  53062. // Super calls are only permitted in constructors of derived classes
  53063. return container.kind === 162 /* Constructor */;
  53064. }
  53065. else {
  53066. // TS 1.0 SPEC (April 2014)
  53067. // 'super' property access is allowed
  53068. // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
  53069. // - In a static member function or static member accessor
  53070. // topmost container must be something that is directly nested in the class declaration\object literal expression
  53071. if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
  53072. if (ts.hasModifier(container, 32 /* Static */)) {
  53073. return container.kind === 161 /* MethodDeclaration */ ||
  53074. container.kind === 160 /* MethodSignature */ ||
  53075. container.kind === 163 /* GetAccessor */ ||
  53076. container.kind === 164 /* SetAccessor */;
  53077. }
  53078. else {
  53079. return container.kind === 161 /* MethodDeclaration */ ||
  53080. container.kind === 160 /* MethodSignature */ ||
  53081. container.kind === 163 /* GetAccessor */ ||
  53082. container.kind === 164 /* SetAccessor */ ||
  53083. container.kind === 159 /* PropertyDeclaration */ ||
  53084. container.kind === 158 /* PropertySignature */ ||
  53085. container.kind === 162 /* Constructor */;
  53086. }
  53087. }
  53088. }
  53089. return false;
  53090. }
  53091. }
  53092. function getContainingObjectLiteral(func) {
  53093. return (func.kind === 161 /* MethodDeclaration */ ||
  53094. func.kind === 163 /* GetAccessor */ ||
  53095. func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
  53096. func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
  53097. undefined;
  53098. }
  53099. function getThisTypeArgument(type) {
  53100. return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
  53101. }
  53102. function getThisTypeFromContextualType(type) {
  53103. return mapType(type, function (t) {
  53104. return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
  53105. });
  53106. }
  53107. function getContextualThisParameterType(func) {
  53108. if (func.kind === 202 /* ArrowFunction */) {
  53109. return undefined;
  53110. }
  53111. if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
  53112. var contextualSignature = getContextualSignature(func);
  53113. if (contextualSignature) {
  53114. var thisParameter = contextualSignature.thisParameter;
  53115. if (thisParameter) {
  53116. return getTypeOfSymbol(thisParameter);
  53117. }
  53118. }
  53119. }
  53120. var inJs = ts.isInJSFile(func);
  53121. if (noImplicitThis || inJs) {
  53122. var containingLiteral = getContainingObjectLiteral(func);
  53123. if (containingLiteral) {
  53124. // We have an object literal method. Check if the containing object literal has a contextual type
  53125. // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
  53126. // any directly enclosing object literals.
  53127. var contextualType = getApparentTypeOfContextualType(containingLiteral);
  53128. var literal = containingLiteral;
  53129. var type = contextualType;
  53130. while (type) {
  53131. var thisType = getThisTypeFromContextualType(type);
  53132. if (thisType) {
  53133. return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
  53134. }
  53135. if (literal.parent.kind !== 281 /* PropertyAssignment */) {
  53136. break;
  53137. }
  53138. literal = literal.parent.parent;
  53139. type = getApparentTypeOfContextualType(literal);
  53140. }
  53141. // There was no contextual ThisType<T> for the containing object literal, so the contextual type
  53142. // for 'this' is the non-null form of the contextual type for the containing object literal or
  53143. // the type of the object literal itself.
  53144. return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
  53145. }
  53146. // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
  53147. // contextual type for 'this' is 'obj'.
  53148. var parent = ts.walkUpParenthesizedExpressions(func.parent);
  53149. if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
  53150. var target = parent.left;
  53151. if (ts.isAccessExpression(target)) {
  53152. var expression = target.expression;
  53153. // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
  53154. if (inJs && ts.isIdentifier(expression)) {
  53155. var sourceFile = ts.getSourceFileOfNode(parent);
  53156. if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
  53157. return undefined;
  53158. }
  53159. }
  53160. return getWidenedType(checkExpressionCached(expression));
  53161. }
  53162. }
  53163. }
  53164. return undefined;
  53165. }
  53166. // Return contextual type of parameter or undefined if no contextual type is available
  53167. function getContextuallyTypedParameterType(parameter) {
  53168. var func = parameter.parent;
  53169. if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
  53170. return undefined;
  53171. }
  53172. var iife = ts.getImmediatelyInvokedFunctionExpression(func);
  53173. if (iife && iife.arguments) {
  53174. var args = getEffectiveCallArguments(iife);
  53175. var indexOfParameter = func.parameters.indexOf(parameter);
  53176. if (parameter.dotDotDotToken) {
  53177. return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
  53178. }
  53179. var links = getNodeLinks(iife);
  53180. var cached = links.resolvedSignature;
  53181. links.resolvedSignature = anySignature;
  53182. var type = indexOfParameter < args.length ?
  53183. getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
  53184. parameter.initializer ? undefined : undefinedWideningType;
  53185. links.resolvedSignature = cached;
  53186. return type;
  53187. }
  53188. var contextualSignature = getContextualSignature(func);
  53189. if (contextualSignature) {
  53190. var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
  53191. return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
  53192. getRestTypeAtPosition(contextualSignature, index) :
  53193. tryGetTypeAtPosition(contextualSignature, index);
  53194. }
  53195. }
  53196. function getContextualTypeForVariableLikeDeclaration(declaration) {
  53197. var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
  53198. if (typeNode) {
  53199. return getTypeFromTypeNode(typeNode);
  53200. }
  53201. switch (declaration.kind) {
  53202. case 156 /* Parameter */:
  53203. return getContextuallyTypedParameterType(declaration);
  53204. case 191 /* BindingElement */:
  53205. return getContextualTypeForBindingElement(declaration);
  53206. // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
  53207. }
  53208. }
  53209. function getContextualTypeForBindingElement(declaration) {
  53210. var parent = declaration.parent.parent;
  53211. var name = declaration.propertyName || declaration.name;
  53212. var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
  53213. parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
  53214. if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) {
  53215. var nameType = getLiteralTypeFromPropertyName(name);
  53216. if (isTypeUsableAsPropertyName(nameType)) {
  53217. var text = getPropertyNameFromType(nameType);
  53218. return getTypeOfPropertyOfType(parentType, text);
  53219. }
  53220. }
  53221. }
  53222. // In a variable, parameter or property declaration with a type annotation,
  53223. // the contextual type of an initializer expression is the type of the variable, parameter or property.
  53224. // Otherwise, in a parameter declaration of a contextually typed function expression,
  53225. // the contextual type of an initializer expression is the contextual type of the parameter.
  53226. // Otherwise, in a variable or parameter declaration with a binding pattern name,
  53227. // the contextual type of an initializer expression is the type implied by the binding pattern.
  53228. // Otherwise, in a binding pattern inside a variable or parameter declaration,
  53229. // the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
  53230. function getContextualTypeForInitializerExpression(node) {
  53231. var declaration = node.parent;
  53232. if (ts.hasInitializer(declaration) && node === declaration.initializer) {
  53233. var result = getContextualTypeForVariableLikeDeclaration(declaration);
  53234. if (result) {
  53235. return result;
  53236. }
  53237. if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
  53238. return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
  53239. }
  53240. }
  53241. return undefined;
  53242. }
  53243. function getContextualTypeForReturnExpression(node) {
  53244. var func = ts.getContainingFunction(node);
  53245. if (func) {
  53246. var functionFlags = ts.getFunctionFlags(func);
  53247. if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
  53248. return undefined;
  53249. }
  53250. var contextualReturnType = getContextualReturnType(func);
  53251. if (contextualReturnType) {
  53252. if (functionFlags & 2 /* Async */) { // Async function
  53253. var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType);
  53254. return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
  53255. }
  53256. return contextualReturnType; // Regular function
  53257. }
  53258. }
  53259. return undefined;
  53260. }
  53261. function getContextualTypeForAwaitOperand(node) {
  53262. var contextualType = getContextualType(node);
  53263. if (contextualType) {
  53264. var contextualAwaitedType = getAwaitedType(contextualType);
  53265. return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
  53266. }
  53267. return undefined;
  53268. }
  53269. function getContextualTypeForYieldOperand(node) {
  53270. var func = ts.getContainingFunction(node);
  53271. if (func) {
  53272. var functionFlags = ts.getFunctionFlags(func);
  53273. var contextualReturnType = getContextualReturnType(func);
  53274. if (contextualReturnType) {
  53275. return node.asteriskToken
  53276. ? contextualReturnType
  53277. : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
  53278. }
  53279. }
  53280. return undefined;
  53281. }
  53282. function isInParameterInitializerBeforeContainingFunction(node) {
  53283. var inBindingInitializer = false;
  53284. while (node.parent && !ts.isFunctionLike(node.parent)) {
  53285. if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
  53286. return true;
  53287. }
  53288. if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
  53289. inBindingInitializer = true;
  53290. }
  53291. node = node.parent;
  53292. }
  53293. return false;
  53294. }
  53295. function getContextualIterationType(kind, functionDecl) {
  53296. var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
  53297. var contextualReturnType = getContextualReturnType(functionDecl);
  53298. if (contextualReturnType) {
  53299. return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
  53300. || undefined;
  53301. }
  53302. return undefined;
  53303. }
  53304. function getContextualReturnType(functionDecl) {
  53305. // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
  53306. // corresponding set accessor has a type annotation, return statements in the function are contextually typed
  53307. var returnType = getReturnTypeFromAnnotation(functionDecl);
  53308. if (returnType) {
  53309. return returnType;
  53310. }
  53311. // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
  53312. // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
  53313. var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
  53314. if (signature && !isResolvingReturnTypeOfSignature(signature)) {
  53315. return getReturnTypeOfSignature(signature);
  53316. }
  53317. return undefined;
  53318. }
  53319. // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
  53320. function getContextualTypeForArgument(callTarget, arg) {
  53321. var args = getEffectiveCallArguments(callTarget);
  53322. var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
  53323. return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
  53324. }
  53325. function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
  53326. // If we're already in the process of resolving the given signature, don't resolve again as
  53327. // that could cause infinite recursion. Instead, return anySignature.
  53328. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
  53329. if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
  53330. return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
  53331. }
  53332. return getTypeAtPosition(signature, argIndex);
  53333. }
  53334. function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
  53335. if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
  53336. return getContextualTypeForArgument(template.parent, substitutionExpression);
  53337. }
  53338. return undefined;
  53339. }
  53340. function getContextualTypeForBinaryOperand(node, contextFlags) {
  53341. var binaryExpression = node.parent;
  53342. var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
  53343. switch (operatorToken.kind) {
  53344. case 62 /* EqualsToken */:
  53345. if (node !== right) {
  53346. return undefined;
  53347. }
  53348. var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
  53349. if (!contextSensitive) {
  53350. return undefined;
  53351. }
  53352. return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
  53353. case 56 /* BarBarToken */:
  53354. case 60 /* QuestionQuestionToken */:
  53355. // When an || expression has a contextual type, the operands are contextually typed by that type, except
  53356. // when that type originates in a binding pattern, the right operand is contextually typed by the type of
  53357. // the left operand. When an || expression has no contextual type, the right operand is contextually typed
  53358. // by the type of the left operand, except for the special case of Javascript declarations of the form
  53359. // `namespace.prop = namespace.prop || {}`.
  53360. var type = getContextualType(binaryExpression, contextFlags);
  53361. return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
  53362. getTypeOfExpression(left) : type;
  53363. case 55 /* AmpersandAmpersandToken */:
  53364. case 27 /* CommaToken */:
  53365. return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
  53366. default:
  53367. return undefined;
  53368. }
  53369. }
  53370. // In an assignment expression, the right operand is contextually typed by the type of the left operand.
  53371. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
  53372. function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
  53373. var kind = ts.getAssignmentDeclarationKind(binaryExpression);
  53374. switch (kind) {
  53375. case 0 /* None */:
  53376. return true;
  53377. case 5 /* Property */:
  53378. case 1 /* ExportsProperty */:
  53379. case 6 /* Prototype */:
  53380. case 3 /* PrototypeProperty */:
  53381. // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
  53382. // See `bindStaticPropertyAssignment` in `binder.ts`.
  53383. if (!binaryExpression.left.symbol) {
  53384. return true;
  53385. }
  53386. else {
  53387. var decl = binaryExpression.left.symbol.valueDeclaration;
  53388. if (!decl) {
  53389. return false;
  53390. }
  53391. var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
  53392. var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
  53393. if (overallAnnotation) {
  53394. return getTypeFromTypeNode(overallAnnotation);
  53395. }
  53396. else if (ts.isIdentifier(lhs.expression)) {
  53397. var id = lhs.expression;
  53398. var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
  53399. if (parentSymbol) {
  53400. var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
  53401. if (annotated) {
  53402. var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
  53403. if (nameStr_1 !== undefined) {
  53404. var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
  53405. return type || false;
  53406. }
  53407. }
  53408. return false;
  53409. }
  53410. }
  53411. return !ts.isInJSFile(decl);
  53412. }
  53413. case 2 /* ModuleExports */:
  53414. case 4 /* ThisProperty */:
  53415. if (!binaryExpression.symbol)
  53416. return true;
  53417. if (binaryExpression.symbol.valueDeclaration) {
  53418. var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
  53419. if (annotated) {
  53420. var type = getTypeFromTypeNode(annotated);
  53421. if (type) {
  53422. return type;
  53423. }
  53424. }
  53425. }
  53426. if (kind === 2 /* ModuleExports */)
  53427. return false;
  53428. var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
  53429. if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
  53430. return false;
  53431. }
  53432. var thisType = checkThisExpression(thisAccess.expression);
  53433. var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
  53434. return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
  53435. case 7 /* ObjectDefinePropertyValue */:
  53436. case 8 /* ObjectDefinePropertyExports */:
  53437. case 9 /* ObjectDefinePrototypeProperty */:
  53438. return ts.Debug.fail("Does not apply");
  53439. default:
  53440. return ts.Debug.assertNever(kind);
  53441. }
  53442. }
  53443. function getTypeOfPropertyOfContextualType(type, name) {
  53444. return mapType(type, function (t) {
  53445. if (isGenericMappedType(t)) {
  53446. var constraint = getConstraintTypeFromMappedType(t);
  53447. var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
  53448. var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
  53449. if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
  53450. return substituteIndexedMappedType(t, propertyNameType);
  53451. }
  53452. }
  53453. else if (t.flags & 3670016 /* StructuredType */) {
  53454. var prop = getPropertyOfType(t, name);
  53455. if (prop) {
  53456. return getTypeOfSymbol(prop);
  53457. }
  53458. if (isTupleType(t)) {
  53459. var restType = getRestTypeOfTupleType(t);
  53460. if (restType && isNumericLiteralName(name) && +name >= 0) {
  53461. return restType;
  53462. }
  53463. }
  53464. return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
  53465. getIndexTypeOfContextualType(t, 0 /* String */);
  53466. }
  53467. return undefined;
  53468. }, /*noReductions*/ true);
  53469. }
  53470. function getIndexTypeOfContextualType(type, kind) {
  53471. return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
  53472. }
  53473. // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
  53474. // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
  53475. // exists. Otherwise, it is the type of the string index signature in T, if one exists.
  53476. function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
  53477. ts.Debug.assert(ts.isObjectLiteralMethod(node));
  53478. if (node.flags & 16777216 /* InWithStatement */) {
  53479. // We cannot answer semantic questions within a with block, do not proceed any further
  53480. return undefined;
  53481. }
  53482. return getContextualTypeForObjectLiteralElement(node, contextFlags);
  53483. }
  53484. function getContextualTypeForObjectLiteralElement(element, contextFlags) {
  53485. var objectLiteral = element.parent;
  53486. var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
  53487. if (type) {
  53488. if (!hasNonBindableDynamicName(element)) {
  53489. // For a (non-symbol) computed property, there is no reason to look up the name
  53490. // in the type. It will just be "__computed", which does not appear in any
  53491. // SymbolTable.
  53492. var symbolName_3 = getSymbolOfNode(element).escapedName;
  53493. var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
  53494. if (propertyType) {
  53495. return propertyType;
  53496. }
  53497. }
  53498. return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
  53499. getIndexTypeOfContextualType(type, 0 /* String */);
  53500. }
  53501. return undefined;
  53502. }
  53503. // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
  53504. // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
  53505. // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
  53506. // type of T.
  53507. function getContextualTypeForElementExpression(arrayContextualType, index) {
  53508. return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
  53509. || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
  53510. }
  53511. // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
  53512. function getContextualTypeForConditionalOperand(node, contextFlags) {
  53513. var conditional = node.parent;
  53514. return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
  53515. }
  53516. function getContextualTypeForChildJsxExpression(node, child) {
  53517. var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
  53518. // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
  53519. var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
  53520. if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
  53521. return undefined;
  53522. }
  53523. var realChildren = getSemanticJsxChildren(node.children);
  53524. var childIndex = realChildren.indexOf(child);
  53525. var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
  53526. return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
  53527. if (isArrayLikeType(t)) {
  53528. return getIndexedAccessType(t, getLiteralType(childIndex));
  53529. }
  53530. else {
  53531. return t;
  53532. }
  53533. }, /*noReductions*/ true));
  53534. }
  53535. function getContextualTypeForJsxExpression(node) {
  53536. var exprParent = node.parent;
  53537. return ts.isJsxAttributeLike(exprParent)
  53538. ? getContextualType(node)
  53539. : ts.isJsxElement(exprParent)
  53540. ? getContextualTypeForChildJsxExpression(exprParent, node)
  53541. : undefined;
  53542. }
  53543. function getContextualTypeForJsxAttribute(attribute) {
  53544. // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
  53545. // which is a type of the parameter of the signature we are trying out.
  53546. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
  53547. if (ts.isJsxAttribute(attribute)) {
  53548. var attributesType = getApparentTypeOfContextualType(attribute.parent);
  53549. if (!attributesType || isTypeAny(attributesType)) {
  53550. return undefined;
  53551. }
  53552. return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
  53553. }
  53554. else {
  53555. return getContextualType(attribute.parent);
  53556. }
  53557. }
  53558. // Return true if the given expression is possibly a discriminant value. We limit the kinds of
  53559. // expressions we check to those that don't depend on their contextual type in order not to cause
  53560. // recursive (and possibly infinite) invocations of getContextualType.
  53561. function isPossiblyDiscriminantValue(node) {
  53562. switch (node.kind) {
  53563. case 10 /* StringLiteral */:
  53564. case 8 /* NumericLiteral */:
  53565. case 9 /* BigIntLiteral */:
  53566. case 14 /* NoSubstitutionTemplateLiteral */:
  53567. case 106 /* TrueKeyword */:
  53568. case 91 /* FalseKeyword */:
  53569. case 100 /* NullKeyword */:
  53570. case 75 /* Identifier */:
  53571. case 146 /* UndefinedKeyword */:
  53572. return true;
  53573. case 194 /* PropertyAccessExpression */:
  53574. case 200 /* ParenthesizedExpression */:
  53575. return isPossiblyDiscriminantValue(node.expression);
  53576. case 276 /* JsxExpression */:
  53577. return !node.expression || isPossiblyDiscriminantValue(node.expression);
  53578. }
  53579. return false;
  53580. }
  53581. function discriminateContextualTypeByObjectMembers(node, contextualType) {
  53582. return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
  53583. }
  53584. function discriminateContextualTypeByJSXAttributes(node, contextualType) {
  53585. return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
  53586. }
  53587. // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
  53588. // be "pushed" onto a node using the contextualType property.
  53589. function getApparentTypeOfContextualType(node, contextFlags) {
  53590. var contextualType = ts.isObjectLiteralMethod(node) ?
  53591. getContextualTypeForObjectLiteralMethod(node, contextFlags) :
  53592. getContextualType(node, contextFlags);
  53593. var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
  53594. if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
  53595. var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
  53596. if (apparentType.flags & 1048576 /* Union */) {
  53597. if (ts.isObjectLiteralExpression(node)) {
  53598. return discriminateContextualTypeByObjectMembers(node, apparentType);
  53599. }
  53600. else if (ts.isJsxAttributes(node)) {
  53601. return discriminateContextualTypeByJSXAttributes(node, apparentType);
  53602. }
  53603. }
  53604. return apparentType;
  53605. }
  53606. }
  53607. // If the given contextual type contains instantiable types and if a mapper representing
  53608. // return type inferences is available, instantiate those types using that mapper.
  53609. function instantiateContextualType(contextualType, node, contextFlags) {
  53610. if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
  53611. var inferenceContext = getInferenceContext(node);
  53612. // If no inferences have been made, nothing is gained from instantiating as type parameters
  53613. // would just be replaced with their defaults similar to the apparent type.
  53614. if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
  53615. // For contextual signatures we incorporate all inferences made so far, e.g. from return
  53616. // types as well as arguments to the left in a function call.
  53617. if (contextFlags && contextFlags & 1 /* Signature */) {
  53618. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
  53619. }
  53620. // For other purposes (e.g. determining whether to produce literal types) we only
  53621. // incorporate inferences made from the return type in a function call.
  53622. if (inferenceContext.returnMapper) {
  53623. return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
  53624. }
  53625. }
  53626. }
  53627. return contextualType;
  53628. }
  53629. // This function is similar to instantiateType, except that (a) it only instantiates types that
  53630. // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
  53631. // no reductions on instantiated union types.
  53632. function instantiateInstantiableTypes(type, mapper) {
  53633. if (type.flags & 63176704 /* Instantiable */) {
  53634. return instantiateType(type, mapper);
  53635. }
  53636. if (type.flags & 1048576 /* Union */) {
  53637. return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
  53638. }
  53639. if (type.flags & 2097152 /* Intersection */) {
  53640. return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
  53641. }
  53642. return type;
  53643. }
  53644. /**
  53645. * Whoa! Do you really want to use this function?
  53646. *
  53647. * Unless you're trying to get the *non-apparent* type for a
  53648. * value-literal type or you're authoring relevant portions of this algorithm,
  53649. * you probably meant to use 'getApparentTypeOfContextualType'.
  53650. * Otherwise this may not be very useful.
  53651. *
  53652. * In cases where you *are* working on this function, you should understand
  53653. * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
  53654. *
  53655. * - Use 'getContextualType' when you are simply going to propagate the result to the expression.
  53656. * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
  53657. *
  53658. * @param node the expression whose contextual type will be returned.
  53659. * @returns the contextual type of an expression.
  53660. */
  53661. function getContextualType(node, contextFlags) {
  53662. if (node.flags & 16777216 /* InWithStatement */) {
  53663. // We cannot answer semantic questions within a with block, do not proceed any further
  53664. return undefined;
  53665. }
  53666. if (node.contextualType) {
  53667. return node.contextualType;
  53668. }
  53669. var parent = node.parent;
  53670. switch (parent.kind) {
  53671. case 242 /* VariableDeclaration */:
  53672. case 156 /* Parameter */:
  53673. case 159 /* PropertyDeclaration */:
  53674. case 158 /* PropertySignature */:
  53675. case 191 /* BindingElement */:
  53676. return getContextualTypeForInitializerExpression(node);
  53677. case 202 /* ArrowFunction */:
  53678. case 235 /* ReturnStatement */:
  53679. return getContextualTypeForReturnExpression(node);
  53680. case 212 /* YieldExpression */:
  53681. return getContextualTypeForYieldOperand(parent);
  53682. case 206 /* AwaitExpression */:
  53683. return getContextualTypeForAwaitOperand(parent);
  53684. case 196 /* CallExpression */:
  53685. if (parent.expression.kind === 96 /* ImportKeyword */) {
  53686. return stringType;
  53687. }
  53688. /* falls through */
  53689. case 197 /* NewExpression */:
  53690. return getContextualTypeForArgument(parent, node);
  53691. case 199 /* TypeAssertionExpression */:
  53692. case 217 /* AsExpression */:
  53693. return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
  53694. case 209 /* BinaryExpression */:
  53695. return getContextualTypeForBinaryOperand(node, contextFlags);
  53696. case 281 /* PropertyAssignment */:
  53697. case 282 /* ShorthandPropertyAssignment */:
  53698. return getContextualTypeForObjectLiteralElement(parent, contextFlags);
  53699. case 283 /* SpreadAssignment */:
  53700. return getApparentTypeOfContextualType(parent.parent, contextFlags);
  53701. case 192 /* ArrayLiteralExpression */: {
  53702. var arrayLiteral = parent;
  53703. var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
  53704. return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
  53705. }
  53706. case 210 /* ConditionalExpression */:
  53707. return getContextualTypeForConditionalOperand(node, contextFlags);
  53708. case 221 /* TemplateSpan */:
  53709. ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
  53710. return getContextualTypeForSubstitutionExpression(parent.parent, node);
  53711. case 200 /* ParenthesizedExpression */: {
  53712. // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
  53713. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
  53714. return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
  53715. }
  53716. case 276 /* JsxExpression */:
  53717. return getContextualTypeForJsxExpression(parent);
  53718. case 273 /* JsxAttribute */:
  53719. case 275 /* JsxSpreadAttribute */:
  53720. return getContextualTypeForJsxAttribute(parent);
  53721. case 268 /* JsxOpeningElement */:
  53722. case 267 /* JsxSelfClosingElement */:
  53723. return getContextualJsxElementAttributesType(parent, contextFlags);
  53724. }
  53725. return undefined;
  53726. }
  53727. function getInferenceContext(node) {
  53728. var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
  53729. return ancestor && ancestor.inferenceContext;
  53730. }
  53731. function getContextualJsxElementAttributesType(node, contextFlags) {
  53732. if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
  53733. // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
  53734. // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
  53735. // (as below) instead!
  53736. return node.parent.contextualType;
  53737. }
  53738. return getContextualTypeForArgumentAtIndex(node, 0);
  53739. }
  53740. function getEffectiveFirstArgumentForJsxSignature(signature, node) {
  53741. return getJsxReferenceKind(node) !== 0 /* Component */
  53742. ? getJsxPropsTypeFromCallSignature(signature, node)
  53743. : getJsxPropsTypeFromClassType(signature, node);
  53744. }
  53745. function getJsxPropsTypeFromCallSignature(sig, context) {
  53746. var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
  53747. propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
  53748. var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
  53749. if (intrinsicAttribs !== errorType) {
  53750. propsType = intersectTypes(intrinsicAttribs, propsType);
  53751. }
  53752. return propsType;
  53753. }
  53754. function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
  53755. if (sig.unionSignatures) {
  53756. // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
  53757. // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
  53758. // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
  53759. // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input.
  53760. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
  53761. var results = [];
  53762. for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
  53763. var signature = _a[_i];
  53764. var instance = getReturnTypeOfSignature(signature);
  53765. if (isTypeAny(instance)) {
  53766. return instance;
  53767. }
  53768. var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
  53769. if (!propType) {
  53770. return;
  53771. }
  53772. results.push(propType);
  53773. }
  53774. return getIntersectionType(results);
  53775. }
  53776. var instanceType = getReturnTypeOfSignature(sig);
  53777. return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
  53778. }
  53779. function getStaticTypeOfReferencedJsxConstructor(context) {
  53780. if (isJsxIntrinsicIdentifier(context.tagName)) {
  53781. var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
  53782. var fakeSignature = createSignatureForJSXIntrinsic(context, result);
  53783. return getOrCreateTypeFromSignature(fakeSignature);
  53784. }
  53785. var tagType = checkExpressionCached(context.tagName);
  53786. if (tagType.flags & 128 /* StringLiteral */) {
  53787. var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
  53788. if (!result) {
  53789. return errorType;
  53790. }
  53791. var fakeSignature = createSignatureForJSXIntrinsic(context, result);
  53792. return getOrCreateTypeFromSignature(fakeSignature);
  53793. }
  53794. return tagType;
  53795. }
  53796. function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
  53797. var managedSym = getJsxLibraryManagedAttributes(ns);
  53798. if (managedSym) {
  53799. var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
  53800. var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
  53801. if (ts.length(declaredManagedType.typeParameters) >= 2) {
  53802. var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
  53803. return createTypeReference(declaredManagedType, args);
  53804. }
  53805. else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
  53806. var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
  53807. return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
  53808. }
  53809. }
  53810. return attributesType;
  53811. }
  53812. function getJsxPropsTypeFromClassType(sig, context) {
  53813. var ns = getJsxNamespaceAt(context);
  53814. var forcedLookupLocation = getJsxElementPropertiesName(ns);
  53815. var attributesType = forcedLookupLocation === undefined
  53816. // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
  53817. ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
  53818. : forcedLookupLocation === ""
  53819. // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
  53820. ? getReturnTypeOfSignature(sig)
  53821. // Otherwise get the type of the property on the signature return type
  53822. : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
  53823. if (!attributesType) {
  53824. // There is no property named 'props' on this instance type
  53825. if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
  53826. error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
  53827. }
  53828. return unknownType;
  53829. }
  53830. attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
  53831. if (isTypeAny(attributesType)) {
  53832. // Props is of type 'any' or unknown
  53833. return attributesType;
  53834. }
  53835. else {
  53836. // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
  53837. var apparentAttributesType = attributesType;
  53838. var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
  53839. if (intrinsicClassAttribs !== errorType) {
  53840. var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
  53841. var hostClassType = getReturnTypeOfSignature(sig);
  53842. apparentAttributesType = intersectTypes(typeParams
  53843. ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
  53844. : intrinsicClassAttribs, apparentAttributesType);
  53845. }
  53846. var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
  53847. if (intrinsicAttribs !== errorType) {
  53848. apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
  53849. }
  53850. return apparentAttributesType;
  53851. }
  53852. }
  53853. // If the given type is an object or union type with a single signature, and if that signature has at
  53854. // least as many parameters as the given function, return the signature. Otherwise return undefined.
  53855. function getContextualCallSignature(type, node) {
  53856. var signatures = getSignaturesOfType(type, 0 /* Call */);
  53857. if (signatures.length === 1) {
  53858. var signature = signatures[0];
  53859. if (!isAritySmaller(signature, node)) {
  53860. return signature;
  53861. }
  53862. }
  53863. }
  53864. /** If the contextual signature has fewer parameters than the function expression, do not use it */
  53865. function isAritySmaller(signature, target) {
  53866. var targetParameterCount = 0;
  53867. for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
  53868. var param = target.parameters[targetParameterCount];
  53869. if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
  53870. break;
  53871. }
  53872. }
  53873. if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
  53874. targetParameterCount--;
  53875. }
  53876. return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
  53877. }
  53878. function isFunctionExpressionOrArrowFunction(node) {
  53879. return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
  53880. }
  53881. function getContextualSignatureForFunctionLikeDeclaration(node) {
  53882. // Only function expressions, arrow functions, and object literal methods are contextually typed.
  53883. return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
  53884. ? getContextualSignature(node)
  53885. : undefined;
  53886. }
  53887. // Return the contextual signature for a given expression node. A contextual type provides a
  53888. // contextual signature if it has a single call signature and if that call signature is non-generic.
  53889. // If the contextual type is a union type, get the signature from each type possible and if they are
  53890. // all identical ignoring their return type, the result is same signature but with return type as
  53891. // union type of return types from these signatures
  53892. function getContextualSignature(node) {
  53893. ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
  53894. var typeTagSignature = getSignatureOfTypeTag(node);
  53895. if (typeTagSignature) {
  53896. return typeTagSignature;
  53897. }
  53898. var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
  53899. if (!type) {
  53900. return undefined;
  53901. }
  53902. if (!(type.flags & 1048576 /* Union */)) {
  53903. return getContextualCallSignature(type, node);
  53904. }
  53905. var signatureList;
  53906. var types = type.types;
  53907. for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
  53908. var current = types_16[_i];
  53909. var signature = getContextualCallSignature(current, node);
  53910. if (signature) {
  53911. if (!signatureList) {
  53912. // This signature will contribute to contextual union signature
  53913. signatureList = [signature];
  53914. }
  53915. else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
  53916. // Signatures aren't identical, do not use
  53917. return undefined;
  53918. }
  53919. else {
  53920. // Use this signature for contextual union signature
  53921. signatureList.push(signature);
  53922. }
  53923. }
  53924. }
  53925. // Result is union of signatures collected (return type is union of return types of this signature set)
  53926. if (signatureList) {
  53927. return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
  53928. }
  53929. }
  53930. function checkSpreadExpression(node, checkMode) {
  53931. if (languageVersion < 2 /* ES2015 */) {
  53932. checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
  53933. }
  53934. var arrayOrIterableType = checkExpression(node.expression, checkMode);
  53935. return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
  53936. }
  53937. function hasDefaultValue(node) {
  53938. return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
  53939. (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
  53940. }
  53941. function checkArrayLiteral(node, checkMode, forceTuple) {
  53942. var elements = node.elements;
  53943. var elementCount = elements.length;
  53944. var hasNonEndingSpreadElement = false;
  53945. var elementTypes = [];
  53946. var inDestructuringPattern = ts.isAssignmentTarget(node);
  53947. var contextualType = getApparentTypeOfContextualType(node);
  53948. var inConstContext = isConstContext(node);
  53949. for (var index = 0; index < elementCount; index++) {
  53950. var e = elements[index];
  53951. if (inDestructuringPattern && e.kind === 213 /* SpreadElement */) {
  53952. // Given the following situation:
  53953. // var c: {};
  53954. // [...c] = ["", 0];
  53955. //
  53956. // c is represented in the tree as a spread element in an array literal.
  53957. // But c really functions as a rest element, and its purpose is to provide
  53958. // a contextual type for the right hand side of the assignment. Therefore,
  53959. // instead of calling checkExpression on "...c", which will give an error
  53960. // if c is not iterable/array-like, we need to act as if we are trying to
  53961. // get the contextual element type from it. So we do something similar to
  53962. // getContextualTypeForElementExpression, which will crucially not error
  53963. // if there is no index type / iterated type.
  53964. var restArrayType = checkExpression(e.expression, checkMode, forceTuple);
  53965. var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) ||
  53966. getIteratedTypeOrElementType(65 /* Destructuring */, restArrayType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
  53967. if (restElementType) {
  53968. elementTypes.push(restElementType);
  53969. }
  53970. }
  53971. else {
  53972. var elementContextualType = getContextualTypeForElementExpression(contextualType, index);
  53973. var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
  53974. elementTypes.push(type);
  53975. }
  53976. if (index < elementCount - 1 && e.kind === 213 /* SpreadElement */) {
  53977. hasNonEndingSpreadElement = true;
  53978. }
  53979. }
  53980. if (!hasNonEndingSpreadElement) {
  53981. var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 213 /* SpreadElement */;
  53982. var minLength = elementCount - (hasRestElement ? 1 : 0);
  53983. // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
  53984. // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
  53985. var tupleResult = void 0;
  53986. if (inDestructuringPattern && minLength > 0) {
  53987. var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement));
  53988. type.pattern = node;
  53989. return type;
  53990. }
  53991. else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
  53992. return createArrayLiteralType(tupleResult);
  53993. }
  53994. else if (forceTuple) {
  53995. return createArrayLiteralType(createTupleType(elementTypes, minLength, hasRestElement));
  53996. }
  53997. }
  53998. return createArrayLiteralType(createArrayType(elementTypes.length ?
  53999. getUnionType(elementTypes, 2 /* Subtype */) :
  54000. strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
  54001. }
  54002. function createArrayLiteralType(type) {
  54003. if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
  54004. return type;
  54005. }
  54006. var literalType = type.literalType;
  54007. if (!literalType) {
  54008. literalType = type.literalType = cloneTypeReference(type);
  54009. literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
  54010. }
  54011. return literalType;
  54012. }
  54013. function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
  54014. if (elementCount === void 0) { elementCount = elementTypes.length; }
  54015. if (readonly === void 0) { readonly = false; }
  54016. // Infer a tuple type when the contextual type is or contains a tuple-like type
  54017. if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
  54018. return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
  54019. }
  54020. }
  54021. function isNumericName(name) {
  54022. switch (name.kind) {
  54023. case 154 /* ComputedPropertyName */:
  54024. return isNumericComputedName(name);
  54025. case 75 /* Identifier */:
  54026. return isNumericLiteralName(name.escapedText);
  54027. case 8 /* NumericLiteral */:
  54028. case 10 /* StringLiteral */:
  54029. return isNumericLiteralName(name.text);
  54030. default:
  54031. return false;
  54032. }
  54033. }
  54034. function isNumericComputedName(name) {
  54035. // It seems odd to consider an expression of type Any to result in a numeric name,
  54036. // but this behavior is consistent with checkIndexedAccess
  54037. return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
  54038. }
  54039. function isInfinityOrNaNString(name) {
  54040. return name === "Infinity" || name === "-Infinity" || name === "NaN";
  54041. }
  54042. function isNumericLiteralName(name) {
  54043. // The intent of numeric names is that
  54044. // - they are names with text in a numeric form, and that
  54045. // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
  54046. // acquired by applying the abstract 'ToNumber' operation on the name's text.
  54047. //
  54048. // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
  54049. // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
  54050. //
  54051. // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
  54052. // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
  54053. // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
  54054. // because their 'ToString' representation is not equal to their original text.
  54055. // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
  54056. //
  54057. // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
  54058. // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
  54059. // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
  54060. //
  54061. // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
  54062. // This is desired behavior, because when indexing with them as numeric entities, you are indexing
  54063. // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
  54064. return (+name).toString() === name;
  54065. }
  54066. function checkComputedPropertyName(node) {
  54067. var links = getNodeLinks(node.expression);
  54068. if (!links.resolvedType) {
  54069. links.resolvedType = checkExpression(node.expression);
  54070. // This will allow types number, string, symbol or any. It will also allow enums, the unknown
  54071. // type, and any union of these types (like string | number).
  54072. if (links.resolvedType.flags & 98304 /* Nullable */ ||
  54073. !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
  54074. !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
  54075. error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
  54076. }
  54077. else {
  54078. checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
  54079. }
  54080. }
  54081. return links.resolvedType;
  54082. }
  54083. function getObjectLiteralIndexInfo(node, offset, properties, kind) {
  54084. var propTypes = [];
  54085. for (var i = 0; i < properties.length; i++) {
  54086. if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
  54087. propTypes.push(getTypeOfSymbol(properties[i]));
  54088. }
  54089. }
  54090. var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
  54091. return createIndexInfo(unionType, isConstContext(node));
  54092. }
  54093. function getImmediateAliasedSymbol(symbol) {
  54094. ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
  54095. var links = getSymbolLinks(symbol);
  54096. if (!links.immediateTarget) {
  54097. var node = getDeclarationOfAliasSymbol(symbol);
  54098. if (!node)
  54099. return ts.Debug.fail();
  54100. links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
  54101. }
  54102. return links.immediateTarget;
  54103. }
  54104. function checkObjectLiteral(node, checkMode) {
  54105. var inDestructuringPattern = ts.isAssignmentTarget(node);
  54106. // Grammar checking
  54107. checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
  54108. var propertiesTable;
  54109. var propertiesArray = [];
  54110. var spread = emptyObjectType;
  54111. var contextualType = getApparentTypeOfContextualType(node);
  54112. var contextualTypeHasPattern = contextualType && contextualType.pattern &&
  54113. (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
  54114. var inConstContext = isConstContext(node);
  54115. var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
  54116. var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
  54117. var enumTag = ts.getJSDocEnumTag(node);
  54118. var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
  54119. var objectFlags = freshObjectLiteralFlag;
  54120. var patternWithComputedProperties = false;
  54121. var hasComputedStringProperty = false;
  54122. var hasComputedNumberProperty = false;
  54123. propertiesTable = ts.createSymbolTable();
  54124. var offset = 0;
  54125. for (var i = 0; i < node.properties.length; i++) {
  54126. var memberDecl = node.properties[i];
  54127. var member = getSymbolOfNode(memberDecl);
  54128. var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
  54129. checkComputedPropertyName(memberDecl.name) : undefined;
  54130. if (memberDecl.kind === 281 /* PropertyAssignment */ ||
  54131. memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
  54132. ts.isObjectLiteralMethod(memberDecl)) {
  54133. var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
  54134. memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
  54135. checkObjectLiteralMethod(memberDecl, checkMode);
  54136. if (isInJavascript) {
  54137. var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
  54138. if (jsDocType) {
  54139. checkTypeAssignableTo(type, jsDocType, memberDecl);
  54140. type = jsDocType;
  54141. }
  54142. else if (enumTag && enumTag.typeExpression) {
  54143. checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
  54144. }
  54145. }
  54146. objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
  54147. var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
  54148. var prop = nameType ?
  54149. createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
  54150. createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
  54151. if (nameType) {
  54152. prop.nameType = nameType;
  54153. }
  54154. if (inDestructuringPattern) {
  54155. // If object literal is an assignment pattern and if the assignment pattern specifies a default value
  54156. // for the property, make the property optional.
  54157. var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
  54158. (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
  54159. if (isOptional) {
  54160. prop.flags |= 16777216 /* Optional */;
  54161. }
  54162. }
  54163. else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
  54164. // If object literal is contextually typed by the implied type of a binding pattern, and if the
  54165. // binding pattern specifies a default value for the property, make the property optional.
  54166. var impliedProp = getPropertyOfType(contextualType, member.escapedName);
  54167. if (impliedProp) {
  54168. prop.flags |= impliedProp.flags & 16777216 /* Optional */;
  54169. }
  54170. else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
  54171. error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
  54172. }
  54173. }
  54174. prop.declarations = member.declarations;
  54175. prop.parent = member.parent;
  54176. if (member.valueDeclaration) {
  54177. prop.valueDeclaration = member.valueDeclaration;
  54178. }
  54179. prop.type = type;
  54180. prop.target = member;
  54181. member = prop;
  54182. }
  54183. else if (memberDecl.kind === 283 /* SpreadAssignment */) {
  54184. if (languageVersion < 2 /* ES2015 */) {
  54185. checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
  54186. }
  54187. if (propertiesArray.length > 0) {
  54188. spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
  54189. propertiesArray = [];
  54190. propertiesTable = ts.createSymbolTable();
  54191. hasComputedStringProperty = false;
  54192. hasComputedNumberProperty = false;
  54193. }
  54194. var type = checkExpression(memberDecl.expression);
  54195. if (!isValidSpreadType(type)) {
  54196. error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
  54197. return errorType;
  54198. }
  54199. spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
  54200. offset = i + 1;
  54201. continue;
  54202. }
  54203. else {
  54204. // TypeScript 1.0 spec (April 2014)
  54205. // A get accessor declaration is processed in the same manner as
  54206. // an ordinary function declaration(section 6.1) with no parameters.
  54207. // A set accessor declaration is processed in the same manner
  54208. // as an ordinary function declaration with a single parameter and a Void return type.
  54209. ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
  54210. checkNodeDeferred(memberDecl);
  54211. }
  54212. if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
  54213. if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
  54214. if (isTypeAssignableTo(computedNameType, numberType)) {
  54215. hasComputedNumberProperty = true;
  54216. }
  54217. else {
  54218. hasComputedStringProperty = true;
  54219. }
  54220. if (inDestructuringPattern) {
  54221. patternWithComputedProperties = true;
  54222. }
  54223. }
  54224. }
  54225. else {
  54226. propertiesTable.set(member.escapedName, member);
  54227. }
  54228. propertiesArray.push(member);
  54229. }
  54230. // If object literal is contextually typed by the implied type of a binding pattern, augment the result
  54231. // type with those properties for which the binding pattern specifies a default value.
  54232. if (contextualTypeHasPattern) {
  54233. for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) {
  54234. var prop = _a[_i];
  54235. if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) {
  54236. if (!(prop.flags & 16777216 /* Optional */)) {
  54237. error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
  54238. }
  54239. propertiesTable.set(prop.escapedName, prop);
  54240. propertiesArray.push(prop);
  54241. }
  54242. }
  54243. }
  54244. if (spread !== emptyObjectType) {
  54245. if (propertiesArray.length > 0) {
  54246. spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
  54247. propertiesArray = [];
  54248. propertiesTable = ts.createSymbolTable();
  54249. hasComputedStringProperty = false;
  54250. hasComputedNumberProperty = false;
  54251. }
  54252. // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
  54253. return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
  54254. }
  54255. return createObjectLiteralType();
  54256. function createObjectLiteralType() {
  54257. var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
  54258. var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
  54259. var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
  54260. result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
  54261. if (isJSObjectLiteral) {
  54262. result.objectFlags |= 16384 /* JSLiteral */;
  54263. }
  54264. if (patternWithComputedProperties) {
  54265. result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
  54266. }
  54267. if (inDestructuringPattern) {
  54268. result.pattern = node;
  54269. }
  54270. return result;
  54271. }
  54272. }
  54273. function isValidSpreadType(type) {
  54274. if (type.flags & 63176704 /* Instantiable */) {
  54275. var constraint = getBaseConstraintOfType(type);
  54276. if (constraint !== undefined) {
  54277. return isValidSpreadType(constraint);
  54278. }
  54279. }
  54280. return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
  54281. getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
  54282. type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
  54283. }
  54284. function checkJsxSelfClosingElementDeferred(node) {
  54285. checkJsxOpeningLikeElementOrOpeningFragment(node);
  54286. }
  54287. function checkJsxSelfClosingElement(node, _checkMode) {
  54288. checkNodeDeferred(node);
  54289. return getJsxElementTypeAt(node) || anyType;
  54290. }
  54291. function checkJsxElementDeferred(node) {
  54292. // Check attributes
  54293. checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
  54294. // Perform resolution on the closing tag so that rename/go to definition/etc work
  54295. if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
  54296. getIntrinsicTagSymbol(node.closingElement);
  54297. }
  54298. else {
  54299. checkExpression(node.closingElement.tagName);
  54300. }
  54301. checkJsxChildren(node);
  54302. }
  54303. function checkJsxElement(node, _checkMode) {
  54304. checkNodeDeferred(node);
  54305. return getJsxElementTypeAt(node) || anyType;
  54306. }
  54307. function checkJsxFragment(node) {
  54308. checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
  54309. if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
  54310. error(node, compilerOptions.jsxFactory
  54311. ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
  54312. : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
  54313. }
  54314. checkJsxChildren(node);
  54315. return getJsxElementTypeAt(node) || anyType;
  54316. }
  54317. /**
  54318. * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
  54319. */
  54320. function isUnhyphenatedJsxName(name) {
  54321. // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
  54322. return !ts.stringContains(name, "-");
  54323. }
  54324. /**
  54325. * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
  54326. */
  54327. function isJsxIntrinsicIdentifier(tagName) {
  54328. return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
  54329. }
  54330. function checkJsxAttribute(node, checkMode) {
  54331. return node.initializer
  54332. ? checkExpressionForMutableLocation(node.initializer, checkMode)
  54333. : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
  54334. }
  54335. /**
  54336. * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
  54337. *
  54338. * @param openingLikeElement a JSX opening-like element
  54339. * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
  54340. * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
  54341. * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
  54342. * which also calls getSpreadType.
  54343. */
  54344. function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
  54345. var attributes = openingLikeElement.attributes;
  54346. var attributesTable = ts.createSymbolTable();
  54347. var spread = emptyJsxObjectType;
  54348. var hasSpreadAnyType = false;
  54349. var typeToIntersect;
  54350. var explicitlySpecifyChildrenAttribute = false;
  54351. var objectFlags = 4096 /* JsxAttributes */;
  54352. var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
  54353. for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
  54354. var attributeDecl = _a[_i];
  54355. var member = attributeDecl.symbol;
  54356. if (ts.isJsxAttribute(attributeDecl)) {
  54357. var exprType = checkJsxAttribute(attributeDecl, checkMode);
  54358. objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
  54359. var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
  54360. attributeSymbol.declarations = member.declarations;
  54361. attributeSymbol.parent = member.parent;
  54362. if (member.valueDeclaration) {
  54363. attributeSymbol.valueDeclaration = member.valueDeclaration;
  54364. }
  54365. attributeSymbol.type = exprType;
  54366. attributeSymbol.target = member;
  54367. attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
  54368. if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
  54369. explicitlySpecifyChildrenAttribute = true;
  54370. }
  54371. }
  54372. else {
  54373. ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
  54374. if (attributesTable.size > 0) {
  54375. spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
  54376. attributesTable = ts.createSymbolTable();
  54377. }
  54378. var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
  54379. if (isTypeAny(exprType)) {
  54380. hasSpreadAnyType = true;
  54381. }
  54382. if (isValidSpreadType(exprType)) {
  54383. spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
  54384. }
  54385. else {
  54386. typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
  54387. }
  54388. }
  54389. }
  54390. if (!hasSpreadAnyType) {
  54391. if (attributesTable.size > 0) {
  54392. spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
  54393. }
  54394. }
  54395. // Handle children attribute
  54396. var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
  54397. // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
  54398. if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
  54399. var childrenTypes = checkJsxChildren(parent, checkMode);
  54400. if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
  54401. // Error if there is a attribute named "children" explicitly specified and children element.
  54402. // This is because children element will overwrite the value from attributes.
  54403. // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
  54404. if (explicitlySpecifyChildrenAttribute) {
  54405. error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
  54406. }
  54407. var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
  54408. var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
  54409. // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process
  54410. var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
  54411. childrenPropSymbol.type = childrenTypes.length === 1 ?
  54412. childrenTypes[0] :
  54413. (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
  54414. // Fake up a property declaration for the children
  54415. childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
  54416. childrenPropSymbol.valueDeclaration.parent = attributes;
  54417. childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
  54418. var childPropMap = ts.createSymbolTable();
  54419. childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
  54420. spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
  54421. }
  54422. }
  54423. if (hasSpreadAnyType) {
  54424. return anyType;
  54425. }
  54426. if (typeToIntersect && spread !== emptyJsxObjectType) {
  54427. return getIntersectionType([typeToIntersect, spread]);
  54428. }
  54429. return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
  54430. /**
  54431. * Create anonymous type from given attributes symbol table.
  54432. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
  54433. * @param attributesTable a symbol table of attributes property
  54434. */
  54435. function createJsxAttributesType() {
  54436. objectFlags |= freshObjectLiteralFlag;
  54437. var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
  54438. result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
  54439. return result;
  54440. }
  54441. }
  54442. function checkJsxChildren(node, checkMode) {
  54443. var childrenTypes = [];
  54444. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  54445. var child = _a[_i];
  54446. // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
  54447. // because then type of children property will have constituent of string type.
  54448. if (child.kind === 11 /* JsxText */) {
  54449. if (!child.containsOnlyTriviaWhiteSpaces) {
  54450. childrenTypes.push(stringType);
  54451. }
  54452. }
  54453. else {
  54454. childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
  54455. }
  54456. }
  54457. return childrenTypes;
  54458. }
  54459. /**
  54460. * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
  54461. * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
  54462. * @param node a JSXAttributes to be resolved of its type
  54463. */
  54464. function checkJsxAttributes(node, checkMode) {
  54465. return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
  54466. }
  54467. function getJsxType(name, location) {
  54468. var namespace = getJsxNamespaceAt(location);
  54469. var exports = namespace && getExportsOfSymbol(namespace);
  54470. var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
  54471. return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
  54472. }
  54473. /**
  54474. * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
  54475. * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
  54476. * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
  54477. * May also return unknownSymbol if both of these lookups fail.
  54478. */
  54479. function getIntrinsicTagSymbol(node) {
  54480. var links = getNodeLinks(node);
  54481. if (!links.resolvedSymbol) {
  54482. var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
  54483. if (intrinsicElementsType !== errorType) {
  54484. // Property case
  54485. if (!ts.isIdentifier(node.tagName))
  54486. return ts.Debug.fail();
  54487. var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
  54488. if (intrinsicProp) {
  54489. links.jsxFlags |= 1 /* IntrinsicNamedElement */;
  54490. return links.resolvedSymbol = intrinsicProp;
  54491. }
  54492. // Intrinsic string indexer case
  54493. var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
  54494. if (indexSignatureType) {
  54495. links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
  54496. return links.resolvedSymbol = intrinsicElementsType.symbol;
  54497. }
  54498. // Wasn't found
  54499. error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
  54500. return links.resolvedSymbol = unknownSymbol;
  54501. }
  54502. else {
  54503. if (noImplicitAny) {
  54504. error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
  54505. }
  54506. return links.resolvedSymbol = unknownSymbol;
  54507. }
  54508. }
  54509. return links.resolvedSymbol;
  54510. }
  54511. function getJsxNamespaceAt(location) {
  54512. var links = location && getNodeLinks(location);
  54513. if (links && links.jsxNamespace) {
  54514. return links.jsxNamespace;
  54515. }
  54516. if (!links || links.jsxNamespace !== false) {
  54517. var namespaceName = getJsxNamespace(location);
  54518. var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
  54519. if (resolvedNamespace) {
  54520. var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
  54521. if (candidate) {
  54522. if (links) {
  54523. links.jsxNamespace = candidate;
  54524. }
  54525. return candidate;
  54526. }
  54527. if (links) {
  54528. links.jsxNamespace = false;
  54529. }
  54530. }
  54531. }
  54532. // JSX global fallback
  54533. return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
  54534. }
  54535. /**
  54536. * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
  54537. * Get a single property from that container if existed. Report an error if there are more than one property.
  54538. *
  54539. * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
  54540. * if other string is given or the container doesn't exist, return undefined.
  54541. */
  54542. function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
  54543. // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
  54544. var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
  54545. // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
  54546. var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
  54547. // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
  54548. var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
  54549. if (propertiesOfJsxElementAttribPropInterface) {
  54550. // Element Attributes has zero properties, so the element attributes type will be the class instance type
  54551. if (propertiesOfJsxElementAttribPropInterface.length === 0) {
  54552. return "";
  54553. }
  54554. // Element Attributes has one property, so the element attributes type will be the type of the corresponding
  54555. // property of the class instance type
  54556. else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
  54557. return propertiesOfJsxElementAttribPropInterface[0].escapedName;
  54558. }
  54559. else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
  54560. // More than one property on ElementAttributesProperty is an error
  54561. error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
  54562. }
  54563. }
  54564. return undefined;
  54565. }
  54566. function getJsxLibraryManagedAttributes(jsxNamespace) {
  54567. // JSX.LibraryManagedAttributes [symbol]
  54568. return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
  54569. }
  54570. /// e.g. "props" for React.d.ts,
  54571. /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
  54572. /// non-intrinsic elements' attributes type is 'any'),
  54573. /// or '' if it has 0 properties (which means every
  54574. /// non-intrinsic elements' attributes type is the element instance type)
  54575. function getJsxElementPropertiesName(jsxNamespace) {
  54576. return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
  54577. }
  54578. function getJsxElementChildrenPropertyName(jsxNamespace) {
  54579. return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
  54580. }
  54581. function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
  54582. if (elementType.flags & 4 /* String */) {
  54583. return [anySignature];
  54584. }
  54585. else if (elementType.flags & 128 /* StringLiteral */) {
  54586. var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
  54587. if (!intrinsicType) {
  54588. error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
  54589. return ts.emptyArray;
  54590. }
  54591. else {
  54592. var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
  54593. return [fakeSignature];
  54594. }
  54595. }
  54596. var apparentElemType = getApparentType(elementType);
  54597. // Resolve the signatures, preferring constructor
  54598. var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
  54599. if (signatures.length === 0) {
  54600. // No construct signatures, try call signatures
  54601. signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
  54602. }
  54603. if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
  54604. // If each member has some combination of new/call signatures; make a union signature list for those
  54605. signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
  54606. }
  54607. return signatures;
  54608. }
  54609. function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
  54610. // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type
  54611. // For example:
  54612. // var CustomTag: "h1" = "h1";
  54613. // <CustomTag> Hello World </CustomTag>
  54614. var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
  54615. if (intrinsicElementsType !== errorType) {
  54616. var stringLiteralTypeName = type.value;
  54617. var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
  54618. if (intrinsicProp) {
  54619. return getTypeOfSymbol(intrinsicProp);
  54620. }
  54621. var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
  54622. if (indexSignatureType) {
  54623. return indexSignatureType;
  54624. }
  54625. return undefined;
  54626. }
  54627. // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
  54628. return anyType;
  54629. }
  54630. function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
  54631. if (refKind === 1 /* Function */) {
  54632. var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
  54633. if (sfcReturnConstraint) {
  54634. checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
  54635. }
  54636. }
  54637. else if (refKind === 0 /* Component */) {
  54638. var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
  54639. if (classConstraint) {
  54640. // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that
  54641. checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
  54642. }
  54643. }
  54644. else { // Mixed
  54645. var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
  54646. var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
  54647. if (!sfcReturnConstraint || !classConstraint) {
  54648. return;
  54649. }
  54650. var combined = getUnionType([sfcReturnConstraint, classConstraint]);
  54651. checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
  54652. }
  54653. }
  54654. /**
  54655. * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
  54656. * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
  54657. * @param node an intrinsic JSX opening-like element
  54658. */
  54659. function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
  54660. ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
  54661. var links = getNodeLinks(node);
  54662. if (!links.resolvedJsxElementAttributesType) {
  54663. var symbol = getIntrinsicTagSymbol(node);
  54664. if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
  54665. return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
  54666. }
  54667. else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
  54668. return links.resolvedJsxElementAttributesType =
  54669. getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
  54670. }
  54671. else {
  54672. return links.resolvedJsxElementAttributesType = errorType;
  54673. }
  54674. }
  54675. return links.resolvedJsxElementAttributesType;
  54676. }
  54677. function getJsxElementClassTypeAt(location) {
  54678. var type = getJsxType(JsxNames.ElementClass, location);
  54679. if (type === errorType)
  54680. return undefined;
  54681. return type;
  54682. }
  54683. function getJsxElementTypeAt(location) {
  54684. return getJsxType(JsxNames.Element, location);
  54685. }
  54686. function getJsxStatelessElementTypeAt(location) {
  54687. var jsxElementType = getJsxElementTypeAt(location);
  54688. if (jsxElementType) {
  54689. return getUnionType([jsxElementType, nullType]);
  54690. }
  54691. }
  54692. /**
  54693. * Returns all the properties of the Jsx.IntrinsicElements interface
  54694. */
  54695. function getJsxIntrinsicTagNamesAt(location) {
  54696. var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
  54697. return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
  54698. }
  54699. function checkJsxPreconditions(errorNode) {
  54700. // Preconditions for using JSX
  54701. if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
  54702. error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
  54703. }
  54704. if (getJsxElementTypeAt(errorNode) === undefined) {
  54705. if (noImplicitAny) {
  54706. error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
  54707. }
  54708. }
  54709. }
  54710. function checkJsxOpeningLikeElementOrOpeningFragment(node) {
  54711. var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
  54712. if (isNodeOpeningLikeElement) {
  54713. checkGrammarJsxElement(node);
  54714. }
  54715. checkJsxPreconditions(node);
  54716. // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
  54717. // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
  54718. var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
  54719. var reactNamespace = getJsxNamespace(node);
  54720. var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
  54721. var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
  54722. if (reactSym) {
  54723. // Mark local symbol as referenced here because it might not have been marked
  54724. // if jsx emit was not react as there wont be error being emitted
  54725. reactSym.isReferenced = 67108863 /* All */;
  54726. // If react symbol is alias, mark it as refereced
  54727. if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
  54728. markAliasSymbolAsReferenced(reactSym);
  54729. }
  54730. }
  54731. if (isNodeOpeningLikeElement) {
  54732. var sig = getResolvedSignature(node);
  54733. checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node);
  54734. }
  54735. }
  54736. /**
  54737. * Check if a property with the given name is known anywhere in the given type. In an object type, a property
  54738. * is considered known if
  54739. * 1. the object type is empty and the check is for assignability, or
  54740. * 2. if the object type has index signatures, or
  54741. * 3. if the property is actually declared in the object type
  54742. * (this means that 'toString', for example, is not usually a known property).
  54743. * 4. In a union or intersection type,
  54744. * a property is considered known if it is known in any constituent type.
  54745. * @param targetType a type to search a given name in
  54746. * @param name a property name to search
  54747. * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
  54748. */
  54749. function isKnownProperty(targetType, name, isComparingJsxAttributes) {
  54750. if (targetType.flags & 524288 /* Object */) {
  54751. var resolved = resolveStructuredTypeMembers(targetType);
  54752. if (resolved.stringIndexInfo ||
  54753. resolved.numberIndexInfo && isNumericLiteralName(name) ||
  54754. getPropertyOfObjectType(targetType, name) ||
  54755. isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
  54756. // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
  54757. return true;
  54758. }
  54759. }
  54760. else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
  54761. for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
  54762. var t = _a[_i];
  54763. if (isKnownProperty(t, name, isComparingJsxAttributes)) {
  54764. return true;
  54765. }
  54766. }
  54767. }
  54768. return false;
  54769. }
  54770. function isExcessPropertyCheckTarget(type) {
  54771. return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
  54772. type.flags & 67108864 /* NonPrimitive */ ||
  54773. type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
  54774. type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
  54775. }
  54776. function checkJsxExpression(node, checkMode) {
  54777. checkGrammarJsxExpression(node);
  54778. if (node.expression) {
  54779. var type = checkExpression(node.expression, checkMode);
  54780. if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
  54781. error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
  54782. }
  54783. return type;
  54784. }
  54785. else {
  54786. return errorType;
  54787. }
  54788. }
  54789. function getDeclarationNodeFlagsFromSymbol(s) {
  54790. return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
  54791. }
  54792. /**
  54793. * Return whether this symbol is a member of a prototype somewhere
  54794. * Note that this is not tracked well within the compiler, so the answer may be incorrect.
  54795. */
  54796. function isPrototypeProperty(symbol) {
  54797. if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
  54798. return true;
  54799. }
  54800. if (ts.isInJSFile(symbol.valueDeclaration)) {
  54801. var parent = symbol.valueDeclaration.parent;
  54802. return parent && ts.isBinaryExpression(parent) &&
  54803. ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
  54804. }
  54805. }
  54806. /**
  54807. * Check whether the requested property access is valid.
  54808. * Returns true if node is a valid property access, and false otherwise.
  54809. * @param node The node to be checked.
  54810. * @param isSuper True if the access is from `super.`.
  54811. * @param type The type of the object whose property is being accessed. (Not the type of the property.)
  54812. * @param prop The symbol for the property being accessed.
  54813. */
  54814. function checkPropertyAccessibility(node, isSuper, type, prop) {
  54815. var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
  54816. var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
  54817. if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) {
  54818. // Synthetic property with private constituent property
  54819. error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type));
  54820. return false;
  54821. }
  54822. if (isSuper) {
  54823. // TS 1.0 spec (April 2014): 4.8.2
  54824. // - In a constructor, instance member function, instance member accessor, or
  54825. // instance member variable initializer where this references a derived class instance,
  54826. // a super property access is permitted and must specify a public instance member function of the base class.
  54827. // - In a static member function or static member accessor
  54828. // where this references the constructor function object of a derived class,
  54829. // a super property access is permitted and must specify a public static member function of the base class.
  54830. if (languageVersion < 2 /* ES2015 */) {
  54831. if (symbolHasNonMethodDeclaration(prop)) {
  54832. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
  54833. return false;
  54834. }
  54835. }
  54836. if (flags & 128 /* Abstract */) {
  54837. // A method cannot be accessed in a super property access if the method is abstract.
  54838. // This error could mask a private property access error. But, a member
  54839. // cannot simultaneously be private and abstract, so this will trigger an
  54840. // additional error elsewhere.
  54841. error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
  54842. return false;
  54843. }
  54844. }
  54845. // Referencing abstract properties within their own constructors is not allowed
  54846. if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
  54847. var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
  54848. if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
  54849. error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217
  54850. return false;
  54851. }
  54852. }
  54853. if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
  54854. if (!ts.getContainingClass(node)) {
  54855. error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
  54856. return false;
  54857. }
  54858. return true;
  54859. }
  54860. // Public properties are otherwise accessible.
  54861. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
  54862. return true;
  54863. }
  54864. // Property is known to be private or protected at this point
  54865. // Private property is accessible if the property is within the declaring class
  54866. if (flags & 8 /* Private */) {
  54867. var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
  54868. if (!isNodeWithinClass(node, declaringClassDeclaration)) {
  54869. error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
  54870. return false;
  54871. }
  54872. return true;
  54873. }
  54874. // Property is known to be protected at this point
  54875. // All protected properties of a supertype are accessible in a super access
  54876. if (isSuper) {
  54877. return true;
  54878. }
  54879. // Find the first enclosing class that has the declaring classes of the protected constituents
  54880. // of the property as base classes
  54881. var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
  54882. var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
  54883. return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
  54884. });
  54885. // A protected property is accessible if the property is within the declaring class or classes derived from it
  54886. if (!enclosingClass) {
  54887. // allow PropertyAccessibility if context is in function with this parameter
  54888. // static member access is disallow
  54889. var thisParameter = void 0;
  54890. if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
  54891. error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
  54892. return false;
  54893. }
  54894. var thisType = getTypeFromTypeNode(thisParameter.type);
  54895. enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType);
  54896. }
  54897. // No further restrictions for static properties
  54898. if (flags & 32 /* Static */) {
  54899. return true;
  54900. }
  54901. if (type.flags & 262144 /* TypeParameter */) {
  54902. // get the original type -- represented as the type constraint of the 'this' type
  54903. type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
  54904. }
  54905. if (!type || !hasBaseType(type, enclosingClass)) {
  54906. error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
  54907. return false;
  54908. }
  54909. return true;
  54910. }
  54911. function getThisParameterFromNodeContext(node) {
  54912. var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
  54913. return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
  54914. }
  54915. function symbolHasNonMethodDeclaration(symbol) {
  54916. return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
  54917. }
  54918. function checkNonNullExpression(node) {
  54919. return checkNonNullType(checkExpression(node), node);
  54920. }
  54921. function isNullableType(type) {
  54922. return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
  54923. }
  54924. function getNonNullableTypeIfNeeded(type) {
  54925. return isNullableType(type) ? getNonNullableType(type) : type;
  54926. }
  54927. function reportObjectPossiblyNullOrUndefinedError(node, flags) {
  54928. error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
  54929. ts.Diagnostics.Object_is_possibly_null_or_undefined :
  54930. ts.Diagnostics.Object_is_possibly_undefined :
  54931. ts.Diagnostics.Object_is_possibly_null);
  54932. }
  54933. function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
  54934. error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
  54935. ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
  54936. ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
  54937. ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
  54938. }
  54939. function checkNonNullTypeWithReporter(type, node, reportError) {
  54940. if (strictNullChecks && type.flags & 2 /* Unknown */) {
  54941. error(node, ts.Diagnostics.Object_is_of_type_unknown);
  54942. return errorType;
  54943. }
  54944. var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
  54945. if (kind) {
  54946. reportError(node, kind);
  54947. var t = getNonNullableType(type);
  54948. return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
  54949. }
  54950. return type;
  54951. }
  54952. function checkNonNullType(type, node) {
  54953. return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
  54954. }
  54955. function checkNonNullNonVoidType(type, node) {
  54956. var nonNullType = checkNonNullType(type, node);
  54957. if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
  54958. error(node, ts.Diagnostics.Object_is_possibly_undefined);
  54959. }
  54960. return nonNullType;
  54961. }
  54962. function checkPropertyAccessExpression(node) {
  54963. return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
  54964. checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
  54965. }
  54966. function checkPropertyAccessChain(node) {
  54967. var leftType = checkExpression(node.expression);
  54968. var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
  54969. return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
  54970. }
  54971. function checkQualifiedName(node) {
  54972. return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
  54973. }
  54974. function isMethodAccessForCall(node) {
  54975. while (node.parent.kind === 200 /* ParenthesizedExpression */) {
  54976. node = node.parent;
  54977. }
  54978. return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
  54979. }
  54980. // Lookup the private identifier lexically.
  54981. function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
  54982. for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
  54983. var symbol = containingClass.symbol;
  54984. var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
  54985. var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
  54986. if (prop) {
  54987. return prop;
  54988. }
  54989. }
  54990. }
  54991. function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
  54992. return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
  54993. }
  54994. function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
  54995. // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
  54996. // Find a private identifier with the same description on the type.
  54997. var propertyOnType;
  54998. var properties = getPropertiesOfType(leftType);
  54999. if (properties) {
  55000. ts.forEach(properties, function (symbol) {
  55001. var decl = symbol.valueDeclaration;
  55002. if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
  55003. propertyOnType = symbol;
  55004. return true;
  55005. }
  55006. });
  55007. }
  55008. var diagName = diagnosticName(right);
  55009. if (propertyOnType) {
  55010. var typeValueDecl = propertyOnType.valueDeclaration;
  55011. var typeClass_1 = ts.getContainingClass(typeValueDecl);
  55012. ts.Debug.assert(!!typeClass_1);
  55013. // We found a private identifier property with the same description.
  55014. // Either:
  55015. // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
  55016. // - It is an attempt to access the private identifier outside of the class.
  55017. if (lexicallyScopedIdentifier) {
  55018. var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
  55019. var lexicalClass = ts.getContainingClass(lexicalValueDecl);
  55020. ts.Debug.assert(!!lexicalClass);
  55021. if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
  55022. var diagnostic = error(right, ts.Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, diagName, typeToString(leftType));
  55023. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(lexicalValueDecl, ts.Diagnostics.The_shadowing_declaration_of_0_is_defined_here, diagName), ts.createDiagnosticForNode(typeValueDecl, ts.Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, diagName));
  55024. return true;
  55025. }
  55026. }
  55027. error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
  55028. return true;
  55029. }
  55030. return false;
  55031. }
  55032. function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
  55033. var parentSymbol = getNodeLinks(left).resolvedSymbol;
  55034. var assignmentKind = ts.getAssignmentTargetKind(node);
  55035. var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
  55036. if (ts.isPrivateIdentifier(right)) {
  55037. checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
  55038. }
  55039. var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
  55040. var prop;
  55041. if (ts.isPrivateIdentifier(right)) {
  55042. var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
  55043. if (isAnyLike) {
  55044. if (lexicallyScopedSymbol) {
  55045. return apparentType;
  55046. }
  55047. if (!ts.getContainingClass(right)) {
  55048. grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
  55049. return anyType;
  55050. }
  55051. }
  55052. prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
  55053. // Check for private-identifier-specific shadowing and lexical-scoping errors.
  55054. if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
  55055. return errorType;
  55056. }
  55057. }
  55058. else {
  55059. if (isAnyLike) {
  55060. if (ts.isIdentifier(left) && parentSymbol) {
  55061. markAliasReferenced(parentSymbol, node);
  55062. }
  55063. return apparentType;
  55064. }
  55065. prop = getPropertyOfType(apparentType, right.escapedText);
  55066. }
  55067. if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
  55068. markAliasReferenced(parentSymbol, node);
  55069. }
  55070. var propType;
  55071. if (!prop) {
  55072. var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
  55073. if (!(indexInfo && indexInfo.type)) {
  55074. if (isJSLiteralType(leftType)) {
  55075. return anyType;
  55076. }
  55077. if (leftType.symbol === globalThisSymbol) {
  55078. if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
  55079. error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
  55080. }
  55081. else if (noImplicitAny) {
  55082. error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
  55083. }
  55084. return anyType;
  55085. }
  55086. if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
  55087. reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
  55088. }
  55089. return errorType;
  55090. }
  55091. if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
  55092. error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
  55093. }
  55094. propType = indexInfo.type;
  55095. }
  55096. else {
  55097. checkPropertyNotUsedBeforeDeclaration(prop, node, right);
  55098. markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
  55099. getNodeLinks(node).resolvedSymbol = prop;
  55100. checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
  55101. if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
  55102. error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
  55103. return errorType;
  55104. }
  55105. propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
  55106. }
  55107. return getFlowTypeOfAccessExpression(node, prop, propType, right);
  55108. }
  55109. function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
  55110. // Only compute control flow type if this is a property access expression that isn't an
  55111. // assignment target, and the referenced property was declared as a variable, property,
  55112. // accessor, or optional method.
  55113. var assignmentKind = ts.getAssignmentTargetKind(node);
  55114. if (!ts.isAccessExpression(node) ||
  55115. assignmentKind === 1 /* Definite */ ||
  55116. prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
  55117. return propType;
  55118. }
  55119. // If strict null checks and strict property initialization checks are enabled, if we have
  55120. // a this.xxx property access, if the property is an instance property without an initializer,
  55121. // and if we are in a constructor of the same class as the property declaration, assume that
  55122. // the property is uninitialized at the top of the control flow.
  55123. var assumeUninitialized = false;
  55124. if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
  55125. var declaration = prop && prop.valueDeclaration;
  55126. if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
  55127. var flowContainer = getControlFlowContainer(node);
  55128. if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
  55129. assumeUninitialized = true;
  55130. }
  55131. }
  55132. }
  55133. else if (strictNullChecks && prop && prop.valueDeclaration &&
  55134. ts.isPropertyAccessExpression(prop.valueDeclaration) &&
  55135. ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
  55136. getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
  55137. assumeUninitialized = true;
  55138. }
  55139. var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
  55140. if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
  55141. error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
  55142. // Return the declared type to reduce follow-on errors
  55143. return propType;
  55144. }
  55145. return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
  55146. }
  55147. function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
  55148. var valueDeclaration = prop.valueDeclaration;
  55149. if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
  55150. return;
  55151. }
  55152. var diagnosticMessage;
  55153. var declarationName = ts.idText(right);
  55154. if (isInPropertyInitializer(node)
  55155. && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
  55156. && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
  55157. && !isPropertyDeclaredInAncestorClass(prop)) {
  55158. diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
  55159. }
  55160. else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
  55161. node.parent.kind !== 169 /* TypeReference */ &&
  55162. !(valueDeclaration.flags & 8388608 /* Ambient */) &&
  55163. !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
  55164. diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
  55165. }
  55166. if (diagnosticMessage) {
  55167. ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
  55168. }
  55169. }
  55170. function isInPropertyInitializer(node) {
  55171. return !!ts.findAncestor(node, function (node) {
  55172. switch (node.kind) {
  55173. case 159 /* PropertyDeclaration */:
  55174. return true;
  55175. case 281 /* PropertyAssignment */:
  55176. case 161 /* MethodDeclaration */:
  55177. case 163 /* GetAccessor */:
  55178. case 164 /* SetAccessor */:
  55179. case 283 /* SpreadAssignment */:
  55180. case 154 /* ComputedPropertyName */:
  55181. case 221 /* TemplateSpan */:
  55182. case 276 /* JsxExpression */:
  55183. case 273 /* JsxAttribute */:
  55184. case 274 /* JsxAttributes */:
  55185. case 275 /* JsxSpreadAttribute */:
  55186. case 268 /* JsxOpeningElement */:
  55187. case 216 /* ExpressionWithTypeArguments */:
  55188. case 279 /* HeritageClause */:
  55189. return false;
  55190. default:
  55191. return ts.isExpressionNode(node) ? false : "quit";
  55192. }
  55193. });
  55194. }
  55195. /**
  55196. * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
  55197. * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
  55198. */
  55199. function isPropertyDeclaredInAncestorClass(prop) {
  55200. if (!(prop.parent.flags & 32 /* Class */)) {
  55201. return false;
  55202. }
  55203. var classType = getTypeOfSymbol(prop.parent);
  55204. while (true) {
  55205. classType = classType.symbol && getSuperClass(classType);
  55206. if (!classType) {
  55207. return false;
  55208. }
  55209. var superProperty = getPropertyOfType(classType, prop.escapedName);
  55210. if (superProperty && superProperty.valueDeclaration) {
  55211. return true;
  55212. }
  55213. }
  55214. }
  55215. function getSuperClass(classType) {
  55216. var x = getBaseTypes(classType);
  55217. if (x.length === 0) {
  55218. return undefined;
  55219. }
  55220. return getIntersectionType(x);
  55221. }
  55222. function reportNonexistentProperty(propNode, containingType) {
  55223. var errorInfo;
  55224. var relatedInfo;
  55225. if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
  55226. for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
  55227. var subtype = _a[_i];
  55228. if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
  55229. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
  55230. break;
  55231. }
  55232. }
  55233. }
  55234. if (typeHasStaticProperty(propNode.escapedText, containingType)) {
  55235. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
  55236. }
  55237. else {
  55238. var promisedType = getPromisedTypeOfPromise(containingType);
  55239. if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
  55240. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
  55241. relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
  55242. }
  55243. else {
  55244. var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
  55245. if (suggestion !== undefined) {
  55246. var suggestedName = ts.symbolName(suggestion);
  55247. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
  55248. relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
  55249. }
  55250. else {
  55251. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
  55252. }
  55253. }
  55254. }
  55255. var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
  55256. if (relatedInfo) {
  55257. ts.addRelatedInfo(resultDiagnostic, relatedInfo);
  55258. }
  55259. diagnostics.add(resultDiagnostic);
  55260. }
  55261. function typeHasStaticProperty(propName, containingType) {
  55262. var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
  55263. return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
  55264. }
  55265. function getSuggestedSymbolForNonexistentProperty(name, containingType) {
  55266. return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
  55267. }
  55268. function getSuggestionForNonexistentProperty(name, containingType) {
  55269. var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
  55270. return suggestion && ts.symbolName(suggestion);
  55271. }
  55272. function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
  55273. ts.Debug.assert(outerName !== undefined, "outername should always be defined");
  55274. var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
  55275. ts.Debug.assertEqual(outerName, name, "name should equal outerName");
  55276. var symbol = getSymbol(symbols, name, meaning);
  55277. // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function
  55278. // So the table *contains* `x` but `x` isn't actually in scope.
  55279. // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
  55280. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
  55281. });
  55282. return result;
  55283. }
  55284. function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
  55285. var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
  55286. return symbolResult && ts.symbolName(symbolResult);
  55287. }
  55288. function getSuggestedSymbolForNonexistentModule(name, targetModule) {
  55289. return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
  55290. }
  55291. function getSuggestionForNonexistentExport(name, targetModule) {
  55292. var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
  55293. return suggestion && ts.symbolName(suggestion);
  55294. }
  55295. function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
  55296. // check if object type has setter or getter
  55297. function hasProp(name) {
  55298. var prop = getPropertyOfObjectType(objectType, name);
  55299. if (prop) {
  55300. var s = getSingleCallSignature(getTypeOfSymbol(prop));
  55301. return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
  55302. }
  55303. return false;
  55304. }
  55305. ;
  55306. var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
  55307. if (!hasProp(suggestedMethod)) {
  55308. return undefined;
  55309. }
  55310. var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
  55311. if (suggestion === undefined) {
  55312. suggestion = suggestedMethod;
  55313. }
  55314. else {
  55315. suggestion += "." + suggestedMethod;
  55316. }
  55317. return suggestion;
  55318. }
  55319. /**
  55320. * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
  55321. * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
  55322. *
  55323. * If there is a candidate that's the same except for case, return that.
  55324. * If there is a candidate that's within one edit of the name, return that.
  55325. * Otherwise, return the candidate with the smallest Levenshtein distance,
  55326. * except for candidates:
  55327. * * With no name
  55328. * * Whose meaning doesn't match the `meaning` parameter.
  55329. * * Whose length differs from the target name by more than 0.34 of the length of the name.
  55330. * * Whose levenshtein distance is more than 0.4 of the length of the name
  55331. * (0.4 allows 1 substitution/transposition for every 5 characters,
  55332. * and 1 insertion/deletion at 3 characters)
  55333. */
  55334. function getSpellingSuggestionForName(name, symbols, meaning) {
  55335. return ts.getSpellingSuggestion(name, symbols, getCandidateName);
  55336. function getCandidateName(candidate) {
  55337. var candidateName = ts.symbolName(candidate);
  55338. return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined;
  55339. }
  55340. }
  55341. function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
  55342. var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
  55343. if (!valueDeclaration) {
  55344. return;
  55345. }
  55346. var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
  55347. var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
  55348. if (!hasPrivateModifier && !hasPrivateIdentifier) {
  55349. return;
  55350. }
  55351. if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) {
  55352. return;
  55353. }
  55354. if (isThisAccess) {
  55355. // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
  55356. var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
  55357. if (containingMethod && containingMethod.symbol === prop) {
  55358. return;
  55359. }
  55360. }
  55361. (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
  55362. }
  55363. function isValidPropertyAccess(node, propertyName) {
  55364. switch (node.kind) {
  55365. case 194 /* PropertyAccessExpression */:
  55366. return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
  55367. case 153 /* QualifiedName */:
  55368. return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
  55369. case 188 /* ImportType */:
  55370. return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
  55371. }
  55372. }
  55373. function isValidPropertyAccessForCompletions(node, type, property) {
  55374. return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
  55375. // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
  55376. }
  55377. function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
  55378. if (type === errorType || isTypeAny(type)) {
  55379. return true;
  55380. }
  55381. var prop = getPropertyOfType(type, propertyName);
  55382. if (prop) {
  55383. if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
  55384. var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
  55385. return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
  55386. }
  55387. return checkPropertyAccessibility(node, isSuper, type, prop);
  55388. }
  55389. // In js files properties of unions are allowed in completion
  55390. return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
  55391. }
  55392. /**
  55393. * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
  55394. */
  55395. function getForInVariableSymbol(node) {
  55396. var initializer = node.initializer;
  55397. if (initializer.kind === 243 /* VariableDeclarationList */) {
  55398. var variable = initializer.declarations[0];
  55399. if (variable && !ts.isBindingPattern(variable.name)) {
  55400. return getSymbolOfNode(variable);
  55401. }
  55402. }
  55403. else if (initializer.kind === 75 /* Identifier */) {
  55404. return getResolvedSymbol(initializer);
  55405. }
  55406. return undefined;
  55407. }
  55408. /**
  55409. * Return true if the given type is considered to have numeric property names.
  55410. */
  55411. function hasNumericPropertyNames(type) {
  55412. return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
  55413. }
  55414. /**
  55415. * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
  55416. * that references a for-in variable for an object with numeric property names.
  55417. */
  55418. function isForInVariableForNumericPropertyNames(expr) {
  55419. var e = ts.skipParentheses(expr);
  55420. if (e.kind === 75 /* Identifier */) {
  55421. var symbol = getResolvedSymbol(e);
  55422. if (symbol.flags & 3 /* Variable */) {
  55423. var child = expr;
  55424. var node = expr.parent;
  55425. while (node) {
  55426. if (node.kind === 231 /* ForInStatement */ &&
  55427. child === node.statement &&
  55428. getForInVariableSymbol(node) === symbol &&
  55429. hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
  55430. return true;
  55431. }
  55432. child = node;
  55433. node = node.parent;
  55434. }
  55435. }
  55436. }
  55437. return false;
  55438. }
  55439. function checkIndexedAccess(node) {
  55440. return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
  55441. checkElementAccessExpression(node, checkNonNullExpression(node.expression));
  55442. }
  55443. function checkElementAccessChain(node) {
  55444. var exprType = checkExpression(node.expression);
  55445. var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
  55446. return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
  55447. }
  55448. function checkElementAccessExpression(node, exprType) {
  55449. var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
  55450. var indexExpression = node.argumentExpression;
  55451. var indexType = checkExpression(indexExpression);
  55452. if (objectType === errorType || objectType === silentNeverType) {
  55453. return objectType;
  55454. }
  55455. if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
  55456. error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
  55457. return errorType;
  55458. }
  55459. var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
  55460. var accessFlags = ts.isAssignmentTarget(node) ?
  55461. 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
  55462. 0 /* None */;
  55463. var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
  55464. return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
  55465. }
  55466. function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
  55467. if (expressionType === errorType) {
  55468. // There is already an error, so no need to report one.
  55469. return false;
  55470. }
  55471. if (!ts.isWellKnownSymbolSyntactically(expression)) {
  55472. return false;
  55473. }
  55474. // Make sure the property type is the primitive symbol type
  55475. if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
  55476. if (reportError) {
  55477. error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
  55478. }
  55479. return false;
  55480. }
  55481. // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
  55482. // global Symbol object
  55483. var leftHandSide = expression.expression;
  55484. var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
  55485. if (!leftHandSideSymbol) {
  55486. return false;
  55487. }
  55488. var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
  55489. if (!globalESSymbol) {
  55490. // Already errored when we tried to look up the symbol
  55491. return false;
  55492. }
  55493. if (leftHandSideSymbol !== globalESSymbol) {
  55494. if (reportError) {
  55495. error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
  55496. }
  55497. return false;
  55498. }
  55499. return true;
  55500. }
  55501. function callLikeExpressionMayHaveTypeArguments(node) {
  55502. return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
  55503. }
  55504. function resolveUntypedCall(node) {
  55505. if (callLikeExpressionMayHaveTypeArguments(node)) {
  55506. // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
  55507. // This gets us diagnostics for the type arguments and marks them as referenced.
  55508. ts.forEach(node.typeArguments, checkSourceElement);
  55509. }
  55510. if (node.kind === 198 /* TaggedTemplateExpression */) {
  55511. checkExpression(node.template);
  55512. }
  55513. else if (ts.isJsxOpeningLikeElement(node)) {
  55514. checkExpression(node.attributes);
  55515. }
  55516. else if (node.kind !== 157 /* Decorator */) {
  55517. ts.forEach(node.arguments, function (argument) {
  55518. checkExpression(argument);
  55519. });
  55520. }
  55521. return anySignature;
  55522. }
  55523. function resolveErrorCall(node) {
  55524. resolveUntypedCall(node);
  55525. return unknownSignature;
  55526. }
  55527. // Re-order candidate signatures into the result array. Assumes the result array to be empty.
  55528. // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
  55529. // A nit here is that we reorder only signatures that belong to the same symbol,
  55530. // so order how inherited signatures are processed is still preserved.
  55531. // interface A { (x: string): void }
  55532. // interface B extends A { (x: 'foo'): string }
  55533. // const b: B;
  55534. // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
  55535. function reorderCandidates(signatures, result, callChainFlags) {
  55536. var lastParent;
  55537. var lastSymbol;
  55538. var cutoffIndex = 0;
  55539. var index;
  55540. var specializedIndex = -1;
  55541. var spliceIndex;
  55542. ts.Debug.assert(!result.length);
  55543. for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
  55544. var signature = signatures_7[_i];
  55545. var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
  55546. var parent = signature.declaration && signature.declaration.parent;
  55547. if (!lastSymbol || symbol === lastSymbol) {
  55548. if (lastParent && parent === lastParent) {
  55549. index = index + 1;
  55550. }
  55551. else {
  55552. lastParent = parent;
  55553. index = cutoffIndex;
  55554. }
  55555. }
  55556. else {
  55557. // current declaration belongs to a different symbol
  55558. // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
  55559. index = cutoffIndex = result.length;
  55560. lastParent = parent;
  55561. }
  55562. lastSymbol = symbol;
  55563. // specialized signatures always need to be placed before non-specialized signatures regardless
  55564. // of the cutoff position; see GH#1133
  55565. if (signatureHasLiteralTypes(signature)) {
  55566. specializedIndex++;
  55567. spliceIndex = specializedIndex;
  55568. // The cutoff index always needs to be greater than or equal to the specialized signature index
  55569. // in order to prevent non-specialized signatures from being added before a specialized
  55570. // signature.
  55571. cutoffIndex++;
  55572. }
  55573. else {
  55574. spliceIndex = index;
  55575. }
  55576. result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
  55577. }
  55578. }
  55579. function isSpreadArgument(arg) {
  55580. return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
  55581. }
  55582. function getSpreadArgumentIndex(args) {
  55583. return ts.findIndex(args, isSpreadArgument);
  55584. }
  55585. function acceptsVoid(t) {
  55586. return !!(t.flags & 16384 /* Void */);
  55587. }
  55588. function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
  55589. if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
  55590. var argCount;
  55591. var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
  55592. var effectiveParameterCount = getParameterCount(signature);
  55593. var effectiveMinimumArguments = getMinArgumentCount(signature);
  55594. if (node.kind === 198 /* TaggedTemplateExpression */) {
  55595. argCount = args.length;
  55596. if (node.template.kind === 211 /* TemplateExpression */) {
  55597. // If a tagged template expression lacks a tail literal, the call is incomplete.
  55598. // Specifically, a template only can end in a TemplateTail or a Missing literal.
  55599. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
  55600. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
  55601. }
  55602. else {
  55603. // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
  55604. // then this might actually turn out to be a TemplateHead in the future;
  55605. // so we consider the call to be incomplete.
  55606. var templateLiteral = node.template;
  55607. ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
  55608. callIsIncomplete = !!templateLiteral.isUnterminated;
  55609. }
  55610. }
  55611. else if (node.kind === 157 /* Decorator */) {
  55612. argCount = getDecoratorArgumentCount(node, signature);
  55613. }
  55614. else if (ts.isJsxOpeningLikeElement(node)) {
  55615. callIsIncomplete = node.attributes.end === node.end;
  55616. if (callIsIncomplete) {
  55617. return true;
  55618. }
  55619. argCount = effectiveMinimumArguments === 0 ? args.length : 1;
  55620. effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
  55621. effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
  55622. }
  55623. else {
  55624. if (!node.arguments) {
  55625. // This only happens when we have something of the form: 'new C'
  55626. ts.Debug.assert(node.kind === 197 /* NewExpression */);
  55627. return getMinArgumentCount(signature) === 0;
  55628. }
  55629. argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
  55630. // If we are missing the close parenthesis, the call is incomplete.
  55631. callIsIncomplete = node.arguments.end === node.end;
  55632. // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
  55633. var spreadArgIndex = getSpreadArgumentIndex(args);
  55634. if (spreadArgIndex >= 0) {
  55635. return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
  55636. }
  55637. }
  55638. // Too many arguments implies incorrect arity.
  55639. if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
  55640. return false;
  55641. }
  55642. // If the call is incomplete, we should skip the lower bound check.
  55643. // JSX signatures can have extra parameters provided by the library which we don't check
  55644. if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
  55645. return true;
  55646. }
  55647. for (var i = argCount; i < effectiveMinimumArguments; i++) {
  55648. var type = getTypeAtPosition(signature, i);
  55649. if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
  55650. return false;
  55651. }
  55652. }
  55653. return true;
  55654. }
  55655. function hasCorrectTypeArgumentArity(signature, typeArguments) {
  55656. // If the user supplied type arguments, but the number of type arguments does not match
  55657. // the declared number of type parameters, the call has an incorrect arity.
  55658. var numTypeParameters = ts.length(signature.typeParameters);
  55659. var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
  55660. return !ts.some(typeArguments) ||
  55661. (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
  55662. }
  55663. // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
  55664. function getSingleCallSignature(type) {
  55665. return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
  55666. }
  55667. function getSingleCallOrConstructSignature(type) {
  55668. return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
  55669. getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
  55670. }
  55671. function getSingleSignature(type, kind, allowMembers) {
  55672. if (type.flags & 524288 /* Object */) {
  55673. var resolved = resolveStructuredTypeMembers(type);
  55674. if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
  55675. if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
  55676. return resolved.callSignatures[0];
  55677. }
  55678. if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
  55679. return resolved.constructSignatures[0];
  55680. }
  55681. }
  55682. }
  55683. return undefined;
  55684. }
  55685. // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
  55686. function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
  55687. var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
  55688. // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
  55689. // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
  55690. // for T but leave it possible to later infer '[any]' back to A.
  55691. var restType = getEffectiveRestType(contextualSignature);
  55692. var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
  55693. var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
  55694. applyToParameterTypes(sourceSignature, signature, function (source, target) {
  55695. // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
  55696. inferTypes(context.inferences, source, target);
  55697. });
  55698. if (!inferenceContext) {
  55699. applyToReturnTypes(contextualSignature, signature, function (source, target) {
  55700. inferTypes(context.inferences, source, target, 32 /* ReturnType */);
  55701. });
  55702. }
  55703. return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
  55704. }
  55705. function inferJsxTypeArguments(node, signature, checkMode, context) {
  55706. var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
  55707. var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
  55708. inferTypes(context.inferences, checkAttrType, paramType);
  55709. return getInferredTypes(context);
  55710. }
  55711. function inferTypeArguments(node, signature, args, checkMode, context) {
  55712. if (ts.isJsxOpeningLikeElement(node)) {
  55713. return inferJsxTypeArguments(node, signature, checkMode, context);
  55714. }
  55715. // If a contextual type is available, infer from that type to the return type of the call expression. For
  55716. // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
  55717. // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
  55718. // return type of 'wrap'.
  55719. if (node.kind !== 157 /* Decorator */) {
  55720. var contextualType = getContextualType(node);
  55721. if (contextualType) {
  55722. // We clone the inference context to avoid disturbing a resolution in progress for an
  55723. // outer call expression. Effectively we just want a snapshot of whatever has been
  55724. // inferred for any outer call expression so far.
  55725. var outerContext = getInferenceContext(node);
  55726. var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
  55727. var instantiatedType = instantiateType(contextualType, outerMapper);
  55728. // If the contextual type is a generic function type with a single call signature, we
  55729. // instantiate the type with its own type parameters and type arguments. This ensures that
  55730. // the type parameters are not erased to type any during type inference such that they can
  55731. // be inferred as actual types from the contextual type. For example:
  55732. // declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
  55733. // const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
  55734. // Above, the type of the 'value' parameter is inferred to be 'A'.
  55735. var contextualSignature = getSingleCallSignature(instantiatedType);
  55736. var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
  55737. getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
  55738. instantiatedType;
  55739. var inferenceTargetType = getReturnTypeOfSignature(signature);
  55740. // Inferences made from return types have lower priority than all other inferences.
  55741. inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
  55742. // Create a type mapper for instantiating generic contextual types using the inferences made
  55743. // from the return type. We need a separate inference pass here because (a) instantiation of
  55744. // the source type uses the outer context's return mapper (which excludes inferences made from
  55745. // outer arguments), and (b) we don't want any further inferences going into this context.
  55746. var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
  55747. var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
  55748. inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
  55749. context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
  55750. }
  55751. }
  55752. var thisType = getThisTypeOfSignature(signature);
  55753. if (thisType) {
  55754. var thisArgumentNode = getThisArgumentOfCall(node);
  55755. var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
  55756. inferTypes(context.inferences, thisArgumentType, thisType);
  55757. }
  55758. var restType = getNonArrayRestType(signature);
  55759. var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
  55760. for (var i = 0; i < argCount; i++) {
  55761. var arg = args[i];
  55762. if (arg.kind !== 215 /* OmittedExpression */) {
  55763. var paramType = getTypeAtPosition(signature, i);
  55764. var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
  55765. inferTypes(context.inferences, argType, paramType);
  55766. }
  55767. }
  55768. if (restType) {
  55769. var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
  55770. inferTypes(context.inferences, spreadType, restType);
  55771. }
  55772. return getInferredTypes(context);
  55773. }
  55774. function getArrayifiedType(type) {
  55775. return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
  55776. type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
  55777. isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
  55778. createArrayType(getIndexedAccessType(type, numberType));
  55779. }
  55780. function getSpreadArgumentType(args, index, argCount, restType, context) {
  55781. if (index >= argCount - 1) {
  55782. var arg = args[argCount - 1];
  55783. if (isSpreadArgument(arg)) {
  55784. // We are inferring from a spread expression in the last argument position, i.e. both the parameter
  55785. // and the argument are ...x forms.
  55786. return arg.kind === 220 /* SyntheticExpression */ ?
  55787. createArrayType(arg.type) :
  55788. getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
  55789. }
  55790. }
  55791. var types = [];
  55792. var spreadIndex = -1;
  55793. for (var i = index; i < argCount; i++) {
  55794. var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
  55795. var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
  55796. if (spreadIndex < 0 && isSpreadArgument(args[i])) {
  55797. spreadIndex = i - index;
  55798. }
  55799. var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
  55800. types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
  55801. }
  55802. return spreadIndex < 0 ?
  55803. createTupleType(types) :
  55804. createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
  55805. }
  55806. function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
  55807. var isJavascript = ts.isInJSFile(signature.declaration);
  55808. var typeParameters = signature.typeParameters;
  55809. var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
  55810. var mapper;
  55811. for (var i = 0; i < typeArgumentNodes.length; i++) {
  55812. ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
  55813. var constraint = getConstraintOfTypeParameter(typeParameters[i]);
  55814. if (constraint) {
  55815. var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
  55816. var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
  55817. if (!mapper) {
  55818. mapper = createTypeMapper(typeParameters, typeArgumentTypes);
  55819. }
  55820. var typeArgument = typeArgumentTypes[i];
  55821. if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
  55822. return undefined;
  55823. }
  55824. }
  55825. }
  55826. return typeArgumentTypes;
  55827. }
  55828. function getJsxReferenceKind(node) {
  55829. if (isJsxIntrinsicIdentifier(node.tagName)) {
  55830. return 2 /* Mixed */;
  55831. }
  55832. var tagType = getApparentType(checkExpression(node.tagName));
  55833. if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
  55834. return 0 /* Component */;
  55835. }
  55836. if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
  55837. return 1 /* Function */;
  55838. }
  55839. return 2 /* Mixed */;
  55840. }
  55841. /**
  55842. * Check if the given signature can possibly be a signature called by the JSX opening-like element.
  55843. * @param node a JSX opening-like element we are trying to figure its call signature
  55844. * @param signature a candidate signature we are trying whether it is a call signature
  55845. * @param relation a relationship to check parameter and argument type
  55846. */
  55847. function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
  55848. // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
  55849. // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
  55850. // can be specified by users through attributes property.
  55851. var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
  55852. var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
  55853. return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes,
  55854. /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
  55855. }
  55856. function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
  55857. var errorOutputContainer = { errors: undefined, skipLogging: true };
  55858. if (ts.isJsxOpeningLikeElement(node)) {
  55859. if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
  55860. ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
  55861. return errorOutputContainer.errors || ts.emptyArray;
  55862. }
  55863. return undefined;
  55864. }
  55865. var thisType = getThisTypeOfSignature(signature);
  55866. if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
  55867. // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
  55868. // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
  55869. // If the expression is a new expression, then the check is skipped.
  55870. var thisArgumentNode = getThisArgumentOfCall(node);
  55871. var thisArgumentType = void 0;
  55872. if (thisArgumentNode) {
  55873. thisArgumentType = checkExpression(thisArgumentNode);
  55874. if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
  55875. thisArgumentType = getNonNullableType(thisArgumentType);
  55876. }
  55877. else if (ts.isOptionalChain(thisArgumentNode.parent)) {
  55878. thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
  55879. }
  55880. }
  55881. else {
  55882. thisArgumentType = voidType;
  55883. }
  55884. var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
  55885. var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
  55886. if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
  55887. ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
  55888. return errorOutputContainer.errors || ts.emptyArray;
  55889. }
  55890. }
  55891. var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
  55892. var restType = getNonArrayRestType(signature);
  55893. var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
  55894. for (var i = 0; i < argCount; i++) {
  55895. var arg = args[i];
  55896. if (arg.kind !== 215 /* OmittedExpression */) {
  55897. var paramType = getTypeAtPosition(signature, i);
  55898. var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
  55899. // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
  55900. // we obtain the regular type of any object literal arguments because we may not have inferred complete
  55901. // parameter types yet and therefore excess property checks may yield false positives (see #17041).
  55902. var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
  55903. if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
  55904. ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
  55905. maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
  55906. return errorOutputContainer.errors || ts.emptyArray;
  55907. }
  55908. }
  55909. }
  55910. if (restType) {
  55911. var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
  55912. var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
  55913. if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
  55914. ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
  55915. maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
  55916. return errorOutputContainer.errors || ts.emptyArray;
  55917. }
  55918. }
  55919. return undefined;
  55920. function maybeAddMissingAwaitInfo(errorNode, source, target) {
  55921. if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
  55922. // Bail if target is Promise-like---something else is wrong
  55923. if (getAwaitedTypeOfPromise(target)) {
  55924. return;
  55925. }
  55926. var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
  55927. if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
  55928. ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
  55929. }
  55930. }
  55931. }
  55932. }
  55933. /**
  55934. * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
  55935. */
  55936. function getThisArgumentOfCall(node) {
  55937. if (node.kind === 196 /* CallExpression */) {
  55938. var callee = ts.skipOuterExpressions(node.expression);
  55939. if (ts.isAccessExpression(callee)) {
  55940. return callee.expression;
  55941. }
  55942. }
  55943. }
  55944. function createSyntheticExpression(parent, type, isSpread) {
  55945. var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
  55946. result.parent = parent;
  55947. result.type = type;
  55948. result.isSpread = isSpread || false;
  55949. return result;
  55950. }
  55951. /**
  55952. * Returns the effective arguments for an expression that works like a function invocation.
  55953. */
  55954. function getEffectiveCallArguments(node) {
  55955. if (node.kind === 198 /* TaggedTemplateExpression */) {
  55956. var template = node.template;
  55957. var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
  55958. if (template.kind === 211 /* TemplateExpression */) {
  55959. ts.forEach(template.templateSpans, function (span) {
  55960. args_3.push(span.expression);
  55961. });
  55962. }
  55963. return args_3;
  55964. }
  55965. if (node.kind === 157 /* Decorator */) {
  55966. return getEffectiveDecoratorArguments(node);
  55967. }
  55968. if (ts.isJsxOpeningLikeElement(node)) {
  55969. return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
  55970. }
  55971. var args = node.arguments || ts.emptyArray;
  55972. var length = args.length;
  55973. if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
  55974. // We have a spread argument in the last position and no other spread arguments. If the type
  55975. // of the argument is a tuple type, spread the tuple elements into the argument list. We can
  55976. // call checkExpressionCached because spread expressions never have a contextual type.
  55977. var spreadArgument_1 = args[length - 1];
  55978. var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
  55979. if (isTupleType(type)) {
  55980. var typeArguments = getTypeArguments(type);
  55981. var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
  55982. var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
  55983. return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
  55984. }
  55985. }
  55986. return args;
  55987. }
  55988. /**
  55989. * Returns the synthetic argument list for a decorator invocation.
  55990. */
  55991. function getEffectiveDecoratorArguments(node) {
  55992. var parent = node.parent;
  55993. var expr = node.expression;
  55994. switch (parent.kind) {
  55995. case 245 /* ClassDeclaration */:
  55996. case 214 /* ClassExpression */:
  55997. // For a class decorator, the `target` is the type of the class (e.g. the
  55998. // "static" or "constructor" side of the class).
  55999. return [
  56000. createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
  56001. ];
  56002. case 156 /* Parameter */:
  56003. // A parameter declaration decorator will have three arguments (see
  56004. // `ParameterDecorator` in core.d.ts).
  56005. var func = parent.parent;
  56006. return [
  56007. createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
  56008. createSyntheticExpression(expr, anyType),
  56009. createSyntheticExpression(expr, numberType)
  56010. ];
  56011. case 159 /* PropertyDeclaration */:
  56012. case 161 /* MethodDeclaration */:
  56013. case 163 /* GetAccessor */:
  56014. case 164 /* SetAccessor */:
  56015. // A method or accessor declaration decorator will have two or three arguments (see
  56016. // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
  56017. // for ES3, we will only pass two arguments.
  56018. var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
  56019. return [
  56020. createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
  56021. createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
  56022. createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
  56023. ];
  56024. }
  56025. return ts.Debug.fail();
  56026. }
  56027. /**
  56028. * Returns the argument count for a decorator node that works like a function invocation.
  56029. */
  56030. function getDecoratorArgumentCount(node, signature) {
  56031. switch (node.parent.kind) {
  56032. case 245 /* ClassDeclaration */:
  56033. case 214 /* ClassExpression */:
  56034. return 1;
  56035. case 159 /* PropertyDeclaration */:
  56036. return 2;
  56037. case 161 /* MethodDeclaration */:
  56038. case 163 /* GetAccessor */:
  56039. case 164 /* SetAccessor */:
  56040. // For ES3 or decorators with only two parameters we supply only two arguments
  56041. return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
  56042. case 156 /* Parameter */:
  56043. return 3;
  56044. default:
  56045. return ts.Debug.fail();
  56046. }
  56047. }
  56048. function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
  56049. var start;
  56050. var length;
  56051. var sourceFile = ts.getSourceFileOfNode(node);
  56052. if (ts.isPropertyAccessExpression(node.expression)) {
  56053. var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
  56054. start = nameSpan.start;
  56055. length = doNotIncludeArguments ? nameSpan.length : node.end - start;
  56056. }
  56057. else {
  56058. var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
  56059. start = expressionSpan.start;
  56060. length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
  56061. }
  56062. return { start: start, length: length, sourceFile: sourceFile };
  56063. }
  56064. function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
  56065. if (ts.isCallExpression(node)) {
  56066. var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length;
  56067. return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3);
  56068. }
  56069. else {
  56070. return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
  56071. }
  56072. }
  56073. function getArgumentArityError(node, signatures, args) {
  56074. var min = Number.POSITIVE_INFINITY;
  56075. var max = Number.NEGATIVE_INFINITY;
  56076. var belowArgCount = Number.NEGATIVE_INFINITY;
  56077. var aboveArgCount = Number.POSITIVE_INFINITY;
  56078. var argCount = args.length;
  56079. var closestSignature;
  56080. for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
  56081. var sig = signatures_8[_i];
  56082. var minCount = getMinArgumentCount(sig);
  56083. var maxCount = getParameterCount(sig);
  56084. if (minCount < argCount && minCount > belowArgCount)
  56085. belowArgCount = minCount;
  56086. if (argCount < maxCount && maxCount < aboveArgCount)
  56087. aboveArgCount = maxCount;
  56088. if (minCount < min) {
  56089. min = minCount;
  56090. closestSignature = sig;
  56091. }
  56092. max = Math.max(max, maxCount);
  56093. }
  56094. var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
  56095. var paramRange = hasRestParameter ? min :
  56096. min < max ? min + "-" + max :
  56097. min;
  56098. var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
  56099. if (argCount <= max && hasSpreadArgument) {
  56100. argCount--;
  56101. }
  56102. var spanArray;
  56103. var related;
  56104. var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
  56105. hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
  56106. ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
  56107. if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
  56108. var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
  56109. if (paramDecl) {
  56110. related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined);
  56111. }
  56112. }
  56113. if (min < argCount && argCount < max) {
  56114. return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
  56115. }
  56116. if (!hasSpreadArgument && argCount < min) {
  56117. var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
  56118. return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
  56119. }
  56120. if (hasRestParameter || hasSpreadArgument) {
  56121. spanArray = ts.createNodeArray(args);
  56122. if (hasSpreadArgument && argCount) {
  56123. var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
  56124. spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
  56125. }
  56126. }
  56127. else {
  56128. spanArray = ts.createNodeArray(args.slice(max));
  56129. }
  56130. spanArray.pos = ts.first(spanArray).pos;
  56131. spanArray.end = ts.last(spanArray).end;
  56132. if (spanArray.end === spanArray.pos) {
  56133. spanArray.end++;
  56134. }
  56135. var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
  56136. return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
  56137. }
  56138. function getTypeArgumentArityError(node, signatures, typeArguments) {
  56139. var argCount = typeArguments.length;
  56140. // No overloads exist
  56141. if (signatures.length === 1) {
  56142. var sig = signatures[0];
  56143. var min_1 = getMinTypeArgumentCount(sig.typeParameters);
  56144. var max = ts.length(sig.typeParameters);
  56145. return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount);
  56146. }
  56147. // Overloads exist
  56148. var belowArgCount = -Infinity;
  56149. var aboveArgCount = Infinity;
  56150. for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
  56151. var sig = signatures_9[_i];
  56152. var min_2 = getMinTypeArgumentCount(sig.typeParameters);
  56153. var max = ts.length(sig.typeParameters);
  56154. if (min_2 > argCount) {
  56155. aboveArgCount = Math.min(aboveArgCount, min_2);
  56156. }
  56157. else if (max < argCount) {
  56158. belowArgCount = Math.max(belowArgCount, max);
  56159. }
  56160. }
  56161. if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
  56162. return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount);
  56163. }
  56164. return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
  56165. }
  56166. function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
  56167. var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
  56168. var isDecorator = node.kind === 157 /* Decorator */;
  56169. var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
  56170. var reportErrors = !candidatesOutArray;
  56171. var typeArguments;
  56172. if (!isDecorator) {
  56173. typeArguments = node.typeArguments;
  56174. // We already perform checking on the type arguments on the class declaration itself.
  56175. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
  56176. ts.forEach(typeArguments, checkSourceElement);
  56177. }
  56178. }
  56179. var candidates = candidatesOutArray || [];
  56180. // reorderCandidates fills up the candidates array directly
  56181. reorderCandidates(signatures, candidates, callChainFlags);
  56182. if (!candidates.length) {
  56183. if (reportErrors) {
  56184. diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
  56185. }
  56186. return resolveErrorCall(node);
  56187. }
  56188. var args = getEffectiveCallArguments(node);
  56189. // The excludeArgument array contains true for each context sensitive argument (an argument
  56190. // is context sensitive it is susceptible to a one-time permanent contextual typing).
  56191. //
  56192. // The idea is that we will perform type argument inference & assignability checking once
  56193. // without using the susceptible parameters that are functions, and once more for those
  56194. // parameters, contextually typing each as we go along.
  56195. //
  56196. // For a tagged template, then the first argument be 'undefined' if necessary because it
  56197. // represents a TemplateStringsArray.
  56198. //
  56199. // For a decorator, no arguments are susceptible to contextual typing due to the fact
  56200. // decorators are applied to a declaration by the emitter, and not to an expression.
  56201. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
  56202. var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
  56203. // The following variables are captured and modified by calls to chooseOverload.
  56204. // If overload resolution or type argument inference fails, we want to report the
  56205. // best error possible. The best error is one which says that an argument was not
  56206. // assignable to a parameter. This implies that everything else about the overload
  56207. // was fine. So if there is any overload that is only incorrect because of an
  56208. // argument, we will report an error on that one.
  56209. //
  56210. // function foo(s: string): void;
  56211. // function foo(n: number): void; // Report argument error on this overload
  56212. // function foo(): void;
  56213. // foo(true);
  56214. //
  56215. // If none of the overloads even made it that far, there are two possibilities.
  56216. // There was a problem with type arguments for some overload, in which case
  56217. // report an error on that. Or none of the overloads even had correct arity,
  56218. // in which case give an arity error.
  56219. //
  56220. // function foo<T extends string>(x: T): void; // Report type argument error
  56221. // function foo(): void;
  56222. // foo<number>(0);
  56223. //
  56224. var candidatesForArgumentError;
  56225. var candidateForArgumentArityError;
  56226. var candidateForTypeArgumentError;
  56227. var result;
  56228. // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
  56229. // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
  56230. var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
  56231. // Section 4.12.1:
  56232. // if the candidate list contains one or more signatures for which the type of each argument
  56233. // expression is a subtype of each corresponding parameter type, the return type of the first
  56234. // of those signatures becomes the return type of the function call.
  56235. // Otherwise, the return type of the first signature in the candidate list becomes the return
  56236. // type of the function call.
  56237. //
  56238. // Whether the call is an error is determined by assignability of the arguments. The subtype pass
  56239. // is just important for choosing the best signature. So in the case where there is only one
  56240. // signature, the subtype pass is useless. So skipping it is an optimization.
  56241. if (candidates.length > 1) {
  56242. result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
  56243. }
  56244. if (!result) {
  56245. result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
  56246. }
  56247. if (result) {
  56248. return result;
  56249. }
  56250. // No signatures were applicable. Now report errors based on the last applicable signature with
  56251. // no arguments excluded from assignability checks.
  56252. // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
  56253. // skip the checkApplicableSignature check.
  56254. if (reportErrors) {
  56255. if (candidatesForArgumentError) {
  56256. if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
  56257. var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
  56258. var chain_1;
  56259. if (candidatesForArgumentError.length > 3) {
  56260. chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
  56261. chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
  56262. }
  56263. var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
  56264. if (diags) {
  56265. for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
  56266. var d = diags_1[_i];
  56267. if (last_2.declaration && candidatesForArgumentError.length > 3) {
  56268. ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
  56269. }
  56270. diagnostics.add(d);
  56271. }
  56272. }
  56273. else {
  56274. ts.Debug.fail("No error for last overload signature");
  56275. }
  56276. }
  56277. else {
  56278. var allDiagnostics = [];
  56279. var max = 0;
  56280. var min_3 = Number.MAX_VALUE;
  56281. var minIndex = 0;
  56282. var i_1 = 0;
  56283. var _loop_15 = function (c) {
  56284. var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); };
  56285. var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
  56286. if (diags_2) {
  56287. if (diags_2.length <= min_3) {
  56288. min_3 = diags_2.length;
  56289. minIndex = i_1;
  56290. }
  56291. max = Math.max(max, diags_2.length);
  56292. allDiagnostics.push(diags_2);
  56293. }
  56294. else {
  56295. ts.Debug.fail("No error for 3 or fewer overload signatures");
  56296. }
  56297. i_1++;
  56298. };
  56299. for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
  56300. var c = candidatesForArgumentError_1[_a];
  56301. _loop_15(c);
  56302. }
  56303. var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
  56304. ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
  56305. var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call);
  56306. var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
  56307. if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) {
  56308. var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length;
  56309. diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
  56310. }
  56311. else {
  56312. diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
  56313. }
  56314. }
  56315. }
  56316. else if (candidateForArgumentArityError) {
  56317. diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
  56318. }
  56319. else if (candidateForTypeArgumentError) {
  56320. checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
  56321. }
  56322. else {
  56323. var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
  56324. if (signaturesWithCorrectTypeArgumentArity.length === 0) {
  56325. diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
  56326. }
  56327. else if (!isDecorator) {
  56328. diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
  56329. }
  56330. else if (fallbackError) {
  56331. diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
  56332. }
  56333. }
  56334. }
  56335. return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
  56336. function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
  56337. if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
  56338. candidatesForArgumentError = undefined;
  56339. candidateForArgumentArityError = undefined;
  56340. candidateForTypeArgumentError = undefined;
  56341. if (isSingleNonGenericCandidate) {
  56342. var candidate = candidates[0];
  56343. if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
  56344. return undefined;
  56345. }
  56346. if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
  56347. candidatesForArgumentError = [candidate];
  56348. return undefined;
  56349. }
  56350. return candidate;
  56351. }
  56352. for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
  56353. var candidate = candidates[candidateIndex];
  56354. if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
  56355. continue;
  56356. }
  56357. var checkCandidate = void 0;
  56358. var inferenceContext = void 0;
  56359. if (candidate.typeParameters) {
  56360. var typeArgumentTypes = void 0;
  56361. if (ts.some(typeArguments)) {
  56362. typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
  56363. if (!typeArgumentTypes) {
  56364. candidateForTypeArgumentError = candidate;
  56365. continue;
  56366. }
  56367. }
  56368. else {
  56369. inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
  56370. typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
  56371. argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
  56372. }
  56373. checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
  56374. // If the original signature has a generic rest type, instantiation may produce a
  56375. // signature with different arity and we need to perform another arity check.
  56376. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
  56377. candidateForArgumentArityError = checkCandidate;
  56378. continue;
  56379. }
  56380. }
  56381. else {
  56382. checkCandidate = candidate;
  56383. }
  56384. if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
  56385. // Give preference to error candidates that have no rest parameters (as they are more specific)
  56386. (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
  56387. continue;
  56388. }
  56389. if (argCheckMode) {
  56390. // If one or more context sensitive arguments were excluded, we start including
  56391. // them now (and keeping do so for any subsequent candidates) and perform a second
  56392. // round of type inference and applicability checking for this particular candidate.
  56393. argCheckMode = 0 /* Normal */;
  56394. if (inferenceContext) {
  56395. var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
  56396. checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
  56397. // If the original signature has a generic rest type, instantiation may produce a
  56398. // signature with different arity and we need to perform another arity check.
  56399. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
  56400. candidateForArgumentArityError = checkCandidate;
  56401. continue;
  56402. }
  56403. }
  56404. if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
  56405. // Give preference to error candidates that have no rest parameters (as they are more specific)
  56406. (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
  56407. continue;
  56408. }
  56409. }
  56410. candidates[candidateIndex] = checkCandidate;
  56411. return checkCandidate;
  56412. }
  56413. return undefined;
  56414. }
  56415. }
  56416. // No signature was applicable. We have already reported the errors for the invalid signature.
  56417. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
  56418. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
  56419. ts.Debug.assert(candidates.length > 0); // Else should not have called this.
  56420. // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
  56421. // Don't do this if there is a `candidatesOutArray`,
  56422. // because then we want the chosen best candidate to be one of the overloads, not a combination.
  56423. return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
  56424. ? pickLongestCandidateSignature(node, candidates, args)
  56425. : createUnionOfSignaturesForOverloadFailure(candidates);
  56426. }
  56427. function createUnionOfSignaturesForOverloadFailure(candidates) {
  56428. var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
  56429. var thisParameter;
  56430. if (thisParameters.length) {
  56431. thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
  56432. }
  56433. var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
  56434. var parameters = [];
  56435. var _loop_16 = function (i) {
  56436. var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
  56437. i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
  56438. i < s.parameters.length ? s.parameters[i] : undefined; });
  56439. ts.Debug.assert(symbols.length !== 0);
  56440. parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
  56441. };
  56442. for (var i = 0; i < maxNonRestParam; i++) {
  56443. _loop_16(i);
  56444. }
  56445. var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
  56446. var flags = 0 /* None */;
  56447. if (restParameterSymbols.length !== 0) {
  56448. var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
  56449. parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
  56450. flags |= 1 /* HasRestParameter */;
  56451. }
  56452. if (candidates.some(signatureHasLiteralTypes)) {
  56453. flags |= 2 /* HasLiteralTypes */;
  56454. }
  56455. return createSignature(candidates[0].declaration,
  56456. /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
  56457. thisParameter, parameters,
  56458. /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)),
  56459. /*typePredicate*/ undefined, minArgumentCount, flags);
  56460. }
  56461. function getNumNonRestParameters(signature) {
  56462. var numParams = signature.parameters.length;
  56463. return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
  56464. }
  56465. function createCombinedSymbolFromTypes(sources, types) {
  56466. return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
  56467. }
  56468. function createCombinedSymbolForOverloadFailure(sources, type) {
  56469. // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
  56470. return createSymbolWithType(ts.first(sources), type);
  56471. }
  56472. function pickLongestCandidateSignature(node, candidates, args) {
  56473. // Pick the longest signature. This way we can get a contextual type for cases like:
  56474. // declare function f(a: { xa: number; xb: number; }, b: number);
  56475. // f({ |
  56476. // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
  56477. // declare function f<T>(k: keyof T);
  56478. // f<Foo>("
  56479. var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
  56480. var candidate = candidates[bestIndex];
  56481. var typeParameters = candidate.typeParameters;
  56482. if (!typeParameters) {
  56483. return candidate;
  56484. }
  56485. var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
  56486. var instantiated = typeArgumentNodes
  56487. ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
  56488. : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
  56489. candidates[bestIndex] = instantiated;
  56490. return instantiated;
  56491. }
  56492. function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
  56493. var typeArguments = typeArgumentNodes.map(getTypeOfNode);
  56494. while (typeArguments.length > typeParameters.length) {
  56495. typeArguments.pop();
  56496. }
  56497. while (typeArguments.length < typeParameters.length) {
  56498. typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
  56499. }
  56500. return typeArguments;
  56501. }
  56502. function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
  56503. var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
  56504. var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
  56505. return createSignatureInstantiation(candidate, typeArgumentTypes);
  56506. }
  56507. function getLongestCandidateIndex(candidates, argsCount) {
  56508. var maxParamsIndex = -1;
  56509. var maxParams = -1;
  56510. for (var i = 0; i < candidates.length; i++) {
  56511. var candidate = candidates[i];
  56512. var paramCount = getParameterCount(candidate);
  56513. if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
  56514. return i;
  56515. }
  56516. if (paramCount > maxParams) {
  56517. maxParams = paramCount;
  56518. maxParamsIndex = i;
  56519. }
  56520. }
  56521. return maxParamsIndex;
  56522. }
  56523. function resolveCallExpression(node, candidatesOutArray, checkMode) {
  56524. if (node.expression.kind === 102 /* SuperKeyword */) {
  56525. var superType = checkSuperExpression(node.expression);
  56526. if (isTypeAny(superType)) {
  56527. for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
  56528. var arg = _a[_i];
  56529. checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
  56530. }
  56531. return anySignature;
  56532. }
  56533. if (superType !== errorType) {
  56534. // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
  56535. // with the type arguments specified in the extends clause.
  56536. var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
  56537. if (baseTypeNode) {
  56538. var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
  56539. return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
  56540. }
  56541. }
  56542. return resolveUntypedCall(node);
  56543. }
  56544. var callChainFlags;
  56545. var funcType = checkExpression(node.expression);
  56546. if (ts.isCallChain(node)) {
  56547. var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
  56548. callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
  56549. ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
  56550. 4 /* IsInnerCallChain */;
  56551. funcType = nonOptionalType;
  56552. }
  56553. else {
  56554. callChainFlags = 0 /* None */;
  56555. }
  56556. funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
  56557. if (funcType === silentNeverType) {
  56558. return silentNeverSignature;
  56559. }
  56560. var apparentType = getApparentType(funcType);
  56561. if (apparentType === errorType) {
  56562. // Another error has already been reported
  56563. return resolveErrorCall(node);
  56564. }
  56565. // Technically, this signatures list may be incomplete. We are taking the apparent type,
  56566. // but we are not including call signatures that may have been added to the Object or
  56567. // Function interface, since they have none by default. This is a bit of a leap of faith
  56568. // that the user will not add any.
  56569. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
  56570. var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
  56571. // TS 1.0 Spec: 4.12
  56572. // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
  56573. // types are provided for the argument expressions, and the result is always of type Any.
  56574. if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
  56575. // The unknownType indicates that an error already occurred (and was reported). No
  56576. // need to report another error in this case.
  56577. if (funcType !== errorType && node.typeArguments) {
  56578. error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
  56579. }
  56580. return resolveUntypedCall(node);
  56581. }
  56582. // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
  56583. // TypeScript employs overload resolution in typed function calls in order to support functions
  56584. // with multiple call signatures.
  56585. if (!callSignatures.length) {
  56586. if (numConstructSignatures) {
  56587. error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
  56588. }
  56589. else {
  56590. var relatedInformation = void 0;
  56591. if (node.arguments.length === 1) {
  56592. var text = ts.getSourceFileOfNode(node).text;
  56593. if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
  56594. relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon);
  56595. }
  56596. }
  56597. invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
  56598. }
  56599. return resolveErrorCall(node);
  56600. }
  56601. // When a call to a generic function is an argument to an outer call to a generic function for which
  56602. // inference is in process, we have a choice to make. If the inner call relies on inferences made from
  56603. // its contextual type to its return type, deferring the inner call processing allows the best possible
  56604. // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
  56605. // the inner call, the inner call should be processed early. There's no sure way to know which choice is
  56606. // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
  56607. // If no type arguments are specified in the inner call and at least one call signature is generic and
  56608. // returns a function type, we choose to defer processing. This narrowly permits function composition
  56609. // operators to flow inferences through return types, but otherwise processes calls right away. We
  56610. // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
  56611. // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
  56612. // from which we never make inferences).
  56613. if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
  56614. skippedGenericFunction(node, checkMode);
  56615. return resolvingSignature;
  56616. }
  56617. // If the function is explicitly marked with `@class`, then it must be constructed.
  56618. if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
  56619. error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
  56620. return resolveErrorCall(node);
  56621. }
  56622. return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
  56623. }
  56624. function isGenericFunctionReturningFunction(signature) {
  56625. return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
  56626. }
  56627. /**
  56628. * TS 1.0 spec: 4.12
  56629. * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
  56630. * but is a subtype of the Function interface, the call is an untyped function call.
  56631. */
  56632. function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
  56633. // We exclude union types because we may have a union of function types that happen to have no common signatures.
  56634. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
  56635. !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
  56636. }
  56637. function resolveNewExpression(node, candidatesOutArray, checkMode) {
  56638. if (node.arguments && languageVersion < 1 /* ES5 */) {
  56639. var spreadIndex = getSpreadArgumentIndex(node.arguments);
  56640. if (spreadIndex >= 0) {
  56641. error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
  56642. }
  56643. }
  56644. var expressionType = checkNonNullExpression(node.expression);
  56645. if (expressionType === silentNeverType) {
  56646. return silentNeverSignature;
  56647. }
  56648. // If expressionType's apparent type(section 3.8.1) is an object type with one or
  56649. // more construct signatures, the expression is processed in the same manner as a
  56650. // function call, but using the construct signatures as the initial set of candidate
  56651. // signatures for overload resolution. The result type of the function call becomes
  56652. // the result type of the operation.
  56653. expressionType = getApparentType(expressionType);
  56654. if (expressionType === errorType) {
  56655. // Another error has already been reported
  56656. return resolveErrorCall(node);
  56657. }
  56658. // TS 1.0 spec: 4.11
  56659. // If expressionType is of type Any, Args can be any argument
  56660. // list and the result of the operation is of type Any.
  56661. if (isTypeAny(expressionType)) {
  56662. if (node.typeArguments) {
  56663. error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
  56664. }
  56665. return resolveUntypedCall(node);
  56666. }
  56667. // Technically, this signatures list may be incomplete. We are taking the apparent type,
  56668. // but we are not including construct signatures that may have been added to the Object or
  56669. // Function interface, since they have none by default. This is a bit of a leap of faith
  56670. // that the user will not add any.
  56671. var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
  56672. if (constructSignatures.length) {
  56673. if (!isConstructorAccessible(node, constructSignatures[0])) {
  56674. return resolveErrorCall(node);
  56675. }
  56676. // If the expression is a class of abstract type, then it cannot be instantiated.
  56677. // Note, only class declarations can be declared abstract.
  56678. // In the case of a merged class-module or class-interface declaration,
  56679. // only the class declaration node will have the Abstract flag set.
  56680. var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
  56681. if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
  56682. error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
  56683. return resolveErrorCall(node);
  56684. }
  56685. return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
  56686. }
  56687. // If expressionType's apparent type is an object type with no construct signatures but
  56688. // one or more call signatures, the expression is processed as a function call. A compile-time
  56689. // error occurs if the result of the function call is not Void. The type of the result of the
  56690. // operation is Any. It is an error to have a Void this type.
  56691. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
  56692. if (callSignatures.length) {
  56693. var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
  56694. if (!noImplicitAny) {
  56695. if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
  56696. error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
  56697. }
  56698. if (getThisTypeOfSignature(signature) === voidType) {
  56699. error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
  56700. }
  56701. }
  56702. return signature;
  56703. }
  56704. invocationError(node.expression, expressionType, 1 /* Construct */);
  56705. return resolveErrorCall(node);
  56706. }
  56707. function typeHasProtectedAccessibleBase(target, type) {
  56708. var baseTypes = getBaseTypes(type);
  56709. if (!ts.length(baseTypes)) {
  56710. return false;
  56711. }
  56712. var firstBase = baseTypes[0];
  56713. if (firstBase.flags & 2097152 /* Intersection */) {
  56714. var types = firstBase.types;
  56715. var mixinFlags = findMixins(types);
  56716. var i = 0;
  56717. for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
  56718. var intersectionMember = _a[_i];
  56719. // We want to ignore mixin ctors
  56720. if (!mixinFlags[i]) {
  56721. if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
  56722. if (intersectionMember.symbol === target) {
  56723. return true;
  56724. }
  56725. if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
  56726. return true;
  56727. }
  56728. }
  56729. }
  56730. i++;
  56731. }
  56732. return false;
  56733. }
  56734. if (firstBase.symbol === target) {
  56735. return true;
  56736. }
  56737. return typeHasProtectedAccessibleBase(target, firstBase);
  56738. }
  56739. function isConstructorAccessible(node, signature) {
  56740. if (!signature || !signature.declaration) {
  56741. return true;
  56742. }
  56743. var declaration = signature.declaration;
  56744. var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
  56745. // (1) Public constructors and (2) constructor functions are always accessible.
  56746. if (!modifiers || declaration.kind !== 162 /* Constructor */) {
  56747. return true;
  56748. }
  56749. var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
  56750. var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
  56751. // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
  56752. if (!isNodeWithinClass(node, declaringClassDeclaration)) {
  56753. var containingClass = ts.getContainingClass(node);
  56754. if (containingClass && modifiers & 16 /* Protected */) {
  56755. var containingType = getTypeOfNode(containingClass);
  56756. if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
  56757. return true;
  56758. }
  56759. }
  56760. if (modifiers & 8 /* Private */) {
  56761. error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
  56762. }
  56763. if (modifiers & 16 /* Protected */) {
  56764. error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
  56765. }
  56766. return false;
  56767. }
  56768. return true;
  56769. }
  56770. function invocationErrorDetails(apparentType, kind) {
  56771. var errorInfo;
  56772. var isCall = kind === 0 /* Call */;
  56773. var awaitedType = getAwaitedType(apparentType);
  56774. var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
  56775. if (apparentType.flags & 1048576 /* Union */) {
  56776. var types = apparentType.types;
  56777. var hasSignatures = false;
  56778. for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
  56779. var constituent = types_17[_i];
  56780. var signatures = getSignaturesOfType(constituent, kind);
  56781. if (signatures.length !== 0) {
  56782. hasSignatures = true;
  56783. if (errorInfo) {
  56784. // Bail early if we already have an error, no chance of "No constituent of type is callable"
  56785. break;
  56786. }
  56787. }
  56788. else {
  56789. // Error on the first non callable constituent only
  56790. if (!errorInfo) {
  56791. errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
  56792. ts.Diagnostics.Type_0_has_no_call_signatures :
  56793. ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
  56794. errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
  56795. ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
  56796. ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
  56797. }
  56798. if (hasSignatures) {
  56799. // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
  56800. break;
  56801. }
  56802. }
  56803. }
  56804. if (!hasSignatures) {
  56805. errorInfo = ts.chainDiagnosticMessages(
  56806. /* detials */ undefined, isCall ?
  56807. ts.Diagnostics.No_constituent_of_type_0_is_callable :
  56808. ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
  56809. }
  56810. if (!errorInfo) {
  56811. errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
  56812. ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
  56813. ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
  56814. }
  56815. }
  56816. else {
  56817. errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
  56818. ts.Diagnostics.Type_0_has_no_call_signatures :
  56819. ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
  56820. }
  56821. return {
  56822. messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
  56823. relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
  56824. };
  56825. }
  56826. function invocationError(errorTarget, apparentType, kind, relatedInformation) {
  56827. var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
  56828. var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
  56829. if (relatedInfo) {
  56830. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
  56831. }
  56832. if (ts.isCallExpression(errorTarget.parent)) {
  56833. var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length;
  56834. diagnostic.start = start;
  56835. diagnostic.length = length_6;
  56836. }
  56837. diagnostics.add(diagnostic);
  56838. invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
  56839. }
  56840. function invocationErrorRecovery(apparentType, kind, diagnostic) {
  56841. if (!apparentType.symbol) {
  56842. return;
  56843. }
  56844. var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
  56845. // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
  56846. // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site
  56847. if (importNode && !ts.isImportCall(importNode)) {
  56848. var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
  56849. if (!sigs || !sigs.length)
  56850. return;
  56851. ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
  56852. }
  56853. }
  56854. function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
  56855. var tagType = checkExpression(node.tag);
  56856. var apparentType = getApparentType(tagType);
  56857. if (apparentType === errorType) {
  56858. // Another error has already been reported
  56859. return resolveErrorCall(node);
  56860. }
  56861. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
  56862. var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
  56863. if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
  56864. return resolveUntypedCall(node);
  56865. }
  56866. if (!callSignatures.length) {
  56867. invocationError(node.tag, apparentType, 0 /* Call */);
  56868. return resolveErrorCall(node);
  56869. }
  56870. return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
  56871. }
  56872. /**
  56873. * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
  56874. */
  56875. function getDiagnosticHeadMessageForDecoratorResolution(node) {
  56876. switch (node.parent.kind) {
  56877. case 245 /* ClassDeclaration */:
  56878. case 214 /* ClassExpression */:
  56879. return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
  56880. case 156 /* Parameter */:
  56881. return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
  56882. case 159 /* PropertyDeclaration */:
  56883. return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
  56884. case 161 /* MethodDeclaration */:
  56885. case 163 /* GetAccessor */:
  56886. case 164 /* SetAccessor */:
  56887. return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
  56888. default:
  56889. return ts.Debug.fail();
  56890. }
  56891. }
  56892. /**
  56893. * Resolves a decorator as if it were a call expression.
  56894. */
  56895. function resolveDecorator(node, candidatesOutArray, checkMode) {
  56896. var funcType = checkExpression(node.expression);
  56897. var apparentType = getApparentType(funcType);
  56898. if (apparentType === errorType) {
  56899. return resolveErrorCall(node);
  56900. }
  56901. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
  56902. var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
  56903. if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
  56904. return resolveUntypedCall(node);
  56905. }
  56906. if (isPotentiallyUncalledDecorator(node, callSignatures)) {
  56907. var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
  56908. error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr);
  56909. return resolveErrorCall(node);
  56910. }
  56911. var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
  56912. if (!callSignatures.length) {
  56913. var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
  56914. var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
  56915. var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
  56916. if (errorDetails.relatedMessage) {
  56917. ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
  56918. }
  56919. diagnostics.add(diag);
  56920. invocationErrorRecovery(apparentType, 0 /* Call */, diag);
  56921. return resolveErrorCall(node);
  56922. }
  56923. return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
  56924. }
  56925. function createSignatureForJSXIntrinsic(node, result) {
  56926. var namespace = getJsxNamespaceAt(node);
  56927. var exports = namespace && getExportsOfSymbol(namespace);
  56928. // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
  56929. // file would probably be preferable.
  56930. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
  56931. var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
  56932. var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(125 /* AnyKeyword */));
  56933. var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
  56934. parameterSymbol.type = result;
  56935. return createSignature(declaration,
  56936. /*typeParameters*/ undefined,
  56937. /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType,
  56938. /*returnTypePredicate*/ undefined, 1, 0 /* None */);
  56939. }
  56940. function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
  56941. if (isJsxIntrinsicIdentifier(node.tagName)) {
  56942. var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
  56943. var fakeSignature = createSignatureForJSXIntrinsic(node, result);
  56944. checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
  56945. return fakeSignature;
  56946. }
  56947. var exprTypes = checkExpression(node.tagName);
  56948. var apparentType = getApparentType(exprTypes);
  56949. if (apparentType === errorType) {
  56950. return resolveErrorCall(node);
  56951. }
  56952. var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
  56953. if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
  56954. return resolveUntypedCall(node);
  56955. }
  56956. if (signatures.length === 0) {
  56957. // We found no signatures at all, which is an error
  56958. error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
  56959. return resolveErrorCall(node);
  56960. }
  56961. return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
  56962. }
  56963. /**
  56964. * Sometimes, we have a decorator that could accept zero arguments,
  56965. * but is receiving too many arguments as part of the decorator invocation.
  56966. * In those cases, a user may have meant to *call* the expression before using it as a decorator.
  56967. */
  56968. function isPotentiallyUncalledDecorator(decorator, signatures) {
  56969. return signatures.length && ts.every(signatures, function (signature) {
  56970. return signature.minArgumentCount === 0 &&
  56971. !signatureHasRestParameter(signature) &&
  56972. signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
  56973. });
  56974. }
  56975. function resolveSignature(node, candidatesOutArray, checkMode) {
  56976. switch (node.kind) {
  56977. case 196 /* CallExpression */:
  56978. return resolveCallExpression(node, candidatesOutArray, checkMode);
  56979. case 197 /* NewExpression */:
  56980. return resolveNewExpression(node, candidatesOutArray, checkMode);
  56981. case 198 /* TaggedTemplateExpression */:
  56982. return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
  56983. case 157 /* Decorator */:
  56984. return resolveDecorator(node, candidatesOutArray, checkMode);
  56985. case 268 /* JsxOpeningElement */:
  56986. case 267 /* JsxSelfClosingElement */:
  56987. return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
  56988. }
  56989. throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
  56990. }
  56991. /**
  56992. * Resolve a signature of a given call-like expression.
  56993. * @param node a call-like expression to try resolve a signature for
  56994. * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
  56995. * the function will fill it up with appropriate candidate signatures
  56996. * @return a signature of the call-like expression or undefined if one can't be found
  56997. */
  56998. function getResolvedSignature(node, candidatesOutArray, checkMode) {
  56999. var links = getNodeLinks(node);
  57000. // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
  57001. // However, it is possible that either candidatesOutArray was not passed in the first time,
  57002. // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
  57003. // to correctly fill the candidatesOutArray.
  57004. var cached = links.resolvedSignature;
  57005. if (cached && cached !== resolvingSignature && !candidatesOutArray) {
  57006. return cached;
  57007. }
  57008. links.resolvedSignature = resolvingSignature;
  57009. var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
  57010. // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
  57011. // resolution should be deferred.
  57012. if (result !== resolvingSignature) {
  57013. // If signature resolution originated in control flow type analysis (for example to compute the
  57014. // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
  57015. // types from the control flow analysis.
  57016. links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
  57017. }
  57018. return result;
  57019. }
  57020. /**
  57021. * Indicates whether a declaration can be treated as a constructor in a JavaScript
  57022. * file.
  57023. */
  57024. function isJSConstructor(node) {
  57025. if (!node || !ts.isInJSFile(node)) {
  57026. return false;
  57027. }
  57028. var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
  57029. ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
  57030. undefined;
  57031. if (func) {
  57032. // If the node has a @class tag, treat it like a constructor.
  57033. if (ts.getJSDocClassTag(node))
  57034. return true;
  57035. // If the symbol of the node has members, treat it like a constructor.
  57036. var symbol = getSymbolOfNode(func);
  57037. return !!symbol && ts.hasEntries(symbol.members);
  57038. }
  57039. return false;
  57040. }
  57041. function mergeJSSymbols(target, source) {
  57042. if (source) {
  57043. var links = getSymbolLinks(source);
  57044. if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
  57045. var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
  57046. inferred.exports = inferred.exports || ts.createSymbolTable();
  57047. inferred.members = inferred.members || ts.createSymbolTable();
  57048. inferred.flags |= source.flags & 32 /* Class */;
  57049. if (ts.hasEntries(source.exports)) {
  57050. mergeSymbolTable(inferred.exports, source.exports);
  57051. }
  57052. if (ts.hasEntries(source.members)) {
  57053. mergeSymbolTable(inferred.members, source.members);
  57054. }
  57055. (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
  57056. return inferred;
  57057. }
  57058. return links.inferredClassSymbol.get("" + getSymbolId(target));
  57059. }
  57060. }
  57061. function getAssignedClassSymbol(decl) {
  57062. var assignmentSymbol = decl && decl.parent &&
  57063. (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
  57064. ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
  57065. ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
  57066. var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
  57067. var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
  57068. return init ? getSymbolOfNode(init) : undefined;
  57069. }
  57070. function getAssignedJSPrototype(node) {
  57071. if (!node.parent) {
  57072. return false;
  57073. }
  57074. var parent = node.parent;
  57075. while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
  57076. parent = parent.parent;
  57077. }
  57078. if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
  57079. var right = ts.getInitializerOfBinaryExpression(parent);
  57080. return ts.isObjectLiteralExpression(right) && right;
  57081. }
  57082. }
  57083. /**
  57084. * Syntactically and semantically checks a call or new expression.
  57085. * @param node The call/new expression to be checked.
  57086. * @returns On success, the expression's signature's return type. On failure, anyType.
  57087. */
  57088. function checkCallExpression(node, checkMode) {
  57089. if (!checkGrammarTypeArguments(node, node.typeArguments))
  57090. checkGrammarArguments(node.arguments);
  57091. var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
  57092. if (signature === resolvingSignature) {
  57093. // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
  57094. // returns a function type. We defer checking and return nonInferrableType.
  57095. return nonInferrableType;
  57096. }
  57097. if (node.expression.kind === 102 /* SuperKeyword */) {
  57098. return voidType;
  57099. }
  57100. if (node.kind === 197 /* NewExpression */) {
  57101. var declaration = signature.declaration;
  57102. if (declaration &&
  57103. declaration.kind !== 162 /* Constructor */ &&
  57104. declaration.kind !== 166 /* ConstructSignature */ &&
  57105. declaration.kind !== 171 /* ConstructorType */ &&
  57106. !ts.isJSDocConstructSignature(declaration) &&
  57107. !isJSConstructor(declaration)) {
  57108. // When resolved signature is a call signature (and not a construct signature) the result type is any
  57109. if (noImplicitAny) {
  57110. error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
  57111. }
  57112. return anyType;
  57113. }
  57114. }
  57115. // In JavaScript files, calls to any identifier 'require' are treated as external module imports
  57116. if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
  57117. return resolveExternalModuleTypeByLiteral(node.arguments[0]);
  57118. }
  57119. var returnType = getReturnTypeOfSignature(signature);
  57120. // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
  57121. // as a fresh unique symbol literal type.
  57122. if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
  57123. return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
  57124. }
  57125. if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
  57126. returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
  57127. if (!ts.isDottedName(node.expression)) {
  57128. error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
  57129. }
  57130. else if (!getEffectsSignature(node)) {
  57131. var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
  57132. getTypeOfDottedName(node.expression, diagnostic);
  57133. }
  57134. }
  57135. if (ts.isInJSFile(node)) {
  57136. var decl = ts.getDeclarationOfExpando(node);
  57137. if (decl) {
  57138. var jsSymbol = getSymbolOfNode(decl);
  57139. if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
  57140. var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
  57141. jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
  57142. return getIntersectionType([returnType, jsAssignmentType]);
  57143. }
  57144. }
  57145. }
  57146. return returnType;
  57147. }
  57148. function isSymbolOrSymbolForCall(node) {
  57149. if (!ts.isCallExpression(node))
  57150. return false;
  57151. var left = node.expression;
  57152. if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
  57153. left = left.expression;
  57154. }
  57155. if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
  57156. return false;
  57157. }
  57158. // make sure `Symbol` is the global symbol
  57159. var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
  57160. if (!globalESSymbol) {
  57161. return false;
  57162. }
  57163. return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
  57164. }
  57165. function checkImportCallExpression(node) {
  57166. // Check grammar of dynamic import
  57167. if (!checkGrammarArguments(node.arguments))
  57168. checkGrammarImportCallExpression(node);
  57169. if (node.arguments.length === 0) {
  57170. return createPromiseReturnType(node, anyType);
  57171. }
  57172. var specifier = node.arguments[0];
  57173. var specifierType = checkExpressionCached(specifier);
  57174. // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
  57175. for (var i = 1; i < node.arguments.length; ++i) {
  57176. checkExpressionCached(node.arguments[i]);
  57177. }
  57178. if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
  57179. error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
  57180. }
  57181. // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
  57182. var moduleSymbol = resolveExternalModuleName(node, specifier);
  57183. if (moduleSymbol) {
  57184. var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
  57185. if (esModuleSymbol) {
  57186. return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
  57187. }
  57188. }
  57189. return createPromiseReturnType(node, anyType);
  57190. }
  57191. function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
  57192. if (allowSyntheticDefaultImports && type && type !== errorType) {
  57193. var synthType = type;
  57194. if (!synthType.syntheticType) {
  57195. var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
  57196. var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
  57197. if (hasSyntheticDefault) {
  57198. var memberTable = ts.createSymbolTable();
  57199. var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
  57200. newSymbol.nameType = getLiteralType("default");
  57201. newSymbol.target = resolveSymbol(symbol);
  57202. memberTable.set("default" /* Default */, newSymbol);
  57203. var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
  57204. var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
  57205. anonymousSymbol.type = defaultContainingObject;
  57206. synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
  57207. }
  57208. else {
  57209. synthType.syntheticType = type;
  57210. }
  57211. }
  57212. return synthType.syntheticType;
  57213. }
  57214. return type;
  57215. }
  57216. function isCommonJsRequire(node) {
  57217. if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
  57218. return false;
  57219. }
  57220. // Make sure require is not a local function
  57221. if (!ts.isIdentifier(node.expression))
  57222. return ts.Debug.fail();
  57223. var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
  57224. if (resolvedRequire === requireSymbol) {
  57225. return true;
  57226. }
  57227. // project includes symbol named 'require' - make sure that it is ambient and local non-alias
  57228. if (resolvedRequire.flags & 2097152 /* Alias */) {
  57229. return false;
  57230. }
  57231. var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
  57232. ? 244 /* FunctionDeclaration */
  57233. : resolvedRequire.flags & 3 /* Variable */
  57234. ? 242 /* VariableDeclaration */
  57235. : 0 /* Unknown */;
  57236. if (targetDeclarationKind !== 0 /* Unknown */) {
  57237. var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
  57238. // function/variable declaration should be ambient
  57239. return !!decl && !!(decl.flags & 8388608 /* Ambient */);
  57240. }
  57241. return false;
  57242. }
  57243. function checkTaggedTemplateExpression(node) {
  57244. if (!checkGrammarTaggedTemplateChain(node))
  57245. checkGrammarTypeArguments(node, node.typeArguments);
  57246. if (languageVersion < 2 /* ES2015 */) {
  57247. checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
  57248. }
  57249. return getReturnTypeOfSignature(getResolvedSignature(node));
  57250. }
  57251. function checkAssertion(node) {
  57252. return checkAssertionWorker(node, node.type, node.expression);
  57253. }
  57254. function isValidConstAssertionArgument(node) {
  57255. switch (node.kind) {
  57256. case 10 /* StringLiteral */:
  57257. case 14 /* NoSubstitutionTemplateLiteral */:
  57258. case 8 /* NumericLiteral */:
  57259. case 9 /* BigIntLiteral */:
  57260. case 106 /* TrueKeyword */:
  57261. case 91 /* FalseKeyword */:
  57262. case 192 /* ArrayLiteralExpression */:
  57263. case 193 /* ObjectLiteralExpression */:
  57264. return true;
  57265. case 200 /* ParenthesizedExpression */:
  57266. return isValidConstAssertionArgument(node.expression);
  57267. case 207 /* PrefixUnaryExpression */:
  57268. var op = node.operator;
  57269. var arg = node.operand;
  57270. return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
  57271. op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
  57272. case 194 /* PropertyAccessExpression */:
  57273. case 195 /* ElementAccessExpression */:
  57274. var expr = node.expression;
  57275. if (ts.isIdentifier(expr)) {
  57276. var symbol = getSymbolAtLocation(expr);
  57277. if (symbol && symbol.flags & 2097152 /* Alias */) {
  57278. symbol = resolveAlias(symbol);
  57279. }
  57280. return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
  57281. }
  57282. }
  57283. return false;
  57284. }
  57285. function checkAssertionWorker(errNode, type, expression, checkMode) {
  57286. var exprType = checkExpression(expression, checkMode);
  57287. if (ts.isConstTypeReference(type)) {
  57288. if (!isValidConstAssertionArgument(expression)) {
  57289. error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
  57290. }
  57291. return getRegularTypeOfLiteralType(exprType);
  57292. }
  57293. checkSourceElement(type);
  57294. exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
  57295. var targetType = getTypeFromTypeNode(type);
  57296. if (produceDiagnostics && targetType !== errorType) {
  57297. var widenedType = getWidenedType(exprType);
  57298. if (!isTypeComparableTo(targetType, widenedType)) {
  57299. checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first);
  57300. }
  57301. }
  57302. return targetType;
  57303. }
  57304. function checkNonNullAssertion(node) {
  57305. return getNonNullableType(checkExpression(node.expression));
  57306. }
  57307. function checkMetaProperty(node) {
  57308. checkGrammarMetaProperty(node);
  57309. if (node.keywordToken === 99 /* NewKeyword */) {
  57310. return checkNewTargetMetaProperty(node);
  57311. }
  57312. if (node.keywordToken === 96 /* ImportKeyword */) {
  57313. return checkImportMetaProperty(node);
  57314. }
  57315. return ts.Debug.assertNever(node.keywordToken);
  57316. }
  57317. function checkNewTargetMetaProperty(node) {
  57318. var container = ts.getNewTargetContainer(node);
  57319. if (!container) {
  57320. error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
  57321. return errorType;
  57322. }
  57323. else if (container.kind === 162 /* Constructor */) {
  57324. var symbol = getSymbolOfNode(container.parent);
  57325. return getTypeOfSymbol(symbol);
  57326. }
  57327. else {
  57328. var symbol = getSymbolOfNode(container);
  57329. return getTypeOfSymbol(symbol);
  57330. }
  57331. }
  57332. function checkImportMetaProperty(node) {
  57333. if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
  57334. error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
  57335. }
  57336. var file = ts.getSourceFileOfNode(node);
  57337. ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
  57338. ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
  57339. return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
  57340. }
  57341. function getTypeOfParameter(symbol) {
  57342. var type = getTypeOfSymbol(symbol);
  57343. if (strictNullChecks) {
  57344. var declaration = symbol.valueDeclaration;
  57345. if (declaration && ts.hasInitializer(declaration)) {
  57346. return getOptionalType(type);
  57347. }
  57348. }
  57349. return type;
  57350. }
  57351. function getParameterNameAtPosition(signature, pos) {
  57352. var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
  57353. if (pos < paramCount) {
  57354. return signature.parameters[pos].escapedName;
  57355. }
  57356. var restParameter = signature.parameters[paramCount] || unknownSymbol;
  57357. var restType = getTypeOfSymbol(restParameter);
  57358. if (isTupleType(restType)) {
  57359. var associatedNames = restType.target.associatedNames;
  57360. var index = pos - paramCount;
  57361. return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
  57362. }
  57363. return restParameter.escapedName;
  57364. }
  57365. function getTypeAtPosition(signature, pos) {
  57366. return tryGetTypeAtPosition(signature, pos) || anyType;
  57367. }
  57368. function tryGetTypeAtPosition(signature, pos) {
  57369. var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
  57370. if (pos < paramCount) {
  57371. return getTypeOfParameter(signature.parameters[pos]);
  57372. }
  57373. if (signatureHasRestParameter(signature)) {
  57374. // We want to return the value undefined for an out of bounds parameter position,
  57375. // so we need to check bounds here before calling getIndexedAccessType (which
  57376. // otherwise would return the type 'undefined').
  57377. var restType = getTypeOfSymbol(signature.parameters[paramCount]);
  57378. var index = pos - paramCount;
  57379. if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
  57380. return getIndexedAccessType(restType, getLiteralType(index));
  57381. }
  57382. }
  57383. return undefined;
  57384. }
  57385. function getRestTypeAtPosition(source, pos) {
  57386. var paramCount = getParameterCount(source);
  57387. var restType = getEffectiveRestType(source);
  57388. var nonRestCount = paramCount - (restType ? 1 : 0);
  57389. if (restType && pos === nonRestCount) {
  57390. return restType;
  57391. }
  57392. var types = [];
  57393. var names = [];
  57394. for (var i = pos; i < nonRestCount; i++) {
  57395. types.push(getTypeAtPosition(source, i));
  57396. names.push(getParameterNameAtPosition(source, i));
  57397. }
  57398. if (restType) {
  57399. types.push(getIndexedAccessType(restType, numberType));
  57400. names.push(getParameterNameAtPosition(source, nonRestCount));
  57401. }
  57402. var minArgumentCount = getMinArgumentCount(source);
  57403. var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
  57404. return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
  57405. }
  57406. function getParameterCount(signature) {
  57407. var length = signature.parameters.length;
  57408. if (signatureHasRestParameter(signature)) {
  57409. var restType = getTypeOfSymbol(signature.parameters[length - 1]);
  57410. if (isTupleType(restType)) {
  57411. return length + getTypeArguments(restType).length - 1;
  57412. }
  57413. }
  57414. return length;
  57415. }
  57416. function getMinArgumentCount(signature) {
  57417. if (signatureHasRestParameter(signature)) {
  57418. var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
  57419. if (isTupleType(restType)) {
  57420. var minLength = restType.target.minLength;
  57421. if (minLength > 0) {
  57422. return signature.parameters.length - 1 + minLength;
  57423. }
  57424. }
  57425. }
  57426. return signature.minArgumentCount;
  57427. }
  57428. function hasEffectiveRestParameter(signature) {
  57429. if (signatureHasRestParameter(signature)) {
  57430. var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
  57431. return !isTupleType(restType) || restType.target.hasRestElement;
  57432. }
  57433. return false;
  57434. }
  57435. function getEffectiveRestType(signature) {
  57436. if (signatureHasRestParameter(signature)) {
  57437. var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
  57438. return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
  57439. }
  57440. return undefined;
  57441. }
  57442. function getNonArrayRestType(signature) {
  57443. var restType = getEffectiveRestType(signature);
  57444. return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined;
  57445. }
  57446. function getTypeOfFirstParameterOfSignature(signature) {
  57447. return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
  57448. }
  57449. function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
  57450. return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
  57451. }
  57452. function inferFromAnnotatedParameters(signature, context, inferenceContext) {
  57453. var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
  57454. for (var i = 0; i < len; i++) {
  57455. var declaration = signature.parameters[i].valueDeclaration;
  57456. if (declaration.type) {
  57457. var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
  57458. if (typeNode) {
  57459. inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
  57460. }
  57461. }
  57462. }
  57463. var restType = getEffectiveRestType(context);
  57464. if (restType && restType.flags & 262144 /* TypeParameter */) {
  57465. // The contextual signature has a generic rest parameter. We first instantiate the contextual
  57466. // signature (without fixing type parameters) and assign types to contextually typed parameters.
  57467. var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
  57468. assignContextualParameterTypes(signature, instantiatedContext);
  57469. // We then infer from a tuple type representing the parameters that correspond to the contextual
  57470. // rest parameter.
  57471. var restPos = getParameterCount(context) - 1;
  57472. inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
  57473. }
  57474. }
  57475. function assignContextualParameterTypes(signature, context) {
  57476. signature.typeParameters = context.typeParameters;
  57477. if (context.thisParameter) {
  57478. var parameter = signature.thisParameter;
  57479. if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
  57480. if (!parameter) {
  57481. signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
  57482. }
  57483. assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
  57484. }
  57485. }
  57486. var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
  57487. for (var i = 0; i < len; i++) {
  57488. var parameter = signature.parameters[i];
  57489. if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
  57490. var contextualParameterType = tryGetTypeAtPosition(context, i);
  57491. assignParameterType(parameter, contextualParameterType);
  57492. }
  57493. }
  57494. if (signatureHasRestParameter(signature)) {
  57495. // parameter might be a transient symbol generated by use of `arguments` in the function body.
  57496. var parameter = ts.last(signature.parameters);
  57497. if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
  57498. var contextualParameterType = getRestTypeAtPosition(context, len);
  57499. assignParameterType(parameter, contextualParameterType);
  57500. }
  57501. }
  57502. }
  57503. function assignNonContextualParameterTypes(signature) {
  57504. if (signature.thisParameter) {
  57505. assignParameterType(signature.thisParameter);
  57506. }
  57507. for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
  57508. var parameter = _a[_i];
  57509. assignParameterType(parameter);
  57510. }
  57511. }
  57512. function assignParameterType(parameter, type) {
  57513. var links = getSymbolLinks(parameter);
  57514. if (!links.type) {
  57515. var declaration = parameter.valueDeclaration;
  57516. links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
  57517. if (declaration.name.kind !== 75 /* Identifier */) {
  57518. // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
  57519. if (links.type === unknownType) {
  57520. links.type = getTypeFromBindingPattern(declaration.name);
  57521. }
  57522. assignBindingElementTypes(declaration.name);
  57523. }
  57524. }
  57525. }
  57526. // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
  57527. // the destructured type into the contained binding elements.
  57528. function assignBindingElementTypes(pattern) {
  57529. for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
  57530. var element = _a[_i];
  57531. if (!ts.isOmittedExpression(element)) {
  57532. if (element.name.kind === 75 /* Identifier */) {
  57533. getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
  57534. }
  57535. else {
  57536. assignBindingElementTypes(element.name);
  57537. }
  57538. }
  57539. }
  57540. }
  57541. function createPromiseType(promisedType) {
  57542. // creates a `Promise<T>` type where `T` is the promisedType argument
  57543. var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
  57544. if (globalPromiseType !== emptyGenericType) {
  57545. // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
  57546. promisedType = getAwaitedType(promisedType) || unknownType;
  57547. return createTypeReference(globalPromiseType, [promisedType]);
  57548. }
  57549. return unknownType;
  57550. }
  57551. function createPromiseLikeType(promisedType) {
  57552. // creates a `PromiseLike<T>` type where `T` is the promisedType argument
  57553. var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
  57554. if (globalPromiseLikeType !== emptyGenericType) {
  57555. // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
  57556. promisedType = getAwaitedType(promisedType) || unknownType;
  57557. return createTypeReference(globalPromiseLikeType, [promisedType]);
  57558. }
  57559. return unknownType;
  57560. }
  57561. function createPromiseReturnType(func, promisedType) {
  57562. var promiseType = createPromiseType(promisedType);
  57563. if (promiseType === unknownType) {
  57564. error(func, ts.isImportCall(func) ?
  57565. ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
  57566. ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option);
  57567. return errorType;
  57568. }
  57569. else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
  57570. error(func, ts.isImportCall(func) ?
  57571. ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option :
  57572. ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
  57573. }
  57574. return promiseType;
  57575. }
  57576. function getReturnTypeFromBody(func, checkMode) {
  57577. if (!func.body) {
  57578. return errorType;
  57579. }
  57580. var functionFlags = ts.getFunctionFlags(func);
  57581. var isAsync = (functionFlags & 2 /* Async */) !== 0;
  57582. var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
  57583. var returnType;
  57584. var yieldType;
  57585. var nextType;
  57586. var fallbackReturnType = voidType;
  57587. if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
  57588. returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
  57589. if (isAsync) {
  57590. // From within an async function you can return either a non-promise value or a promise. Any
  57591. // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
  57592. // return type of the body should be unwrapped to its awaited type, which we will wrap in
  57593. // the native Promise<T> type later in this function.
  57594. returnType = checkAwaitedType(returnType, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
  57595. }
  57596. }
  57597. else if (isGenerator) { // Generator or AsyncGenerator function
  57598. var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
  57599. if (!returnTypes) {
  57600. fallbackReturnType = neverType;
  57601. }
  57602. else if (returnTypes.length > 0) {
  57603. returnType = getUnionType(returnTypes, 2 /* Subtype */);
  57604. }
  57605. var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
  57606. yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
  57607. nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
  57608. }
  57609. else { // Async or normal function
  57610. var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
  57611. if (!types) {
  57612. // For an async function, the return type will not be never, but rather a Promise for never.
  57613. return functionFlags & 2 /* Async */
  57614. ? createPromiseReturnType(func, neverType) // Async function
  57615. : neverType; // Normal function
  57616. }
  57617. if (types.length === 0) {
  57618. // For an async function, the return type will not be void, but rather a Promise for void.
  57619. return functionFlags & 2 /* Async */
  57620. ? createPromiseReturnType(func, voidType) // Async function
  57621. : voidType; // Normal function
  57622. }
  57623. // Return a union of the return expression types.
  57624. returnType = getUnionType(types, 2 /* Subtype */);
  57625. }
  57626. if (returnType || yieldType || nextType) {
  57627. var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
  57628. if (!contextualSignature) {
  57629. if (yieldType)
  57630. reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */);
  57631. if (returnType)
  57632. reportErrorsFromWidening(func, returnType);
  57633. if (nextType)
  57634. reportErrorsFromWidening(func, nextType);
  57635. }
  57636. if (returnType && isUnitType(returnType) ||
  57637. yieldType && isUnitType(yieldType) ||
  57638. nextType && isUnitType(nextType)) {
  57639. var contextualType = !contextualSignature ? undefined :
  57640. contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
  57641. instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
  57642. if (isGenerator) {
  57643. yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
  57644. returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
  57645. nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
  57646. }
  57647. else {
  57648. returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
  57649. }
  57650. }
  57651. if (yieldType)
  57652. yieldType = getWidenedType(yieldType);
  57653. if (returnType)
  57654. returnType = getWidenedType(returnType);
  57655. if (nextType)
  57656. nextType = getWidenedType(nextType);
  57657. }
  57658. if (isGenerator) {
  57659. return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
  57660. }
  57661. else {
  57662. // From within an async function you can return either a non-promise value or a promise. Any
  57663. // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
  57664. // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
  57665. return isAsync
  57666. ? createPromiseType(returnType || fallbackReturnType)
  57667. : returnType || fallbackReturnType;
  57668. }
  57669. }
  57670. function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
  57671. var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
  57672. var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
  57673. yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
  57674. returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
  57675. nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
  57676. if (globalGeneratorType === emptyGenericType) {
  57677. // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
  57678. // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
  57679. // nextType.
  57680. var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
  57681. var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
  57682. var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
  57683. var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
  57684. if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
  57685. isTypeAssignableTo(iterableIteratorNextType, nextType)) {
  57686. if (globalType !== emptyGenericType) {
  57687. return createTypeFromGenericGlobalType(globalType, [yieldType]);
  57688. }
  57689. // The global IterableIterator type doesn't exist, so report an error
  57690. resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
  57691. return emptyObjectType;
  57692. }
  57693. // The global Generator type doesn't exist, so report an error
  57694. resolver.getGlobalGeneratorType(/*reportErrors*/ true);
  57695. return emptyObjectType;
  57696. }
  57697. return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
  57698. }
  57699. function checkAndAggregateYieldOperandTypes(func, checkMode) {
  57700. var yieldTypes = [];
  57701. var nextTypes = [];
  57702. var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
  57703. ts.forEachYieldExpression(func.body, function (yieldExpression) {
  57704. var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
  57705. ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
  57706. var nextType;
  57707. if (yieldExpression.asteriskToken) {
  57708. var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
  57709. nextType = iterationTypes && iterationTypes.nextType;
  57710. }
  57711. else {
  57712. nextType = getContextualType(yieldExpression);
  57713. }
  57714. if (nextType)
  57715. ts.pushIfUnique(nextTypes, nextType);
  57716. });
  57717. return { yieldTypes: yieldTypes, nextTypes: nextTypes };
  57718. }
  57719. function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
  57720. var errorNode = node.expression || node;
  57721. // A `yield*` expression effectively yields everything that its operand yields
  57722. var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
  57723. return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
  57724. ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
  57725. : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
  57726. }
  57727. /**
  57728. * Collect the TypeFacts learned from a typeof switch with
  57729. * total clauses `witnesses`, and the active clause ranging
  57730. * from `start` to `end`. Parameter `hasDefault` denotes
  57731. * whether the active clause contains a default clause.
  57732. */
  57733. function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
  57734. var facts = 0 /* None */;
  57735. // When in the default we only collect inequality facts
  57736. // because default is 'in theory' a set of infinite
  57737. // equalities.
  57738. if (hasDefault) {
  57739. // Value is not equal to any types after the active clause.
  57740. for (var i = end; i < witnesses.length; i++) {
  57741. facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
  57742. }
  57743. // Remove inequalities for types that appear in the
  57744. // active clause because they appear before other
  57745. // types collected so far.
  57746. for (var i = start; i < end; i++) {
  57747. facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
  57748. }
  57749. // Add inequalities for types before the active clause unconditionally.
  57750. for (var i = 0; i < start; i++) {
  57751. facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
  57752. }
  57753. }
  57754. // When in an active clause without default the set of
  57755. // equalities is finite.
  57756. else {
  57757. // Add equalities for all types in the active clause.
  57758. for (var i = start; i < end; i++) {
  57759. facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
  57760. }
  57761. // Remove equalities for types that appear before the
  57762. // active clause.
  57763. for (var i = 0; i < start; i++) {
  57764. facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
  57765. }
  57766. }
  57767. return facts;
  57768. }
  57769. function isExhaustiveSwitchStatement(node) {
  57770. var links = getNodeLinks(node);
  57771. return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
  57772. }
  57773. function computeExhaustiveSwitchStatement(node) {
  57774. if (node.expression.kind === 204 /* TypeOfExpression */) {
  57775. var operandType = getTypeOfExpression(node.expression.expression);
  57776. // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined.
  57777. var witnesses = getSwitchClauseTypeOfWitnesses(node);
  57778. // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
  57779. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
  57780. var type_3 = getBaseConstraintOfType(operandType) || operandType;
  57781. return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
  57782. }
  57783. var type = getTypeOfExpression(node.expression);
  57784. if (!isLiteralType(type)) {
  57785. return false;
  57786. }
  57787. var switchTypes = getSwitchClauseTypes(node);
  57788. if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
  57789. return false;
  57790. }
  57791. return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
  57792. }
  57793. function functionHasImplicitReturn(func) {
  57794. return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
  57795. }
  57796. /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
  57797. function checkAndAggregateReturnExpressionTypes(func, checkMode) {
  57798. var functionFlags = ts.getFunctionFlags(func);
  57799. var aggregatedTypes = [];
  57800. var hasReturnWithNoExpression = functionHasImplicitReturn(func);
  57801. var hasReturnOfTypeNever = false;
  57802. ts.forEachReturnStatement(func.body, function (returnStatement) {
  57803. var expr = returnStatement.expression;
  57804. if (expr) {
  57805. var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
  57806. if (functionFlags & 2 /* Async */) {
  57807. // From within an async function you can return either a non-promise value or a promise. Any
  57808. // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
  57809. // return type of the body should be unwrapped to its awaited type, which should be wrapped in
  57810. // the native Promise<T> type by the caller.
  57811. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
  57812. }
  57813. if (type.flags & 131072 /* Never */) {
  57814. hasReturnOfTypeNever = true;
  57815. }
  57816. ts.pushIfUnique(aggregatedTypes, type);
  57817. }
  57818. else {
  57819. hasReturnWithNoExpression = true;
  57820. }
  57821. });
  57822. if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
  57823. return undefined;
  57824. }
  57825. if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
  57826. !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
  57827. // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
  57828. ts.pushIfUnique(aggregatedTypes, undefinedType);
  57829. }
  57830. return aggregatedTypes;
  57831. }
  57832. function mayReturnNever(func) {
  57833. switch (func.kind) {
  57834. case 201 /* FunctionExpression */:
  57835. case 202 /* ArrowFunction */:
  57836. return true;
  57837. case 161 /* MethodDeclaration */:
  57838. return func.parent.kind === 193 /* ObjectLiteralExpression */;
  57839. default:
  57840. return false;
  57841. }
  57842. }
  57843. /**
  57844. * TypeScript Specification 1.0 (6.3) - July 2014
  57845. * An explicitly typed function whose return type isn't the Void type,
  57846. * the Any type, or a union type containing the Void or Any type as a constituent
  57847. * must have at least one return statement somewhere in its body.
  57848. * An exception to this rule is if the function implementation consists of a single 'throw' statement.
  57849. *
  57850. * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
  57851. */
  57852. function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
  57853. if (!produceDiagnostics) {
  57854. return;
  57855. }
  57856. var functionFlags = ts.getFunctionFlags(func);
  57857. var type = returnType && getReturnOrPromisedType(returnType, functionFlags);
  57858. // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
  57859. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
  57860. return;
  57861. }
  57862. // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
  57863. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
  57864. if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
  57865. return;
  57866. }
  57867. var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
  57868. if (type && type.flags & 131072 /* Never */) {
  57869. error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
  57870. }
  57871. else if (type && !hasExplicitReturn) {
  57872. // minimal check: function has syntactic return type annotation and no explicit return statements in the body
  57873. // this function does not conform to the specification.
  57874. // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
  57875. error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
  57876. }
  57877. else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
  57878. error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
  57879. }
  57880. else if (compilerOptions.noImplicitReturns) {
  57881. if (!type) {
  57882. // If return type annotation is omitted check if function has any explicit return statements.
  57883. // If it does not have any - its inferred return type is void - don't do any checks.
  57884. // Otherwise get inferred return type from function body and report error only if it is not void / anytype
  57885. if (!hasExplicitReturn) {
  57886. return;
  57887. }
  57888. var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
  57889. if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
  57890. return;
  57891. }
  57892. }
  57893. error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
  57894. }
  57895. }
  57896. function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
  57897. ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
  57898. checkNodeDeferred(node);
  57899. // The identityMapper object is used to indicate that function expressions are wildcards
  57900. if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
  57901. // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
  57902. if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
  57903. // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
  57904. var contextualSignature = getContextualSignature(node);
  57905. if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
  57906. var links = getNodeLinks(node);
  57907. if (links.contextFreeType) {
  57908. return links.contextFreeType;
  57909. }
  57910. var returnType = getReturnTypeFromBody(node, checkMode);
  57911. var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
  57912. var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
  57913. returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
  57914. return links.contextFreeType = returnOnlyType;
  57915. }
  57916. }
  57917. return anyFunctionType;
  57918. }
  57919. // Grammar checking
  57920. var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
  57921. if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
  57922. checkGrammarForGenerator(node);
  57923. }
  57924. contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
  57925. return getTypeOfSymbol(getSymbolOfNode(node));
  57926. }
  57927. function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
  57928. var links = getNodeLinks(node);
  57929. // Check if function expression is contextually typed and assign parameter types if so.
  57930. if (!(links.flags & 1024 /* ContextChecked */)) {
  57931. var contextualSignature = getContextualSignature(node);
  57932. // If a type check is started at a function expression that is an argument of a function call, obtaining the
  57933. // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
  57934. // already assigned contextual types.
  57935. if (!(links.flags & 1024 /* ContextChecked */)) {
  57936. links.flags |= 1024 /* ContextChecked */;
  57937. var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
  57938. if (!signature) {
  57939. return;
  57940. }
  57941. if (isContextSensitive(node)) {
  57942. if (contextualSignature) {
  57943. var inferenceContext = getInferenceContext(node);
  57944. if (checkMode && checkMode & 2 /* Inferential */) {
  57945. inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
  57946. }
  57947. var instantiatedContextualSignature = inferenceContext ?
  57948. instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
  57949. assignContextualParameterTypes(signature, instantiatedContextualSignature);
  57950. }
  57951. else {
  57952. // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
  57953. assignNonContextualParameterTypes(signature);
  57954. }
  57955. }
  57956. if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
  57957. var returnType = getReturnTypeFromBody(node, checkMode);
  57958. if (!signature.resolvedReturnType) {
  57959. signature.resolvedReturnType = returnType;
  57960. }
  57961. }
  57962. checkSignatureDeclaration(node);
  57963. }
  57964. }
  57965. }
  57966. function getReturnOrPromisedType(type, functionFlags) {
  57967. var isGenerator = !!(functionFlags & 1 /* Generator */);
  57968. var isAsync = !!(functionFlags & 2 /* Async */);
  57969. return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType :
  57970. type && isAsync ? getAwaitedType(type) || errorType :
  57971. type;
  57972. }
  57973. function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
  57974. ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
  57975. var functionFlags = ts.getFunctionFlags(node);
  57976. var returnType = getReturnTypeFromAnnotation(node);
  57977. checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
  57978. if (node.body) {
  57979. if (!ts.getEffectiveReturnTypeNode(node)) {
  57980. // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
  57981. // we need. An example is the noImplicitAny errors resulting from widening the return expression
  57982. // of a function. Because checking of function expression bodies is deferred, there was never an
  57983. // appropriate time to do this during the main walk of the file (see the comment at the top of
  57984. // checkFunctionExpressionBodies). So it must be done now.
  57985. getReturnTypeOfSignature(getSignatureFromDeclaration(node));
  57986. }
  57987. if (node.body.kind === 223 /* Block */) {
  57988. checkSourceElement(node.body);
  57989. }
  57990. else {
  57991. // From within an async function you can return either a non-promise value or a promise. Any
  57992. // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
  57993. // should not be checking assignability of a promise to the return type. Instead, we need to
  57994. // check assignability of the awaited type of the expression body against the promised type of
  57995. // its return type annotation.
  57996. var exprType = checkExpression(node.body);
  57997. var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags);
  57998. if (returnOrPromisedType) {
  57999. if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
  58000. var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
  58001. checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
  58002. }
  58003. else { // Normal function
  58004. checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
  58005. }
  58006. }
  58007. }
  58008. }
  58009. }
  58010. function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
  58011. if (isAwaitValid === void 0) { isAwaitValid = false; }
  58012. if (!isTypeAssignableTo(type, numberOrBigIntType)) {
  58013. var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
  58014. errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
  58015. return false;
  58016. }
  58017. return true;
  58018. }
  58019. function isReadonlyAssignmentDeclaration(d) {
  58020. if (!ts.isCallExpression(d)) {
  58021. return false;
  58022. }
  58023. if (!ts.isBindableObjectDefinePropertyCall(d)) {
  58024. return false;
  58025. }
  58026. var objectLitType = checkExpressionCached(d.arguments[2]);
  58027. var valueType = getTypeOfPropertyOfType(objectLitType, "value");
  58028. if (valueType) {
  58029. var writableProp = getPropertyOfType(objectLitType, "writable");
  58030. var writableType = writableProp && getTypeOfSymbol(writableProp);
  58031. if (!writableType || writableType === falseType || writableType === regularFalseType) {
  58032. return true;
  58033. }
  58034. // We include this definition whereupon we walk back and check the type at the declaration because
  58035. // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
  58036. // argument types, should the type be contextualized by the call itself.
  58037. if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
  58038. var initializer = writableProp.valueDeclaration.initializer;
  58039. var rawOriginalType = checkExpression(initializer);
  58040. if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
  58041. return true;
  58042. }
  58043. }
  58044. return false;
  58045. }
  58046. var setProp = getPropertyOfType(objectLitType, "set");
  58047. return !setProp;
  58048. }
  58049. function isReadonlySymbol(symbol) {
  58050. // The following symbols are considered read-only:
  58051. // Properties with a 'readonly' modifier
  58052. // Variables declared with 'const'
  58053. // Get accessors without matching set accessors
  58054. // Enum members
  58055. // Object.defineProperty assignments with writable false or no setter
  58056. // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
  58057. return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
  58058. symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
  58059. symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
  58060. symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
  58061. symbol.flags & 8 /* EnumMember */ ||
  58062. ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
  58063. }
  58064. function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
  58065. var _a, _b;
  58066. if (assignmentKind === 0 /* None */) {
  58067. // no assigment means it doesn't matter whether the entity is readonly
  58068. return false;
  58069. }
  58070. if (isReadonlySymbol(symbol)) {
  58071. // Allow assignments to readonly properties within constructors of the same class declaration.
  58072. if (symbol.flags & 4 /* Property */ &&
  58073. ts.isAccessExpression(expr) &&
  58074. expr.expression.kind === 104 /* ThisKeyword */) {
  58075. // Look for if this is the constructor for the class that `symbol` is a property of.
  58076. var ctor = ts.getContainingFunction(expr);
  58077. if (!(ctor && ctor.kind === 162 /* Constructor */)) {
  58078. return true;
  58079. }
  58080. if (symbol.valueDeclaration) {
  58081. var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
  58082. var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
  58083. var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
  58084. var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
  58085. var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
  58086. var isWriteableSymbol = isLocalPropertyDeclaration
  58087. || isLocalParameterProperty
  58088. || isLocalThisPropertyAssignment
  58089. || isLocalThisPropertyAssignmentConstructorFunction;
  58090. return !isWriteableSymbol;
  58091. }
  58092. }
  58093. return true;
  58094. }
  58095. if (ts.isAccessExpression(expr)) {
  58096. // references through namespace import should be readonly
  58097. var node = ts.skipParentheses(expr.expression);
  58098. if (node.kind === 75 /* Identifier */) {
  58099. var symbol_2 = getNodeLinks(node).resolvedSymbol;
  58100. if (symbol_2.flags & 2097152 /* Alias */) {
  58101. var declaration = getDeclarationOfAliasSymbol(symbol_2);
  58102. return !!declaration && declaration.kind === 256 /* NamespaceImport */;
  58103. }
  58104. }
  58105. }
  58106. return false;
  58107. }
  58108. function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
  58109. // References are combinations of identifiers, parentheses, and property accesses.
  58110. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */);
  58111. if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
  58112. error(expr, invalidReferenceMessage);
  58113. return false;
  58114. }
  58115. if (node.flags & 32 /* OptionalChain */) {
  58116. error(expr, invalidOptionalChainMessage);
  58117. return false;
  58118. }
  58119. return true;
  58120. }
  58121. function checkDeleteExpression(node) {
  58122. checkExpression(node.expression);
  58123. var expr = ts.skipParentheses(node.expression);
  58124. if (!ts.isAccessExpression(expr)) {
  58125. error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
  58126. return booleanType;
  58127. }
  58128. if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
  58129. error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
  58130. }
  58131. var links = getNodeLinks(expr);
  58132. var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
  58133. if (symbol && isReadonlySymbol(symbol)) {
  58134. error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
  58135. }
  58136. return booleanType;
  58137. }
  58138. function checkTypeOfExpression(node) {
  58139. checkExpression(node.expression);
  58140. return typeofType;
  58141. }
  58142. function checkVoidExpression(node) {
  58143. checkExpression(node.expression);
  58144. return undefinedWideningType;
  58145. }
  58146. function isTopLevelAwait(node) {
  58147. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
  58148. return ts.isSourceFile(container);
  58149. }
  58150. function checkAwaitExpression(node) {
  58151. // Grammar checking
  58152. if (produceDiagnostics) {
  58153. if (!(node.flags & 32768 /* AwaitContext */)) {
  58154. if (isTopLevelAwait(node)) {
  58155. var sourceFile = ts.getSourceFileOfNode(node);
  58156. if (!hasParseDiagnostics(sourceFile)) {
  58157. var span = void 0;
  58158. if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
  58159. if (!span)
  58160. span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
  58161. var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module);
  58162. diagnostics.add(diagnostic);
  58163. }
  58164. if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
  58165. span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
  58166. var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher);
  58167. diagnostics.add(diagnostic);
  58168. }
  58169. }
  58170. }
  58171. else {
  58172. // use of 'await' in non-async function
  58173. var sourceFile = ts.getSourceFileOfNode(node);
  58174. if (!hasParseDiagnostics(sourceFile)) {
  58175. var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
  58176. var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
  58177. var func = ts.getContainingFunction(node);
  58178. if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
  58179. var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
  58180. ts.addRelatedInfo(diagnostic, relatedInfo);
  58181. }
  58182. diagnostics.add(diagnostic);
  58183. }
  58184. }
  58185. }
  58186. if (isInParameterInitializerBeforeContainingFunction(node)) {
  58187. error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
  58188. }
  58189. }
  58190. var operandType = checkExpression(node.expression);
  58191. var awaitedType = checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
  58192. if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
  58193. addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
  58194. }
  58195. return awaitedType;
  58196. }
  58197. function checkPrefixUnaryExpression(node) {
  58198. var operandType = checkExpression(node.operand);
  58199. if (operandType === silentNeverType) {
  58200. return silentNeverType;
  58201. }
  58202. switch (node.operand.kind) {
  58203. case 8 /* NumericLiteral */:
  58204. switch (node.operator) {
  58205. case 40 /* MinusToken */:
  58206. return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
  58207. case 39 /* PlusToken */:
  58208. return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
  58209. }
  58210. break;
  58211. case 9 /* BigIntLiteral */:
  58212. if (node.operator === 40 /* MinusToken */) {
  58213. return getFreshTypeOfLiteralType(getLiteralType({
  58214. negative: true,
  58215. base10Value: ts.parsePseudoBigInt(node.operand.text)
  58216. }));
  58217. }
  58218. }
  58219. switch (node.operator) {
  58220. case 39 /* PlusToken */:
  58221. case 40 /* MinusToken */:
  58222. case 54 /* TildeToken */:
  58223. checkNonNullType(operandType, node.operand);
  58224. if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
  58225. error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
  58226. }
  58227. if (node.operator === 39 /* PlusToken */) {
  58228. if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
  58229. error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
  58230. }
  58231. return numberType;
  58232. }
  58233. return getUnaryResultType(operandType);
  58234. case 53 /* ExclamationToken */:
  58235. checkTruthinessExpression(node.operand);
  58236. var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
  58237. return facts === 4194304 /* Truthy */ ? falseType :
  58238. facts === 8388608 /* Falsy */ ? trueType :
  58239. booleanType;
  58240. case 45 /* PlusPlusToken */:
  58241. case 46 /* MinusMinusToken */:
  58242. var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
  58243. if (ok) {
  58244. // run check only if former checks succeeded to avoid reporting cascading errors
  58245. checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access);
  58246. }
  58247. return getUnaryResultType(operandType);
  58248. }
  58249. return errorType;
  58250. }
  58251. function checkPostfixUnaryExpression(node) {
  58252. var operandType = checkExpression(node.operand);
  58253. if (operandType === silentNeverType) {
  58254. return silentNeverType;
  58255. }
  58256. var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
  58257. if (ok) {
  58258. // run check only if former checks succeeded to avoid reporting cascading errors
  58259. checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access);
  58260. }
  58261. return getUnaryResultType(operandType);
  58262. }
  58263. function getUnaryResultType(operandType) {
  58264. if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
  58265. return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
  58266. ? numberOrBigIntType
  58267. : bigintType;
  58268. }
  58269. // If it's not a bigint type, implicit coercion will result in a number
  58270. return numberType;
  58271. }
  58272. // Return true if type might be of the given kind. A union or intersection type might be of a given
  58273. // kind if at least one constituent type is of the given kind.
  58274. function maybeTypeOfKind(type, kind) {
  58275. if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
  58276. return true;
  58277. }
  58278. if (type.flags & 3145728 /* UnionOrIntersection */) {
  58279. var types = type.types;
  58280. for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
  58281. var t = types_18[_i];
  58282. if (maybeTypeOfKind(t, kind)) {
  58283. return true;
  58284. }
  58285. }
  58286. }
  58287. return false;
  58288. }
  58289. function isTypeAssignableToKind(source, kind, strict) {
  58290. if (source.flags & kind) {
  58291. return true;
  58292. }
  58293. if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
  58294. return false;
  58295. }
  58296. return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
  58297. !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
  58298. !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
  58299. !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
  58300. !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
  58301. !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
  58302. !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
  58303. !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
  58304. !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
  58305. !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
  58306. }
  58307. function allTypesAssignableToKind(source, kind, strict) {
  58308. return source.flags & 1048576 /* Union */ ?
  58309. ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
  58310. isTypeAssignableToKind(source, kind, strict);
  58311. }
  58312. function isConstEnumObjectType(type) {
  58313. return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
  58314. }
  58315. function isConstEnumSymbol(symbol) {
  58316. return (symbol.flags & 128 /* ConstEnum */) !== 0;
  58317. }
  58318. function checkInstanceOfExpression(left, right, leftType, rightType) {
  58319. if (leftType === silentNeverType || rightType === silentNeverType) {
  58320. return silentNeverType;
  58321. }
  58322. // TypeScript 1.0 spec (April 2014): 4.15.4
  58323. // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
  58324. // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
  58325. // The result is always of the Boolean primitive type.
  58326. // NOTE: do not raise error if leftType is unknown as related error was already reported
  58327. if (!isTypeAny(leftType) &&
  58328. allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
  58329. error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
  58330. }
  58331. // NOTE: do not raise error if right is unknown as related error was already reported
  58332. if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
  58333. error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type);
  58334. }
  58335. return booleanType;
  58336. }
  58337. function checkInExpression(left, right, leftType, rightType) {
  58338. if (leftType === silentNeverType || rightType === silentNeverType) {
  58339. return silentNeverType;
  58340. }
  58341. leftType = checkNonNullType(leftType, left);
  58342. rightType = checkNonNullType(rightType, right);
  58343. // TypeScript 1.0 spec (April 2014): 4.15.5
  58344. // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
  58345. // and the right operand to be of type Any, an object type, or a type parameter type.
  58346. // The result is always of the Boolean primitive type.
  58347. if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
  58348. error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
  58349. }
  58350. if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
  58351. error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
  58352. }
  58353. return booleanType;
  58354. }
  58355. function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
  58356. var properties = node.properties;
  58357. if (strictNullChecks && properties.length === 0) {
  58358. return checkNonNullType(sourceType, node);
  58359. }
  58360. for (var i = 0; i < properties.length; i++) {
  58361. checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
  58362. }
  58363. return sourceType;
  58364. }
  58365. /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
  58366. function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
  58367. if (rightIsThis === void 0) { rightIsThis = false; }
  58368. var properties = node.properties;
  58369. var property = properties[propertyIndex];
  58370. if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
  58371. var name = property.name;
  58372. var exprType = getLiteralTypeFromPropertyName(name);
  58373. if (isTypeUsableAsPropertyName(exprType)) {
  58374. var text = getPropertyNameFromType(exprType);
  58375. var prop = getPropertyOfType(objectLiteralType, text);
  58376. if (prop) {
  58377. markPropertyAsReferenced(prop, property, rightIsThis);
  58378. checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
  58379. }
  58380. }
  58381. var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
  58382. var type = getFlowTypeOfDestructuring(property, elementType);
  58383. return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
  58384. }
  58385. else if (property.kind === 283 /* SpreadAssignment */) {
  58386. if (propertyIndex < properties.length - 1) {
  58387. error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
  58388. }
  58389. else {
  58390. if (languageVersion < 99 /* ESNext */) {
  58391. checkExternalEmitHelpers(property, 4 /* Rest */);
  58392. }
  58393. var nonRestNames = [];
  58394. if (allProperties) {
  58395. for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
  58396. var otherProperty = allProperties_1[_i];
  58397. if (!ts.isSpreadAssignment(otherProperty)) {
  58398. nonRestNames.push(otherProperty.name);
  58399. }
  58400. }
  58401. }
  58402. var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
  58403. checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
  58404. return checkDestructuringAssignment(property.expression, type);
  58405. }
  58406. }
  58407. else {
  58408. error(property, ts.Diagnostics.Property_assignment_expected);
  58409. }
  58410. }
  58411. function checkArrayLiteralAssignment(node, sourceType, checkMode) {
  58412. var elements = node.elements;
  58413. if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
  58414. checkExternalEmitHelpers(node, 512 /* Read */);
  58415. }
  58416. // This elementType will be used if the specific property corresponding to this index is not
  58417. // present (aka the tuple element property). This call also checks that the parentType is in
  58418. // fact an iterable or array (depending on target language).
  58419. var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
  58420. for (var i = 0; i < elements.length; i++) {
  58421. checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
  58422. }
  58423. return sourceType;
  58424. }
  58425. function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
  58426. var elements = node.elements;
  58427. var element = elements[elementIndex];
  58428. if (element.kind !== 215 /* OmittedExpression */) {
  58429. if (element.kind !== 213 /* SpreadElement */) {
  58430. var indexType = getLiteralType(elementIndex);
  58431. if (isArrayLikeType(sourceType)) {
  58432. // We create a synthetic expression so that getIndexedAccessType doesn't get confused
  58433. // when the element is a SyntaxKind.ElementAccessExpression.
  58434. var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
  58435. var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
  58436. var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
  58437. var type = getFlowTypeOfDestructuring(element, assignedType);
  58438. return checkDestructuringAssignment(element, type, checkMode);
  58439. }
  58440. return checkDestructuringAssignment(element, elementType, checkMode);
  58441. }
  58442. if (elementIndex < elements.length - 1) {
  58443. error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
  58444. }
  58445. else {
  58446. var restExpression = element.expression;
  58447. if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
  58448. error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
  58449. }
  58450. else {
  58451. checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
  58452. var type = everyType(sourceType, isTupleType) ?
  58453. mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
  58454. createArrayType(elementType);
  58455. return checkDestructuringAssignment(restExpression, type, checkMode);
  58456. }
  58457. }
  58458. }
  58459. return undefined;
  58460. }
  58461. function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
  58462. var target;
  58463. if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
  58464. var prop = exprOrAssignment;
  58465. if (prop.objectAssignmentInitializer) {
  58466. // In strict null checking mode, if a default value of a non-undefined type is specified, remove
  58467. // undefined from the final type.
  58468. if (strictNullChecks &&
  58469. !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
  58470. sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
  58471. }
  58472. checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
  58473. }
  58474. target = exprOrAssignment.name;
  58475. }
  58476. else {
  58477. target = exprOrAssignment;
  58478. }
  58479. if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
  58480. checkBinaryExpression(target, checkMode);
  58481. target = target.left;
  58482. }
  58483. if (target.kind === 193 /* ObjectLiteralExpression */) {
  58484. return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
  58485. }
  58486. if (target.kind === 192 /* ArrayLiteralExpression */) {
  58487. return checkArrayLiteralAssignment(target, sourceType, checkMode);
  58488. }
  58489. return checkReferenceAssignment(target, sourceType, checkMode);
  58490. }
  58491. function checkReferenceAssignment(target, sourceType, checkMode) {
  58492. var targetType = checkExpression(target, checkMode);
  58493. var error = target.parent.kind === 283 /* SpreadAssignment */ ?
  58494. ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
  58495. ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
  58496. var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
  58497. ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
  58498. ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
  58499. if (checkReferenceExpression(target, error, optionalError)) {
  58500. checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
  58501. }
  58502. if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
  58503. checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
  58504. }
  58505. return sourceType;
  58506. }
  58507. /**
  58508. * This is a *shallow* check: An expression is side-effect-free if the
  58509. * evaluation of the expression *itself* cannot produce side effects.
  58510. * For example, x++ / 3 is side-effect free because the / operator
  58511. * does not have side effects.
  58512. * The intent is to "smell test" an expression for correctness in positions where
  58513. * its value is discarded (e.g. the left side of the comma operator).
  58514. */
  58515. function isSideEffectFree(node) {
  58516. node = ts.skipParentheses(node);
  58517. switch (node.kind) {
  58518. case 75 /* Identifier */:
  58519. case 10 /* StringLiteral */:
  58520. case 13 /* RegularExpressionLiteral */:
  58521. case 198 /* TaggedTemplateExpression */:
  58522. case 211 /* TemplateExpression */:
  58523. case 14 /* NoSubstitutionTemplateLiteral */:
  58524. case 8 /* NumericLiteral */:
  58525. case 9 /* BigIntLiteral */:
  58526. case 106 /* TrueKeyword */:
  58527. case 91 /* FalseKeyword */:
  58528. case 100 /* NullKeyword */:
  58529. case 146 /* UndefinedKeyword */:
  58530. case 201 /* FunctionExpression */:
  58531. case 214 /* ClassExpression */:
  58532. case 202 /* ArrowFunction */:
  58533. case 192 /* ArrayLiteralExpression */:
  58534. case 193 /* ObjectLiteralExpression */:
  58535. case 204 /* TypeOfExpression */:
  58536. case 218 /* NonNullExpression */:
  58537. case 267 /* JsxSelfClosingElement */:
  58538. case 266 /* JsxElement */:
  58539. return true;
  58540. case 210 /* ConditionalExpression */:
  58541. return isSideEffectFree(node.whenTrue) &&
  58542. isSideEffectFree(node.whenFalse);
  58543. case 209 /* BinaryExpression */:
  58544. if (ts.isAssignmentOperator(node.operatorToken.kind)) {
  58545. return false;
  58546. }
  58547. return isSideEffectFree(node.left) &&
  58548. isSideEffectFree(node.right);
  58549. case 207 /* PrefixUnaryExpression */:
  58550. case 208 /* PostfixUnaryExpression */:
  58551. // Unary operators ~, !, +, and - have no side effects.
  58552. // The rest do.
  58553. switch (node.operator) {
  58554. case 53 /* ExclamationToken */:
  58555. case 39 /* PlusToken */:
  58556. case 40 /* MinusToken */:
  58557. case 54 /* TildeToken */:
  58558. return true;
  58559. }
  58560. return false;
  58561. // Some forms listed here for clarity
  58562. case 205 /* VoidExpression */: // Explicit opt-out
  58563. case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
  58564. case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
  58565. default:
  58566. return false;
  58567. }
  58568. }
  58569. function isTypeEqualityComparableTo(source, target) {
  58570. return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
  58571. }
  58572. var CheckBinaryExpressionState;
  58573. (function (CheckBinaryExpressionState) {
  58574. CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
  58575. CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
  58576. CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
  58577. })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
  58578. function checkBinaryExpression(node, checkMode) {
  58579. var workStacks = {
  58580. expr: [node],
  58581. state: [0 /* MaybeCheckLeft */],
  58582. leftType: [undefined]
  58583. };
  58584. var stackIndex = 0;
  58585. var lastResult;
  58586. while (stackIndex >= 0) {
  58587. node = workStacks.expr[stackIndex];
  58588. switch (workStacks.state[stackIndex]) {
  58589. case 0 /* MaybeCheckLeft */: {
  58590. if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
  58591. finishInvocation(checkExpression(node.right, checkMode));
  58592. break;
  58593. }
  58594. checkGrammarNullishCoalesceWithLogicalExpression(node);
  58595. var operator = node.operatorToken.kind;
  58596. if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
  58597. finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
  58598. break;
  58599. }
  58600. advanceState(1 /* CheckRight */);
  58601. maybeCheckExpression(node.left);
  58602. break;
  58603. }
  58604. case 1 /* CheckRight */: {
  58605. var leftType = lastResult;
  58606. workStacks.leftType[stackIndex] = leftType;
  58607. var operator = node.operatorToken.kind;
  58608. if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
  58609. checkTruthinessOfType(leftType, node.left);
  58610. }
  58611. advanceState(2 /* FinishCheck */);
  58612. maybeCheckExpression(node.right);
  58613. break;
  58614. }
  58615. case 2 /* FinishCheck */: {
  58616. var leftType = workStacks.leftType[stackIndex];
  58617. var rightType = lastResult;
  58618. finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
  58619. break;
  58620. }
  58621. default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
  58622. }
  58623. }
  58624. return lastResult;
  58625. function finishInvocation(result) {
  58626. lastResult = result;
  58627. stackIndex--;
  58628. }
  58629. /**
  58630. * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
  58631. * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
  58632. */
  58633. function advanceState(nextState) {
  58634. workStacks.state[stackIndex] = nextState;
  58635. }
  58636. function maybeCheckExpression(node) {
  58637. if (ts.isBinaryExpression(node)) {
  58638. stackIndex++;
  58639. workStacks.expr[stackIndex] = node;
  58640. workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
  58641. workStacks.leftType[stackIndex] = undefined;
  58642. }
  58643. else {
  58644. lastResult = checkExpression(node, checkMode);
  58645. }
  58646. }
  58647. }
  58648. function checkGrammarNullishCoalesceWithLogicalExpression(node) {
  58649. var left = node.left, operatorToken = node.operatorToken, right = node.right;
  58650. if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
  58651. if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
  58652. grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
  58653. }
  58654. if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
  58655. grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
  58656. }
  58657. }
  58658. }
  58659. // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
  58660. // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
  58661. function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
  58662. var operator = operatorToken.kind;
  58663. if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
  58664. return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
  58665. }
  58666. var leftType;
  58667. if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
  58668. leftType = checkTruthinessExpression(left, checkMode);
  58669. }
  58670. else {
  58671. leftType = checkExpression(left, checkMode);
  58672. }
  58673. var rightType = checkExpression(right, checkMode);
  58674. return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
  58675. }
  58676. function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
  58677. var operator = operatorToken.kind;
  58678. switch (operator) {
  58679. case 41 /* AsteriskToken */:
  58680. case 42 /* AsteriskAsteriskToken */:
  58681. case 65 /* AsteriskEqualsToken */:
  58682. case 66 /* AsteriskAsteriskEqualsToken */:
  58683. case 43 /* SlashToken */:
  58684. case 67 /* SlashEqualsToken */:
  58685. case 44 /* PercentToken */:
  58686. case 68 /* PercentEqualsToken */:
  58687. case 40 /* MinusToken */:
  58688. case 64 /* MinusEqualsToken */:
  58689. case 47 /* LessThanLessThanToken */:
  58690. case 69 /* LessThanLessThanEqualsToken */:
  58691. case 48 /* GreaterThanGreaterThanToken */:
  58692. case 70 /* GreaterThanGreaterThanEqualsToken */:
  58693. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  58694. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  58695. case 51 /* BarToken */:
  58696. case 73 /* BarEqualsToken */:
  58697. case 52 /* CaretToken */:
  58698. case 74 /* CaretEqualsToken */:
  58699. case 50 /* AmpersandToken */:
  58700. case 72 /* AmpersandEqualsToken */:
  58701. if (leftType === silentNeverType || rightType === silentNeverType) {
  58702. return silentNeverType;
  58703. }
  58704. leftType = checkNonNullType(leftType, left);
  58705. rightType = checkNonNullType(rightType, right);
  58706. var suggestedOperator = void 0;
  58707. // if a user tries to apply a bitwise operator to 2 boolean operands
  58708. // try and return them a helpful suggestion
  58709. if ((leftType.flags & 528 /* BooleanLike */) &&
  58710. (rightType.flags & 528 /* BooleanLike */) &&
  58711. (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
  58712. error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator));
  58713. return numberType;
  58714. }
  58715. else {
  58716. // otherwise just check each operand separately and report errors as normal
  58717. var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ true);
  58718. var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ true);
  58719. var resultType_1;
  58720. // If both are any or unknown, allow operation; assume it will resolve to number
  58721. if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
  58722. // Or, if neither could be bigint, implicit coercion results in a number result
  58723. !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
  58724. resultType_1 = numberType;
  58725. }
  58726. // At least one is assignable to bigint, so check that both are
  58727. else if (bothAreBigIntLike(leftType, rightType)) {
  58728. switch (operator) {
  58729. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  58730. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  58731. reportOperatorError();
  58732. }
  58733. resultType_1 = bigintType;
  58734. }
  58735. // Exactly one of leftType/rightType is assignable to bigint
  58736. else {
  58737. reportOperatorError(bothAreBigIntLike);
  58738. resultType_1 = errorType;
  58739. }
  58740. if (leftOk && rightOk) {
  58741. checkAssignmentOperator(resultType_1);
  58742. }
  58743. return resultType_1;
  58744. }
  58745. case 39 /* PlusToken */:
  58746. case 63 /* PlusEqualsToken */:
  58747. if (leftType === silentNeverType || rightType === silentNeverType) {
  58748. return silentNeverType;
  58749. }
  58750. if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
  58751. leftType = checkNonNullType(leftType, left);
  58752. rightType = checkNonNullType(rightType, right);
  58753. }
  58754. var resultType = void 0;
  58755. if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
  58756. // Operands of an enum type are treated as having the primitive type Number.
  58757. // If both operands are of the Number primitive type, the result is of the Number primitive type.
  58758. resultType = numberType;
  58759. }
  58760. else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
  58761. // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
  58762. resultType = bigintType;
  58763. }
  58764. else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
  58765. // If one or both operands are of the String primitive type, the result is of the String primitive type.
  58766. resultType = stringType;
  58767. }
  58768. else if (isTypeAny(leftType) || isTypeAny(rightType)) {
  58769. // Otherwise, the result is of type Any.
  58770. // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
  58771. resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
  58772. }
  58773. // Symbols are not allowed at all in arithmetic expressions
  58774. if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
  58775. return resultType;
  58776. }
  58777. if (!resultType) {
  58778. // Types that have a reasonably good chance of being a valid operand type.
  58779. // If both types have an awaited type of one of these, we'll assume the user
  58780. // might be missing an await without doing an exhaustive check that inserting
  58781. // await(s) will actually be a completely valid binary expression.
  58782. var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
  58783. reportOperatorError(function (left, right) {
  58784. return isTypeAssignableToKind(left, closeEnoughKind_1) &&
  58785. isTypeAssignableToKind(right, closeEnoughKind_1);
  58786. });
  58787. return anyType;
  58788. }
  58789. if (operator === 63 /* PlusEqualsToken */) {
  58790. checkAssignmentOperator(resultType);
  58791. }
  58792. return resultType;
  58793. case 29 /* LessThanToken */:
  58794. case 31 /* GreaterThanToken */:
  58795. case 32 /* LessThanEqualsToken */:
  58796. case 33 /* GreaterThanEqualsToken */:
  58797. if (checkForDisallowedESSymbolOperand(operator)) {
  58798. leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
  58799. rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
  58800. reportOperatorErrorUnless(function (left, right) {
  58801. return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
  58802. });
  58803. }
  58804. return booleanType;
  58805. case 34 /* EqualsEqualsToken */:
  58806. case 35 /* ExclamationEqualsToken */:
  58807. case 36 /* EqualsEqualsEqualsToken */:
  58808. case 37 /* ExclamationEqualsEqualsToken */:
  58809. reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
  58810. return booleanType;
  58811. case 98 /* InstanceOfKeyword */:
  58812. return checkInstanceOfExpression(left, right, leftType, rightType);
  58813. case 97 /* InKeyword */:
  58814. return checkInExpression(left, right, leftType, rightType);
  58815. case 55 /* AmpersandAmpersandToken */:
  58816. return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
  58817. getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
  58818. leftType;
  58819. case 56 /* BarBarToken */:
  58820. return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
  58821. getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
  58822. leftType;
  58823. case 60 /* QuestionQuestionToken */:
  58824. return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
  58825. getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
  58826. leftType;
  58827. case 62 /* EqualsToken */:
  58828. var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
  58829. checkAssignmentDeclaration(declKind, rightType);
  58830. if (isAssignmentDeclaration(declKind)) {
  58831. if (!(rightType.flags & 524288 /* Object */) ||
  58832. declKind !== 2 /* ModuleExports */ &&
  58833. declKind !== 6 /* Prototype */ &&
  58834. !isEmptyObjectType(rightType) &&
  58835. !isFunctionObjectType(rightType) &&
  58836. !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
  58837. // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
  58838. checkAssignmentOperator(rightType);
  58839. }
  58840. return leftType;
  58841. }
  58842. else {
  58843. checkAssignmentOperator(rightType);
  58844. return getRegularTypeOfObjectLiteral(rightType);
  58845. }
  58846. case 27 /* CommaToken */:
  58847. if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
  58848. error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
  58849. }
  58850. return rightType;
  58851. default:
  58852. return ts.Debug.fail();
  58853. }
  58854. function bothAreBigIntLike(left, right) {
  58855. return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
  58856. }
  58857. function checkAssignmentDeclaration(kind, rightType) {
  58858. if (kind === 2 /* ModuleExports */) {
  58859. for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
  58860. var prop = _a[_i];
  58861. var propType = getTypeOfSymbol(prop);
  58862. if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
  58863. var name = prop.escapedName;
  58864. var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
  58865. if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
  58866. grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
  58867. return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
  58868. }
  58869. }
  58870. }
  58871. }
  58872. }
  58873. function isEvalNode(node) {
  58874. return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
  58875. }
  58876. // Return true if there was no error, false if there was an error.
  58877. function checkForDisallowedESSymbolOperand(operator) {
  58878. var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
  58879. maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
  58880. undefined;
  58881. if (offendingSymbolOperand) {
  58882. error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
  58883. return false;
  58884. }
  58885. return true;
  58886. }
  58887. function getSuggestedBooleanOperator(operator) {
  58888. switch (operator) {
  58889. case 51 /* BarToken */:
  58890. case 73 /* BarEqualsToken */:
  58891. return 56 /* BarBarToken */;
  58892. case 52 /* CaretToken */:
  58893. case 74 /* CaretEqualsToken */:
  58894. return 37 /* ExclamationEqualsEqualsToken */;
  58895. case 50 /* AmpersandToken */:
  58896. case 72 /* AmpersandEqualsToken */:
  58897. return 55 /* AmpersandAmpersandToken */;
  58898. default:
  58899. return undefined;
  58900. }
  58901. }
  58902. function checkAssignmentOperator(valueType) {
  58903. if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
  58904. // TypeScript 1.0 spec (April 2014): 4.17
  58905. // An assignment of the form
  58906. // VarExpr = ValueExpr
  58907. // requires VarExpr to be classified as a reference
  58908. // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
  58909. // and the type of the non-compound operation to be assignable to the type of VarExpr.
  58910. if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)
  58911. && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
  58912. // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
  58913. checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
  58914. }
  58915. }
  58916. }
  58917. function isAssignmentDeclaration(kind) {
  58918. switch (kind) {
  58919. case 2 /* ModuleExports */:
  58920. return true;
  58921. case 1 /* ExportsProperty */:
  58922. case 5 /* Property */:
  58923. case 6 /* Prototype */:
  58924. case 3 /* PrototypeProperty */:
  58925. case 4 /* ThisProperty */:
  58926. var symbol = getSymbolOfNode(left);
  58927. var init = ts.getAssignedExpandoInitializer(right);
  58928. return init && ts.isObjectLiteralExpression(init) &&
  58929. symbol && ts.hasEntries(symbol.exports);
  58930. default:
  58931. return false;
  58932. }
  58933. }
  58934. /**
  58935. * Returns true if an error is reported
  58936. */
  58937. function reportOperatorErrorUnless(typesAreCompatible) {
  58938. if (!typesAreCompatible(leftType, rightType)) {
  58939. reportOperatorError(typesAreCompatible);
  58940. return true;
  58941. }
  58942. return false;
  58943. }
  58944. function reportOperatorError(isRelated) {
  58945. var _a;
  58946. var wouldWorkWithAwait = false;
  58947. var errNode = errorNode || operatorToken;
  58948. if (isRelated) {
  58949. var awaitedLeftType = getAwaitedType(leftType);
  58950. var awaitedRightType = getAwaitedType(rightType);
  58951. wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
  58952. && !!(awaitedLeftType && awaitedRightType)
  58953. && isRelated(awaitedLeftType, awaitedRightType);
  58954. }
  58955. var effectiveLeft = leftType;
  58956. var effectiveRight = rightType;
  58957. if (!wouldWorkWithAwait && isRelated) {
  58958. _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
  58959. }
  58960. var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
  58961. if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
  58962. errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
  58963. }
  58964. }
  58965. function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
  58966. var typeName;
  58967. switch (operatorToken.kind) {
  58968. case 36 /* EqualsEqualsEqualsToken */:
  58969. case 34 /* EqualsEqualsToken */:
  58970. typeName = "false";
  58971. break;
  58972. case 37 /* ExclamationEqualsEqualsToken */:
  58973. case 35 /* ExclamationEqualsToken */:
  58974. typeName = "true";
  58975. }
  58976. if (typeName) {
  58977. return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
  58978. }
  58979. return undefined;
  58980. }
  58981. }
  58982. function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
  58983. var effectiveLeft = leftType;
  58984. var effectiveRight = rightType;
  58985. var leftBase = getBaseTypeOfLiteralType(leftType);
  58986. var rightBase = getBaseTypeOfLiteralType(rightType);
  58987. if (!isRelated(leftBase, rightBase)) {
  58988. effectiveLeft = leftBase;
  58989. effectiveRight = rightBase;
  58990. }
  58991. return [effectiveLeft, effectiveRight];
  58992. }
  58993. function checkYieldExpression(node) {
  58994. // Grammar checking
  58995. if (produceDiagnostics) {
  58996. if (!(node.flags & 8192 /* YieldContext */)) {
  58997. grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
  58998. }
  58999. if (isInParameterInitializerBeforeContainingFunction(node)) {
  59000. error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
  59001. }
  59002. }
  59003. var func = ts.getContainingFunction(node);
  59004. if (!func)
  59005. return anyType;
  59006. var functionFlags = ts.getFunctionFlags(func);
  59007. if (!(functionFlags & 1 /* Generator */)) {
  59008. // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
  59009. return anyType;
  59010. }
  59011. var isAsync = (functionFlags & 2 /* Async */) !== 0;
  59012. if (node.asteriskToken) {
  59013. // Async generator functions prior to ESNext require the __await, __asyncDelegator,
  59014. // and __asyncValues helpers
  59015. if (isAsync && languageVersion < 99 /* ESNext */) {
  59016. checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
  59017. }
  59018. // Generator functions prior to ES2015 require the __values helper
  59019. if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
  59020. checkExternalEmitHelpers(node, 256 /* Values */);
  59021. }
  59022. }
  59023. // There is no point in doing an assignability check if the function
  59024. // has no explicit return type because the return type is directly computed
  59025. // from the yield expressions.
  59026. var returnType = getReturnTypeFromAnnotation(func);
  59027. var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
  59028. var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
  59029. var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
  59030. var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
  59031. var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
  59032. var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
  59033. if (returnType && yieldedType) {
  59034. checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
  59035. }
  59036. if (node.asteriskToken) {
  59037. var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
  59038. return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
  59039. || anyType;
  59040. }
  59041. else if (returnType) {
  59042. return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
  59043. || anyType;
  59044. }
  59045. return getContextualIterationType(2 /* Next */, func) || anyType;
  59046. }
  59047. function checkConditionalExpression(node, checkMode) {
  59048. checkTruthinessExpression(node.condition);
  59049. var type1 = checkExpression(node.whenTrue, checkMode);
  59050. var type2 = checkExpression(node.whenFalse, checkMode);
  59051. return getUnionType([type1, type2], 2 /* Subtype */);
  59052. }
  59053. function checkTemplateExpression(node) {
  59054. // We just want to check each expressions, but we are unconcerned with
  59055. // the type of each expression, as any value may be coerced into a string.
  59056. // It is worth asking whether this is what we really want though.
  59057. // A place where we actually *are* concerned with the expressions' types are
  59058. // in tagged templates.
  59059. ts.forEach(node.templateSpans, function (templateSpan) {
  59060. if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
  59061. error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
  59062. }
  59063. });
  59064. return stringType;
  59065. }
  59066. function getContextNode(node) {
  59067. if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
  59068. return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes)
  59069. }
  59070. return node;
  59071. }
  59072. function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
  59073. var context = getContextNode(node);
  59074. var saveContextualType = context.contextualType;
  59075. var saveInferenceContext = context.inferenceContext;
  59076. try {
  59077. context.contextualType = contextualType;
  59078. context.inferenceContext = inferenceContext;
  59079. var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
  59080. // We strip literal freshness when an appropriate contextual type is present such that contextually typed
  59081. // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
  59082. // here would be to not mark contextually typed literals as fresh in the first place.
  59083. var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
  59084. getRegularTypeOfLiteralType(type) : type;
  59085. return result;
  59086. }
  59087. finally {
  59088. // In the event our operation is canceled or some other exception occurs, reset the contextual type
  59089. // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
  59090. // may hold onto the checker that created it.
  59091. context.contextualType = saveContextualType;
  59092. context.inferenceContext = saveInferenceContext;
  59093. }
  59094. }
  59095. function checkExpressionCached(node, checkMode) {
  59096. var links = getNodeLinks(node);
  59097. if (!links.resolvedType) {
  59098. if (checkMode && checkMode !== 0 /* Normal */) {
  59099. return checkExpression(node, checkMode);
  59100. }
  59101. // When computing a type that we're going to cache, we need to ignore any ongoing control flow
  59102. // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
  59103. // to the top of the stack ensures all transient types are computed from a known point.
  59104. var saveFlowLoopStart = flowLoopStart;
  59105. var saveFlowTypeCache = flowTypeCache;
  59106. flowLoopStart = flowLoopCount;
  59107. flowTypeCache = undefined;
  59108. links.resolvedType = checkExpression(node, checkMode);
  59109. flowTypeCache = saveFlowTypeCache;
  59110. flowLoopStart = saveFlowLoopStart;
  59111. }
  59112. return links.resolvedType;
  59113. }
  59114. function isTypeAssertion(node) {
  59115. node = ts.skipParentheses(node);
  59116. return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
  59117. }
  59118. function checkDeclarationInitializer(declaration, contextualType) {
  59119. var initializer = ts.getEffectiveInitializer(declaration);
  59120. var type = getQuickTypeOfExpression(initializer) ||
  59121. (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
  59122. return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
  59123. isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
  59124. padTupleType(type, declaration.name) : type;
  59125. }
  59126. function padTupleType(type, pattern) {
  59127. var patternElements = pattern.elements;
  59128. var arity = getTypeReferenceArity(type);
  59129. var elementTypes = arity ? getTypeArguments(type).slice() : [];
  59130. for (var i = arity; i < patternElements.length; i++) {
  59131. var e = patternElements[i];
  59132. if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
  59133. elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
  59134. if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
  59135. reportImplicitAny(e, anyType);
  59136. }
  59137. }
  59138. }
  59139. return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
  59140. }
  59141. function widenTypeInferredFromInitializer(declaration, type) {
  59142. var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
  59143. if (ts.isInJSFile(declaration)) {
  59144. if (widened.flags & 98304 /* Nullable */) {
  59145. reportImplicitAny(declaration, anyType);
  59146. return anyType;
  59147. }
  59148. else if (isEmptyArrayLiteralType(widened)) {
  59149. reportImplicitAny(declaration, anyArrayType);
  59150. return anyArrayType;
  59151. }
  59152. }
  59153. return widened;
  59154. }
  59155. function isLiteralOfContextualType(candidateType, contextualType) {
  59156. if (contextualType) {
  59157. if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
  59158. var types = contextualType.types;
  59159. return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
  59160. }
  59161. if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
  59162. // If the contextual type is a type variable constrained to a primitive type, consider
  59163. // this a literal context for literals of that primitive type. For example, given a
  59164. // type parameter 'T extends string', infer string literal types for T.
  59165. var constraint = getBaseConstraintOfType(contextualType) || unknownType;
  59166. return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
  59167. maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
  59168. maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
  59169. maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
  59170. isLiteralOfContextualType(candidateType, constraint);
  59171. }
  59172. // If the contextual type is a literal of a particular primitive type, we consider this a
  59173. // literal context for all literals of that primitive type.
  59174. return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
  59175. contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
  59176. contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
  59177. contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
  59178. contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
  59179. }
  59180. return false;
  59181. }
  59182. function isConstContext(node) {
  59183. var parent = node.parent;
  59184. return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
  59185. (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
  59186. (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
  59187. }
  59188. function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
  59189. var type = checkExpression(node, checkMode, forceTuple);
  59190. return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
  59191. isTypeAssertion(node) ? type :
  59192. getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
  59193. }
  59194. function checkPropertyAssignment(node, checkMode) {
  59195. // Do not use hasDynamicName here, because that returns false for well known symbols.
  59196. // We want to perform checkComputedPropertyName for all computed properties, including
  59197. // well known symbols.
  59198. if (node.name.kind === 154 /* ComputedPropertyName */) {
  59199. checkComputedPropertyName(node.name);
  59200. }
  59201. return checkExpressionForMutableLocation(node.initializer, checkMode);
  59202. }
  59203. function checkObjectLiteralMethod(node, checkMode) {
  59204. // Grammar checking
  59205. checkGrammarMethod(node);
  59206. // Do not use hasDynamicName here, because that returns false for well known symbols.
  59207. // We want to perform checkComputedPropertyName for all computed properties, including
  59208. // well known symbols.
  59209. if (node.name.kind === 154 /* ComputedPropertyName */) {
  59210. checkComputedPropertyName(node.name);
  59211. }
  59212. var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
  59213. return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
  59214. }
  59215. function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
  59216. if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
  59217. var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
  59218. var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
  59219. var signature = callSignature || constructSignature;
  59220. if (signature && signature.typeParameters) {
  59221. var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
  59222. if (contextualType) {
  59223. var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
  59224. if (contextualSignature && !contextualSignature.typeParameters) {
  59225. if (checkMode & 8 /* SkipGenericFunctions */) {
  59226. skippedGenericFunction(node, checkMode);
  59227. return anyFunctionType;
  59228. }
  59229. var context = getInferenceContext(node);
  59230. // We have an expression that is an argument of a generic function for which we are performing
  59231. // type argument inference. The expression is of a function type with a single generic call
  59232. // signature and a contextual function type with a single non-generic call signature. Now check
  59233. // if the outer function returns a function type with a single non-generic call signature and
  59234. // if some of the outer function type parameters have no inferences so far. If so, we can
  59235. // potentially add inferred type parameters to the outer function return type.
  59236. var returnType = context.signature && getReturnTypeOfSignature(context.signature);
  59237. var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
  59238. if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
  59239. // Instantiate the signature with its own type parameters as type arguments, possibly
  59240. // renaming the type parameters to ensure they have unique names.
  59241. var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
  59242. var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
  59243. // Infer from the parameters of the instantiated signature to the parameters of the
  59244. // contextual signature starting with an empty set of inference candidates.
  59245. var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
  59246. applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
  59247. inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
  59248. });
  59249. if (ts.some(inferences_3, hasInferenceCandidates)) {
  59250. // We have inference candidates, indicating that one or more type parameters are referenced
  59251. // in the parameter types of the contextual signature. Now also infer from the return type.
  59252. applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
  59253. inferTypes(inferences_3, source, target);
  59254. });
  59255. // If the type parameters for which we produced candidates do not have any inferences yet,
  59256. // we adopt the new inference candidates and add the type parameters of the expression type
  59257. // to the set of inferred type parameters for the outer function return type.
  59258. if (!hasOverlappingInferences(context.inferences, inferences_3)) {
  59259. mergeInferences(context.inferences, inferences_3);
  59260. context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
  59261. return getOrCreateTypeFromSignature(instantiatedSignature);
  59262. }
  59263. }
  59264. }
  59265. return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
  59266. }
  59267. }
  59268. }
  59269. }
  59270. return type;
  59271. }
  59272. function skippedGenericFunction(node, checkMode) {
  59273. if (checkMode & 2 /* Inferential */) {
  59274. // We have skipped a generic function during inferential typing. Obtain the inference context and
  59275. // indicate this has occurred such that we know a second pass of inference is be needed.
  59276. var context = getInferenceContext(node);
  59277. context.flags |= 4 /* SkippedGenericFunction */;
  59278. }
  59279. }
  59280. function hasInferenceCandidates(info) {
  59281. return !!(info.candidates || info.contraCandidates);
  59282. }
  59283. function hasOverlappingInferences(a, b) {
  59284. for (var i = 0; i < a.length; i++) {
  59285. if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
  59286. return true;
  59287. }
  59288. }
  59289. return false;
  59290. }
  59291. function mergeInferences(target, source) {
  59292. for (var i = 0; i < target.length; i++) {
  59293. if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
  59294. target[i] = source[i];
  59295. }
  59296. }
  59297. }
  59298. function getUniqueTypeParameters(context, typeParameters) {
  59299. var result = [];
  59300. var oldTypeParameters;
  59301. var newTypeParameters;
  59302. for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
  59303. var tp = typeParameters_2[_i];
  59304. var name = tp.symbol.escapedName;
  59305. if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
  59306. var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
  59307. var symbol = createSymbol(262144 /* TypeParameter */, newName);
  59308. var newTypeParameter = createTypeParameter(symbol);
  59309. newTypeParameter.target = tp;
  59310. oldTypeParameters = ts.append(oldTypeParameters, tp);
  59311. newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
  59312. result.push(newTypeParameter);
  59313. }
  59314. else {
  59315. result.push(tp);
  59316. }
  59317. }
  59318. if (newTypeParameters) {
  59319. var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
  59320. for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
  59321. var tp = newTypeParameters_1[_a];
  59322. tp.mapper = mapper;
  59323. }
  59324. }
  59325. return result;
  59326. }
  59327. function hasTypeParameterByName(typeParameters, name) {
  59328. return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
  59329. }
  59330. function getUniqueTypeParameterName(typeParameters, baseName) {
  59331. var len = baseName.length;
  59332. while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
  59333. len--;
  59334. var s = baseName.slice(0, len);
  59335. for (var index = 1; true; index++) {
  59336. var augmentedName = (s + index);
  59337. if (!hasTypeParameterByName(typeParameters, augmentedName)) {
  59338. return augmentedName;
  59339. }
  59340. }
  59341. }
  59342. function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
  59343. var signature = getSingleCallSignature(funcType);
  59344. if (signature && !signature.typeParameters) {
  59345. return getReturnTypeOfSignature(signature);
  59346. }
  59347. }
  59348. function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
  59349. var funcType = checkExpression(expr.expression);
  59350. var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
  59351. var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
  59352. return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
  59353. }
  59354. /**
  59355. * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
  59356. * with computing the type and may not fully check all contained sub-expressions for errors.
  59357. */
  59358. function getTypeOfExpression(node) {
  59359. // Don't bother caching types that require no flow analysis and are quick to compute.
  59360. var quickType = getQuickTypeOfExpression(node);
  59361. if (quickType) {
  59362. return quickType;
  59363. }
  59364. // If a type has been cached for the node, return it.
  59365. if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
  59366. var cachedType = flowTypeCache[getNodeId(node)];
  59367. if (cachedType) {
  59368. return cachedType;
  59369. }
  59370. }
  59371. var startInvocationCount = flowInvocationCount;
  59372. var type = checkExpression(node);
  59373. // If control flow analysis was required to determine the type, it is worth caching.
  59374. if (flowInvocationCount !== startInvocationCount) {
  59375. var cache = flowTypeCache || (flowTypeCache = []);
  59376. cache[getNodeId(node)] = type;
  59377. node.flags |= 67108864 /* TypeCached */;
  59378. }
  59379. return type;
  59380. }
  59381. function getQuickTypeOfExpression(node) {
  59382. var expr = ts.skipParentheses(node);
  59383. // Optimize for the common case of a call to a function with a single non-generic call
  59384. // signature where we can just fetch the return type without checking the arguments.
  59385. if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
  59386. var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
  59387. getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
  59388. if (type) {
  59389. return type;
  59390. }
  59391. }
  59392. else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
  59393. return getTypeFromTypeNode(expr.type);
  59394. }
  59395. else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
  59396. node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
  59397. return checkExpression(node);
  59398. }
  59399. return undefined;
  59400. }
  59401. /**
  59402. * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
  59403. * with computing the type and may not fully check all contained sub-expressions for errors.
  59404. * It is intended for uses where you know there is no contextual type,
  59405. * and requesting the contextual type might cause a circularity or other bad behaviour.
  59406. * It sets the contextual type of the node to any before calling getTypeOfExpression.
  59407. */
  59408. function getContextFreeTypeOfExpression(node) {
  59409. var links = getNodeLinks(node);
  59410. if (links.contextFreeType) {
  59411. return links.contextFreeType;
  59412. }
  59413. var saveContextualType = node.contextualType;
  59414. node.contextualType = anyType;
  59415. try {
  59416. var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
  59417. return type;
  59418. }
  59419. finally {
  59420. // In the event our operation is canceled or some other exception occurs, reset the contextual type
  59421. // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
  59422. // may hold onto the checker that created it.
  59423. node.contextualType = saveContextualType;
  59424. }
  59425. }
  59426. function checkExpression(node, checkMode, forceTuple) {
  59427. var saveCurrentNode = currentNode;
  59428. currentNode = node;
  59429. instantiationCount = 0;
  59430. var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
  59431. var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
  59432. if (isConstEnumObjectType(type)) {
  59433. checkConstEnumAccess(node, type);
  59434. }
  59435. currentNode = saveCurrentNode;
  59436. return type;
  59437. }
  59438. function checkConstEnumAccess(node, type) {
  59439. // enum object type for const enums are only permitted in:
  59440. // - 'left' in property access
  59441. // - 'object' in indexed access
  59442. // - target in rhs of import statement
  59443. var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
  59444. (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
  59445. ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
  59446. (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
  59447. (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
  59448. if (!ok) {
  59449. error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query);
  59450. }
  59451. if (compilerOptions.isolatedModules) {
  59452. ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
  59453. var constEnumDeclaration = type.symbol.valueDeclaration;
  59454. if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
  59455. error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
  59456. }
  59457. }
  59458. }
  59459. function checkParenthesizedExpression(node, checkMode) {
  59460. var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
  59461. if (tag) {
  59462. return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
  59463. }
  59464. return checkExpression(node.expression, checkMode);
  59465. }
  59466. function checkExpressionWorker(node, checkMode, forceTuple) {
  59467. var kind = node.kind;
  59468. if (cancellationToken) {
  59469. // Only bother checking on a few construct kinds. We don't want to be excessively
  59470. // hitting the cancellation token on every node we check.
  59471. switch (kind) {
  59472. case 214 /* ClassExpression */:
  59473. case 201 /* FunctionExpression */:
  59474. case 202 /* ArrowFunction */:
  59475. cancellationToken.throwIfCancellationRequested();
  59476. }
  59477. }
  59478. switch (kind) {
  59479. case 75 /* Identifier */:
  59480. return checkIdentifier(node);
  59481. case 104 /* ThisKeyword */:
  59482. return checkThisExpression(node);
  59483. case 102 /* SuperKeyword */:
  59484. return checkSuperExpression(node);
  59485. case 100 /* NullKeyword */:
  59486. return nullWideningType;
  59487. case 14 /* NoSubstitutionTemplateLiteral */:
  59488. case 10 /* StringLiteral */:
  59489. return getFreshTypeOfLiteralType(getLiteralType(node.text));
  59490. case 8 /* NumericLiteral */:
  59491. checkGrammarNumericLiteral(node);
  59492. return getFreshTypeOfLiteralType(getLiteralType(+node.text));
  59493. case 9 /* BigIntLiteral */:
  59494. checkGrammarBigIntLiteral(node);
  59495. return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
  59496. case 106 /* TrueKeyword */:
  59497. return trueType;
  59498. case 91 /* FalseKeyword */:
  59499. return falseType;
  59500. case 211 /* TemplateExpression */:
  59501. return checkTemplateExpression(node);
  59502. case 13 /* RegularExpressionLiteral */:
  59503. return globalRegExpType;
  59504. case 192 /* ArrayLiteralExpression */:
  59505. return checkArrayLiteral(node, checkMode, forceTuple);
  59506. case 193 /* ObjectLiteralExpression */:
  59507. return checkObjectLiteral(node, checkMode);
  59508. case 194 /* PropertyAccessExpression */:
  59509. return checkPropertyAccessExpression(node);
  59510. case 153 /* QualifiedName */:
  59511. return checkQualifiedName(node);
  59512. case 195 /* ElementAccessExpression */:
  59513. return checkIndexedAccess(node);
  59514. case 196 /* CallExpression */:
  59515. if (node.expression.kind === 96 /* ImportKeyword */) {
  59516. return checkImportCallExpression(node);
  59517. }
  59518. // falls through
  59519. case 197 /* NewExpression */:
  59520. return checkCallExpression(node, checkMode);
  59521. case 198 /* TaggedTemplateExpression */:
  59522. return checkTaggedTemplateExpression(node);
  59523. case 200 /* ParenthesizedExpression */:
  59524. return checkParenthesizedExpression(node, checkMode);
  59525. case 214 /* ClassExpression */:
  59526. return checkClassExpression(node);
  59527. case 201 /* FunctionExpression */:
  59528. case 202 /* ArrowFunction */:
  59529. return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
  59530. case 204 /* TypeOfExpression */:
  59531. return checkTypeOfExpression(node);
  59532. case 199 /* TypeAssertionExpression */:
  59533. case 217 /* AsExpression */:
  59534. return checkAssertion(node);
  59535. case 218 /* NonNullExpression */:
  59536. return checkNonNullAssertion(node);
  59537. case 219 /* MetaProperty */:
  59538. return checkMetaProperty(node);
  59539. case 203 /* DeleteExpression */:
  59540. return checkDeleteExpression(node);
  59541. case 205 /* VoidExpression */:
  59542. return checkVoidExpression(node);
  59543. case 206 /* AwaitExpression */:
  59544. return checkAwaitExpression(node);
  59545. case 207 /* PrefixUnaryExpression */:
  59546. return checkPrefixUnaryExpression(node);
  59547. case 208 /* PostfixUnaryExpression */:
  59548. return checkPostfixUnaryExpression(node);
  59549. case 209 /* BinaryExpression */:
  59550. return checkBinaryExpression(node, checkMode);
  59551. case 210 /* ConditionalExpression */:
  59552. return checkConditionalExpression(node, checkMode);
  59553. case 213 /* SpreadElement */:
  59554. return checkSpreadExpression(node, checkMode);
  59555. case 215 /* OmittedExpression */:
  59556. return undefinedWideningType;
  59557. case 212 /* YieldExpression */:
  59558. return checkYieldExpression(node);
  59559. case 220 /* SyntheticExpression */:
  59560. return node.type;
  59561. case 276 /* JsxExpression */:
  59562. return checkJsxExpression(node, checkMode);
  59563. case 266 /* JsxElement */:
  59564. return checkJsxElement(node, checkMode);
  59565. case 267 /* JsxSelfClosingElement */:
  59566. return checkJsxSelfClosingElement(node, checkMode);
  59567. case 270 /* JsxFragment */:
  59568. return checkJsxFragment(node);
  59569. case 274 /* JsxAttributes */:
  59570. return checkJsxAttributes(node, checkMode);
  59571. case 268 /* JsxOpeningElement */:
  59572. ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
  59573. }
  59574. return errorType;
  59575. }
  59576. // DECLARATION AND STATEMENT TYPE CHECKING
  59577. function checkTypeParameter(node) {
  59578. // Grammar Checking
  59579. if (node.expression) {
  59580. grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
  59581. }
  59582. checkSourceElement(node.constraint);
  59583. checkSourceElement(node.default);
  59584. var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
  59585. // Resolve base constraint to reveal circularity errors
  59586. getBaseConstraintOfType(typeParameter);
  59587. if (!hasNonCircularTypeParameterDefault(typeParameter)) {
  59588. error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
  59589. }
  59590. var constraintType = getConstraintOfTypeParameter(typeParameter);
  59591. var defaultType = getDefaultFromTypeParameter(typeParameter);
  59592. if (constraintType && defaultType) {
  59593. checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
  59594. }
  59595. if (produceDiagnostics) {
  59596. checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
  59597. }
  59598. }
  59599. function checkParameter(node) {
  59600. // Grammar checking
  59601. // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
  59602. // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
  59603. // or if its FunctionBody is strict code(11.1.5).
  59604. checkGrammarDecoratorsAndModifiers(node);
  59605. checkVariableLikeDeclaration(node);
  59606. var func = ts.getContainingFunction(node);
  59607. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
  59608. if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
  59609. error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
  59610. }
  59611. }
  59612. if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
  59613. error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
  59614. }
  59615. if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
  59616. if (func.parameters.indexOf(node) !== 0) {
  59617. error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
  59618. }
  59619. if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
  59620. error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
  59621. }
  59622. if (func.kind === 202 /* ArrowFunction */) {
  59623. error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
  59624. }
  59625. }
  59626. // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
  59627. // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
  59628. if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
  59629. error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
  59630. }
  59631. }
  59632. function checkTypePredicate(node) {
  59633. var parent = getTypePredicateParent(node);
  59634. if (!parent) {
  59635. // The parent must not be valid.
  59636. error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
  59637. return;
  59638. }
  59639. var signature = getSignatureFromDeclaration(parent);
  59640. var typePredicate = getTypePredicateOfSignature(signature);
  59641. if (!typePredicate) {
  59642. return;
  59643. }
  59644. checkSourceElement(node.type);
  59645. var parameterName = node.parameterName;
  59646. if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
  59647. getTypeFromThisTypeNode(parameterName);
  59648. }
  59649. else {
  59650. if (typePredicate.parameterIndex >= 0) {
  59651. if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
  59652. error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
  59653. }
  59654. else {
  59655. if (typePredicate.type) {
  59656. var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
  59657. checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
  59658. /*headMessage*/ undefined, leadingError);
  59659. }
  59660. }
  59661. }
  59662. else if (parameterName) {
  59663. var hasReportedError = false;
  59664. for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
  59665. var name = _a[_i].name;
  59666. if (ts.isBindingPattern(name) &&
  59667. checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
  59668. hasReportedError = true;
  59669. break;
  59670. }
  59671. }
  59672. if (!hasReportedError) {
  59673. error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
  59674. }
  59675. }
  59676. }
  59677. }
  59678. function getTypePredicateParent(node) {
  59679. switch (node.parent.kind) {
  59680. case 202 /* ArrowFunction */:
  59681. case 165 /* CallSignature */:
  59682. case 244 /* FunctionDeclaration */:
  59683. case 201 /* FunctionExpression */:
  59684. case 170 /* FunctionType */:
  59685. case 161 /* MethodDeclaration */:
  59686. case 160 /* MethodSignature */:
  59687. var parent = node.parent;
  59688. if (node === parent.type) {
  59689. return parent;
  59690. }
  59691. }
  59692. }
  59693. function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
  59694. for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
  59695. var element = _a[_i];
  59696. if (ts.isOmittedExpression(element)) {
  59697. continue;
  59698. }
  59699. var name = element.name;
  59700. if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
  59701. error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
  59702. return true;
  59703. }
  59704. else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
  59705. if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
  59706. return true;
  59707. }
  59708. }
  59709. }
  59710. }
  59711. function checkSignatureDeclaration(node) {
  59712. // Grammar checking
  59713. if (node.kind === 167 /* IndexSignature */) {
  59714. checkGrammarIndexSignature(node);
  59715. }
  59716. // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
  59717. else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
  59718. node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
  59719. node.kind === 166 /* ConstructSignature */) {
  59720. checkGrammarFunctionLikeDeclaration(node);
  59721. }
  59722. var functionFlags = ts.getFunctionFlags(node);
  59723. if (!(functionFlags & 4 /* Invalid */)) {
  59724. // Async generators prior to ESNext require the __await and __asyncGenerator helpers
  59725. if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
  59726. checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
  59727. }
  59728. // Async functions prior to ES2017 require the __awaiter helper
  59729. if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
  59730. checkExternalEmitHelpers(node, 64 /* Awaiter */);
  59731. }
  59732. // Generator functions, Async functions, and Async Generator functions prior to
  59733. // ES2015 require the __generator helper
  59734. if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
  59735. checkExternalEmitHelpers(node, 128 /* Generator */);
  59736. }
  59737. }
  59738. checkTypeParameters(node.typeParameters);
  59739. ts.forEach(node.parameters, checkParameter);
  59740. // TODO(rbuckton): Should we start checking JSDoc types?
  59741. if (node.type) {
  59742. checkSourceElement(node.type);
  59743. }
  59744. if (produceDiagnostics) {
  59745. checkCollisionWithArgumentsInGeneratedCode(node);
  59746. var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
  59747. if (noImplicitAny && !returnTypeNode) {
  59748. switch (node.kind) {
  59749. case 166 /* ConstructSignature */:
  59750. error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
  59751. break;
  59752. case 165 /* CallSignature */:
  59753. error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
  59754. break;
  59755. }
  59756. }
  59757. if (returnTypeNode) {
  59758. var functionFlags_1 = ts.getFunctionFlags(node);
  59759. if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
  59760. var returnType = getTypeFromTypeNode(returnTypeNode);
  59761. if (returnType === voidType) {
  59762. error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
  59763. }
  59764. else {
  59765. // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
  59766. // However, that would not catch the error in the following case.
  59767. //
  59768. // interface BadGenerator extends Iterable<number>, Iterator<string> { }
  59769. // function* g(): BadGenerator { } // Iterable and Iterator have different types!
  59770. //
  59771. var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
  59772. var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
  59773. var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
  59774. var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
  59775. checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
  59776. }
  59777. }
  59778. else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
  59779. checkAsyncFunctionReturnType(node, returnTypeNode);
  59780. }
  59781. }
  59782. if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
  59783. registerForUnusedIdentifiersCheck(node);
  59784. }
  59785. }
  59786. }
  59787. function checkClassForDuplicateDeclarations(node) {
  59788. var instanceNames = ts.createUnderscoreEscapedMap();
  59789. var staticNames = ts.createUnderscoreEscapedMap();
  59790. // instance and static private identifiers share the same scope
  59791. var privateIdentifiers = ts.createUnderscoreEscapedMap();
  59792. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  59793. var member = _a[_i];
  59794. if (member.kind === 162 /* Constructor */) {
  59795. for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
  59796. var param = _c[_b];
  59797. if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
  59798. addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
  59799. }
  59800. }
  59801. }
  59802. else {
  59803. var isStatic = ts.hasModifier(member, 32 /* Static */);
  59804. var name = member.name;
  59805. if (!name) {
  59806. return;
  59807. }
  59808. var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
  59809. isStatic ? staticNames :
  59810. instanceNames;
  59811. var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
  59812. if (memberName) {
  59813. switch (member.kind) {
  59814. case 163 /* GetAccessor */:
  59815. addName(names, name, memberName, 1 /* GetAccessor */);
  59816. break;
  59817. case 164 /* SetAccessor */:
  59818. addName(names, name, memberName, 2 /* SetAccessor */);
  59819. break;
  59820. case 159 /* PropertyDeclaration */:
  59821. addName(names, name, memberName, 3 /* GetOrSetAccessor */);
  59822. break;
  59823. case 161 /* MethodDeclaration */:
  59824. addName(names, name, memberName, 8 /* Method */);
  59825. break;
  59826. }
  59827. }
  59828. }
  59829. }
  59830. function addName(names, location, name, meaning) {
  59831. var prev = names.get(name);
  59832. if (prev) {
  59833. if (prev & 8 /* Method */) {
  59834. if (meaning !== 8 /* Method */) {
  59835. error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
  59836. }
  59837. }
  59838. else if (prev & meaning) {
  59839. error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
  59840. }
  59841. else {
  59842. names.set(name, prev | meaning);
  59843. }
  59844. }
  59845. else {
  59846. names.set(name, meaning);
  59847. }
  59848. }
  59849. }
  59850. /**
  59851. * Static members being set on a constructor function may conflict with built-in properties
  59852. * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
  59853. * built-in properties. This check issues a transpile error when a class has a static
  59854. * member with the same name as a non-writable built-in property.
  59855. *
  59856. * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
  59857. * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
  59858. * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
  59859. * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
  59860. */
  59861. function checkClassForStaticPropertyNameConflicts(node) {
  59862. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  59863. var member = _a[_i];
  59864. var memberNameNode = member.name;
  59865. var isStatic = ts.hasModifier(member, 32 /* Static */);
  59866. if (isStatic && memberNameNode) {
  59867. var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
  59868. switch (memberName) {
  59869. case "name":
  59870. case "length":
  59871. case "caller":
  59872. case "arguments":
  59873. case "prototype":
  59874. var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
  59875. var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
  59876. error(memberNameNode, message, memberName, className);
  59877. break;
  59878. }
  59879. }
  59880. }
  59881. }
  59882. function checkObjectTypeForDuplicateDeclarations(node) {
  59883. var names = ts.createMap();
  59884. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  59885. var member = _a[_i];
  59886. if (member.kind === 158 /* PropertySignature */) {
  59887. var memberName = void 0;
  59888. var name = member.name;
  59889. switch (name.kind) {
  59890. case 10 /* StringLiteral */:
  59891. case 8 /* NumericLiteral */:
  59892. memberName = name.text;
  59893. break;
  59894. case 75 /* Identifier */:
  59895. memberName = ts.idText(name);
  59896. break;
  59897. default:
  59898. continue;
  59899. }
  59900. if (names.get(memberName)) {
  59901. error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
  59902. error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
  59903. }
  59904. else {
  59905. names.set(memberName, true);
  59906. }
  59907. }
  59908. }
  59909. }
  59910. function checkTypeForDuplicateIndexSignatures(node) {
  59911. if (node.kind === 246 /* InterfaceDeclaration */) {
  59912. var nodeSymbol = getSymbolOfNode(node);
  59913. // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
  59914. // to prevent this run check only for the first declaration of a given kind
  59915. if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
  59916. return;
  59917. }
  59918. }
  59919. // TypeScript 1.0 spec (April 2014)
  59920. // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
  59921. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
  59922. var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
  59923. if (indexSymbol) {
  59924. var seenNumericIndexer = false;
  59925. var seenStringIndexer = false;
  59926. for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
  59927. var decl = _a[_i];
  59928. var declaration = decl;
  59929. if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
  59930. switch (declaration.parameters[0].type.kind) {
  59931. case 143 /* StringKeyword */:
  59932. if (!seenStringIndexer) {
  59933. seenStringIndexer = true;
  59934. }
  59935. else {
  59936. error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
  59937. }
  59938. break;
  59939. case 140 /* NumberKeyword */:
  59940. if (!seenNumericIndexer) {
  59941. seenNumericIndexer = true;
  59942. }
  59943. else {
  59944. error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
  59945. }
  59946. break;
  59947. }
  59948. }
  59949. }
  59950. }
  59951. }
  59952. function checkPropertyDeclaration(node) {
  59953. // Grammar checking
  59954. if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
  59955. checkGrammarComputedPropertyName(node.name);
  59956. checkVariableLikeDeclaration(node);
  59957. // Private class fields transformation relies on WeakMaps.
  59958. if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
  59959. for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
  59960. getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
  59961. }
  59962. }
  59963. }
  59964. function checkPropertySignature(node) {
  59965. if (ts.isPrivateIdentifier(node.name)) {
  59966. error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
  59967. }
  59968. return checkPropertyDeclaration(node);
  59969. }
  59970. function checkMethodDeclaration(node) {
  59971. // Grammar checking
  59972. if (!checkGrammarMethod(node))
  59973. checkGrammarComputedPropertyName(node.name);
  59974. if (ts.isPrivateIdentifier(node.name)) {
  59975. error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
  59976. }
  59977. // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
  59978. checkFunctionOrMethodDeclaration(node);
  59979. // Abstract methods cannot have an implementation.
  59980. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
  59981. if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
  59982. error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
  59983. }
  59984. }
  59985. function checkConstructorDeclaration(node) {
  59986. // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
  59987. checkSignatureDeclaration(node);
  59988. // Grammar check for checking only related to constructorDeclaration
  59989. if (!checkGrammarConstructorTypeParameters(node))
  59990. checkGrammarConstructorTypeAnnotation(node);
  59991. checkSourceElement(node.body);
  59992. var symbol = getSymbolOfNode(node);
  59993. var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
  59994. // Only type check the symbol once
  59995. if (node === firstDeclaration) {
  59996. checkFunctionOrConstructorSymbol(symbol);
  59997. }
  59998. // exit early in the case of signature - super checks are not relevant to them
  59999. if (ts.nodeIsMissing(node.body)) {
  60000. return;
  60001. }
  60002. if (!produceDiagnostics) {
  60003. return;
  60004. }
  60005. function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
  60006. if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
  60007. return true;
  60008. }
  60009. return n.kind === 159 /* PropertyDeclaration */ &&
  60010. !ts.hasModifier(n, 32 /* Static */) &&
  60011. !!n.initializer;
  60012. }
  60013. // TS 1.0 spec (April 2014): 8.3.2
  60014. // Constructors of classes with no extends clause may not contain super calls, whereas
  60015. // constructors of derived classes must contain at least one super call somewhere in their function body.
  60016. var containingClassDecl = node.parent;
  60017. if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
  60018. captureLexicalThis(node.parent, containingClassDecl);
  60019. var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
  60020. var superCall = getSuperCallInConstructor(node);
  60021. if (superCall) {
  60022. if (classExtendsNull) {
  60023. error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
  60024. }
  60025. // The first statement in the body of a constructor (excluding prologue directives) must be a super call
  60026. // if both of the following are true:
  60027. // - The containing class is a derived class.
  60028. // - The constructor declares parameter properties
  60029. // or the containing class declares instance member variables with initializers.
  60030. var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
  60031. ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); });
  60032. // Skip past any prologue directives to find the first statement
  60033. // to ensure that it was a super call.
  60034. if (superCallShouldBeFirst) {
  60035. var statements = node.body.statements;
  60036. var superCallStatement = void 0;
  60037. for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
  60038. var statement = statements_3[_i];
  60039. if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
  60040. superCallStatement = statement;
  60041. break;
  60042. }
  60043. if (!ts.isPrologueDirective(statement)) {
  60044. break;
  60045. }
  60046. }
  60047. if (!superCallStatement) {
  60048. error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers);
  60049. }
  60050. }
  60051. }
  60052. else if (!classExtendsNull) {
  60053. error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
  60054. }
  60055. }
  60056. }
  60057. function checkAccessorDeclaration(node) {
  60058. if (produceDiagnostics) {
  60059. // Grammar checking accessors
  60060. if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
  60061. checkGrammarComputedPropertyName(node.name);
  60062. checkDecorators(node);
  60063. checkSignatureDeclaration(node);
  60064. if (node.kind === 163 /* GetAccessor */) {
  60065. if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
  60066. if (!(node.flags & 512 /* HasExplicitReturn */)) {
  60067. error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
  60068. }
  60069. }
  60070. }
  60071. // Do not use hasDynamicName here, because that returns false for well known symbols.
  60072. // We want to perform checkComputedPropertyName for all computed properties, including
  60073. // well known symbols.
  60074. if (node.name.kind === 154 /* ComputedPropertyName */) {
  60075. checkComputedPropertyName(node.name);
  60076. }
  60077. if (ts.isPrivateIdentifier(node.name)) {
  60078. error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
  60079. }
  60080. if (!hasNonBindableDynamicName(node)) {
  60081. // TypeScript 1.0 spec (April 2014): 8.4.3
  60082. // Accessors for the same member name must specify the same accessibility.
  60083. var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
  60084. var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
  60085. if (otherAccessor) {
  60086. var nodeFlags = ts.getModifierFlags(node);
  60087. var otherFlags = ts.getModifierFlags(otherAccessor);
  60088. if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
  60089. error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
  60090. }
  60091. if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
  60092. error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
  60093. }
  60094. // TypeScript 1.0 spec (April 2014): 4.5
  60095. // If both accessors include type annotations, the specified types must be identical.
  60096. checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
  60097. checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
  60098. }
  60099. }
  60100. var returnType = getTypeOfAccessors(getSymbolOfNode(node));
  60101. if (node.kind === 163 /* GetAccessor */) {
  60102. checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
  60103. }
  60104. }
  60105. checkSourceElement(node.body);
  60106. }
  60107. function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
  60108. var firstType = getAnnotatedType(first);
  60109. var secondType = getAnnotatedType(second);
  60110. if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
  60111. error(first, message);
  60112. }
  60113. }
  60114. function checkMissingDeclaration(node) {
  60115. checkDecorators(node);
  60116. }
  60117. function getEffectiveTypeArguments(node, typeParameters) {
  60118. return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
  60119. }
  60120. function checkTypeArgumentConstraints(node, typeParameters) {
  60121. var typeArguments;
  60122. var mapper;
  60123. var result = true;
  60124. for (var i = 0; i < typeParameters.length; i++) {
  60125. var constraint = getConstraintOfTypeParameter(typeParameters[i]);
  60126. if (constraint) {
  60127. if (!typeArguments) {
  60128. typeArguments = getEffectiveTypeArguments(node, typeParameters);
  60129. mapper = createTypeMapper(typeParameters, typeArguments);
  60130. }
  60131. result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
  60132. }
  60133. }
  60134. return result;
  60135. }
  60136. function getTypeParametersForTypeReference(node) {
  60137. var type = getTypeFromTypeReference(node);
  60138. if (type !== errorType) {
  60139. var symbol = getNodeLinks(node).resolvedSymbol;
  60140. if (symbol) {
  60141. return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
  60142. (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
  60143. }
  60144. }
  60145. return undefined;
  60146. }
  60147. function checkTypeReferenceNode(node) {
  60148. checkGrammarTypeArguments(node, node.typeArguments);
  60149. if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
  60150. grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
  60151. }
  60152. ts.forEach(node.typeArguments, checkSourceElement);
  60153. var type = getTypeFromTypeReference(node);
  60154. if (type !== errorType) {
  60155. if (node.typeArguments && produceDiagnostics) {
  60156. var typeParameters = getTypeParametersForTypeReference(node);
  60157. if (typeParameters) {
  60158. checkTypeArgumentConstraints(node, typeParameters);
  60159. }
  60160. }
  60161. if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
  60162. error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
  60163. }
  60164. }
  60165. }
  60166. function getTypeArgumentConstraint(node) {
  60167. var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
  60168. if (!typeReferenceNode)
  60169. return undefined;
  60170. var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
  60171. var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
  60172. return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
  60173. }
  60174. function checkTypeQuery(node) {
  60175. getTypeFromTypeQueryNode(node);
  60176. }
  60177. function checkTypeLiteral(node) {
  60178. ts.forEach(node.members, checkSourceElement);
  60179. if (produceDiagnostics) {
  60180. var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
  60181. checkIndexConstraints(type);
  60182. checkTypeForDuplicateIndexSignatures(node);
  60183. checkObjectTypeForDuplicateDeclarations(node);
  60184. }
  60185. }
  60186. function checkArrayType(node) {
  60187. checkSourceElement(node.elementType);
  60188. }
  60189. function checkTupleType(node) {
  60190. var elementTypes = node.elementTypes;
  60191. var seenOptionalElement = false;
  60192. for (var i = 0; i < elementTypes.length; i++) {
  60193. var e = elementTypes[i];
  60194. if (e.kind === 177 /* RestType */) {
  60195. if (i !== elementTypes.length - 1) {
  60196. grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
  60197. break;
  60198. }
  60199. if (!isArrayType(getTypeFromTypeNode(e.type))) {
  60200. error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
  60201. }
  60202. }
  60203. else if (e.kind === 176 /* OptionalType */) {
  60204. seenOptionalElement = true;
  60205. }
  60206. else if (seenOptionalElement) {
  60207. grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
  60208. break;
  60209. }
  60210. }
  60211. ts.forEach(node.elementTypes, checkSourceElement);
  60212. }
  60213. function checkUnionOrIntersectionType(node) {
  60214. ts.forEach(node.types, checkSourceElement);
  60215. }
  60216. function checkIndexedAccessIndexType(type, accessNode) {
  60217. if (!(type.flags & 8388608 /* IndexedAccess */)) {
  60218. return type;
  60219. }
  60220. // Check if the index type is assignable to 'keyof T' for the object type.
  60221. var objectType = type.objectType;
  60222. var indexType = type.indexType;
  60223. if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
  60224. if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
  60225. ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
  60226. error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
  60227. }
  60228. return type;
  60229. }
  60230. // Check if we're indexing with a numeric type and if either object or index types
  60231. // is a generic type with a constraint that has a numeric index signature.
  60232. var apparentObjectType = getApparentType(objectType);
  60233. if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
  60234. return type;
  60235. }
  60236. if (isGenericObjectType(objectType)) {
  60237. var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
  60238. if (propertyName_1) {
  60239. var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
  60240. if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
  60241. error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
  60242. return errorType;
  60243. }
  60244. }
  60245. }
  60246. error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
  60247. return errorType;
  60248. }
  60249. function checkIndexedAccessType(node) {
  60250. checkSourceElement(node.objectType);
  60251. checkSourceElement(node.indexType);
  60252. checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
  60253. }
  60254. function checkMappedType(node) {
  60255. checkSourceElement(node.typeParameter);
  60256. checkSourceElement(node.type);
  60257. if (!node.type) {
  60258. reportImplicitAny(node, anyType);
  60259. }
  60260. var type = getTypeFromMappedTypeNode(node);
  60261. var constraintType = getConstraintTypeFromMappedType(type);
  60262. checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
  60263. }
  60264. function checkThisType(node) {
  60265. getTypeFromThisTypeNode(node);
  60266. }
  60267. function checkTypeOperator(node) {
  60268. checkGrammarTypeOperatorNode(node);
  60269. checkSourceElement(node.type);
  60270. }
  60271. function checkConditionalType(node) {
  60272. ts.forEachChild(node, checkSourceElement);
  60273. }
  60274. function checkInferType(node) {
  60275. if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
  60276. grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
  60277. }
  60278. checkSourceElement(node.typeParameter);
  60279. registerForUnusedIdentifiersCheck(node);
  60280. }
  60281. function checkImportType(node) {
  60282. checkSourceElement(node.argument);
  60283. getTypeFromTypeNode(node);
  60284. }
  60285. function isPrivateWithinAmbient(node) {
  60286. return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
  60287. }
  60288. function getEffectiveDeclarationFlags(n, flagsToCheck) {
  60289. var flags = ts.getCombinedModifierFlags(n);
  60290. // children of classes (even ambient classes) should not be marked as ambient or export
  60291. // because those flags have no useful semantics there.
  60292. if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
  60293. n.parent.kind !== 245 /* ClassDeclaration */ &&
  60294. n.parent.kind !== 214 /* ClassExpression */ &&
  60295. n.flags & 8388608 /* Ambient */) {
  60296. if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
  60297. // It is nested in an ambient context, which means it is automatically exported
  60298. flags |= 1 /* Export */;
  60299. }
  60300. flags |= 2 /* Ambient */;
  60301. }
  60302. return flags & flagsToCheck;
  60303. }
  60304. function checkFunctionOrConstructorSymbol(symbol) {
  60305. if (!produceDiagnostics) {
  60306. return;
  60307. }
  60308. function getCanonicalOverload(overloads, implementation) {
  60309. // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
  60310. // Error on all deviations from this canonical set of flags
  60311. // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
  60312. // report the errors on those. To achieve this, we will say that the implementation is
  60313. // the canonical signature only if it is in the same container as the first overload
  60314. var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
  60315. return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
  60316. }
  60317. function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
  60318. // Error if some overloads have a flag that is not shared by all overloads. To find the
  60319. // deviations, we XOR someOverloadFlags with allOverloadFlags
  60320. var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
  60321. if (someButNotAllOverloadFlags !== 0) {
  60322. var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
  60323. ts.forEach(overloads, function (o) {
  60324. var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
  60325. if (deviation & 1 /* Export */) {
  60326. error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
  60327. }
  60328. else if (deviation & 2 /* Ambient */) {
  60329. error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
  60330. }
  60331. else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
  60332. error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
  60333. }
  60334. else if (deviation & 128 /* Abstract */) {
  60335. error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
  60336. }
  60337. });
  60338. }
  60339. }
  60340. function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
  60341. if (someHaveQuestionToken !== allHaveQuestionToken) {
  60342. var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
  60343. ts.forEach(overloads, function (o) {
  60344. var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
  60345. if (deviation) {
  60346. error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
  60347. }
  60348. });
  60349. }
  60350. }
  60351. var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
  60352. var someNodeFlags = 0 /* None */;
  60353. var allNodeFlags = flagsToCheck;
  60354. var someHaveQuestionToken = false;
  60355. var allHaveQuestionToken = true;
  60356. var hasOverloads = false;
  60357. var bodyDeclaration;
  60358. var lastSeenNonAmbientDeclaration;
  60359. var previousDeclaration;
  60360. var declarations = symbol.declarations;
  60361. var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
  60362. function reportImplementationExpectedError(node) {
  60363. if (node.name && ts.nodeIsMissing(node.name)) {
  60364. return;
  60365. }
  60366. var seen = false;
  60367. var subsequentNode = ts.forEachChild(node.parent, function (c) {
  60368. if (seen) {
  60369. return c;
  60370. }
  60371. else {
  60372. seen = c === node;
  60373. }
  60374. });
  60375. // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
  60376. // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
  60377. if (subsequentNode && subsequentNode.pos === node.end) {
  60378. if (subsequentNode.kind === node.kind) {
  60379. var errorNode_1 = subsequentNode.name || subsequentNode;
  60380. var subsequentName = subsequentNode.name;
  60381. if (node.name && subsequentName && (
  60382. // both are private identifiers
  60383. ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
  60384. // Both are computed property names
  60385. // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
  60386. ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
  60387. // Both are literal property names that are the same.
  60388. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
  60389. ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
  60390. var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
  60391. ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
  60392. // we can get here in two cases
  60393. // 1. mixed static and instance class members
  60394. // 2. something with the same name was defined before the set of overloads that prevents them from merging
  60395. // here we'll report error only for the first case since for second we should already report error in binder
  60396. if (reportError) {
  60397. var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
  60398. error(errorNode_1, diagnostic);
  60399. }
  60400. return;
  60401. }
  60402. if (ts.nodeIsPresent(subsequentNode.body)) {
  60403. error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
  60404. return;
  60405. }
  60406. }
  60407. }
  60408. var errorNode = node.name || node;
  60409. if (isConstructor) {
  60410. error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
  60411. }
  60412. else {
  60413. // Report different errors regarding non-consecutive blocks of declarations depending on whether
  60414. // the node in question is abstract.
  60415. if (ts.hasModifier(node, 128 /* Abstract */)) {
  60416. error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
  60417. }
  60418. else {
  60419. error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
  60420. }
  60421. }
  60422. }
  60423. var duplicateFunctionDeclaration = false;
  60424. var multipleConstructorImplementation = false;
  60425. var hasNonAmbientClass = false;
  60426. for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
  60427. var current = declarations_4[_i];
  60428. var node = current;
  60429. var inAmbientContext = node.flags & 8388608 /* Ambient */;
  60430. var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
  60431. if (inAmbientContextOrInterface) {
  60432. // check if declarations are consecutive only if they are non-ambient
  60433. // 1. ambient declarations can be interleaved
  60434. // i.e. this is legal
  60435. // declare function foo();
  60436. // declare function bar();
  60437. // declare function foo();
  60438. // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
  60439. previousDeclaration = undefined;
  60440. }
  60441. if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
  60442. hasNonAmbientClass = true;
  60443. }
  60444. if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
  60445. var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
  60446. someNodeFlags |= currentNodeFlags;
  60447. allNodeFlags &= currentNodeFlags;
  60448. someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
  60449. allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
  60450. if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
  60451. if (isConstructor) {
  60452. multipleConstructorImplementation = true;
  60453. }
  60454. else {
  60455. duplicateFunctionDeclaration = true;
  60456. }
  60457. }
  60458. else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
  60459. reportImplementationExpectedError(previousDeclaration);
  60460. }
  60461. if (ts.nodeIsPresent(node.body)) {
  60462. if (!bodyDeclaration) {
  60463. bodyDeclaration = node;
  60464. }
  60465. }
  60466. else {
  60467. hasOverloads = true;
  60468. }
  60469. previousDeclaration = node;
  60470. if (!inAmbientContextOrInterface) {
  60471. lastSeenNonAmbientDeclaration = node;
  60472. }
  60473. }
  60474. }
  60475. if (multipleConstructorImplementation) {
  60476. ts.forEach(declarations, function (declaration) {
  60477. error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
  60478. });
  60479. }
  60480. if (duplicateFunctionDeclaration) {
  60481. ts.forEach(declarations, function (declaration) {
  60482. error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
  60483. });
  60484. }
  60485. if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
  60486. // A non-ambient class cannot be an implementation for a non-constructor function/class merge
  60487. // TODO: The below just replicates our older error from when classes and functions were
  60488. // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
  60489. // might be warranted. :shrug:
  60490. ts.forEach(declarations, function (declaration) {
  60491. addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; }));
  60492. });
  60493. }
  60494. // Abstract methods can't have an implementation -- in particular, they don't need one.
  60495. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
  60496. !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
  60497. reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
  60498. }
  60499. if (hasOverloads) {
  60500. checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
  60501. checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
  60502. if (bodyDeclaration) {
  60503. var signatures = getSignaturesOfSymbol(symbol);
  60504. var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
  60505. for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
  60506. var signature = signatures_10[_a];
  60507. if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
  60508. ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
  60509. break;
  60510. }
  60511. }
  60512. }
  60513. }
  60514. }
  60515. function checkExportsOnMergedDeclarations(node) {
  60516. if (!produceDiagnostics) {
  60517. return;
  60518. }
  60519. // if localSymbol is defined on node then node itself is exported - check is required
  60520. var symbol = node.localSymbol;
  60521. if (!symbol) {
  60522. // local symbol is undefined => this declaration is non-exported.
  60523. // however symbol might contain other declarations that are exported
  60524. symbol = getSymbolOfNode(node);
  60525. if (!symbol.exportSymbol) {
  60526. // this is a pure local symbol (all declarations are non-exported) - no need to check anything
  60527. return;
  60528. }
  60529. }
  60530. // run the check only for the first declaration in the list
  60531. if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
  60532. return;
  60533. }
  60534. var exportedDeclarationSpaces = 0 /* None */;
  60535. var nonExportedDeclarationSpaces = 0 /* None */;
  60536. var defaultExportedDeclarationSpaces = 0 /* None */;
  60537. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  60538. var d = _a[_i];
  60539. var declarationSpaces = getDeclarationSpaces(d);
  60540. var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
  60541. if (effectiveDeclarationFlags & 1 /* Export */) {
  60542. if (effectiveDeclarationFlags & 512 /* Default */) {
  60543. defaultExportedDeclarationSpaces |= declarationSpaces;
  60544. }
  60545. else {
  60546. exportedDeclarationSpaces |= declarationSpaces;
  60547. }
  60548. }
  60549. else {
  60550. nonExportedDeclarationSpaces |= declarationSpaces;
  60551. }
  60552. }
  60553. // Spaces for anything not declared a 'default export'.
  60554. var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
  60555. var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
  60556. var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
  60557. if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
  60558. // declaration spaces for exported and non-exported declarations intersect
  60559. for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
  60560. var d = _c[_b];
  60561. var declarationSpaces = getDeclarationSpaces(d);
  60562. var name = ts.getNameOfDeclaration(d);
  60563. // Only error on the declarations that contributed to the intersecting spaces.
  60564. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
  60565. error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name));
  60566. }
  60567. else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
  60568. error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
  60569. }
  60570. }
  60571. }
  60572. function getDeclarationSpaces(decl) {
  60573. var d = decl;
  60574. switch (d.kind) {
  60575. case 246 /* InterfaceDeclaration */:
  60576. case 247 /* TypeAliasDeclaration */:
  60577. // A jsdoc typedef and callback are, by definition, type aliases.
  60578. // falls through
  60579. case 321 /* JSDocTypedefTag */:
  60580. case 314 /* JSDocCallbackTag */:
  60581. case 315 /* JSDocEnumTag */:
  60582. return 2 /* ExportType */;
  60583. case 249 /* ModuleDeclaration */:
  60584. return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
  60585. ? 4 /* ExportNamespace */ | 1 /* ExportValue */
  60586. : 4 /* ExportNamespace */;
  60587. case 245 /* ClassDeclaration */:
  60588. case 248 /* EnumDeclaration */:
  60589. case 284 /* EnumMember */:
  60590. return 2 /* ExportType */ | 1 /* ExportValue */;
  60591. case 290 /* SourceFile */:
  60592. return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
  60593. case 259 /* ExportAssignment */:
  60594. // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
  60595. if (!ts.isEntityNameExpression(d.expression)) {
  60596. return 1 /* ExportValue */;
  60597. }
  60598. d = d.expression;
  60599. // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
  60600. // falls through
  60601. case 253 /* ImportEqualsDeclaration */:
  60602. case 256 /* NamespaceImport */:
  60603. case 255 /* ImportClause */:
  60604. var result_7 = 0 /* None */;
  60605. var target = resolveAlias(getSymbolOfNode(d));
  60606. ts.forEach(target.declarations, function (d) { result_7 |= getDeclarationSpaces(d); });
  60607. return result_7;
  60608. case 242 /* VariableDeclaration */:
  60609. case 191 /* BindingElement */:
  60610. case 244 /* FunctionDeclaration */:
  60611. case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
  60612. case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
  60613. // Identifiers are used as declarations of assignment declarations whose parents may be
  60614. // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
  60615. // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
  60616. // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
  60617. // all of which are pretty much always values, or at least imply a value meaning.
  60618. // It may be apprpriate to treat these as aliases in the future.
  60619. return 1 /* ExportValue */;
  60620. default:
  60621. return ts.Debug.failBadSyntaxKind(d);
  60622. }
  60623. }
  60624. }
  60625. function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
  60626. var promisedType = getPromisedTypeOfPromise(type, errorNode);
  60627. return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
  60628. }
  60629. /**
  60630. * Gets the "promised type" of a promise.
  60631. * @param type The type of the promise.
  60632. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
  60633. */
  60634. function getPromisedTypeOfPromise(promise, errorNode) {
  60635. //
  60636. // { // promise
  60637. // then( // thenFunction
  60638. // onfulfilled: ( // onfulfilledParameterType
  60639. // value: T // valueParameterType
  60640. // ) => any
  60641. // ): any;
  60642. // }
  60643. //
  60644. if (isTypeAny(promise)) {
  60645. return undefined;
  60646. }
  60647. var typeAsPromise = promise;
  60648. if (typeAsPromise.promisedTypeOfPromise) {
  60649. return typeAsPromise.promisedTypeOfPromise;
  60650. }
  60651. if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) {
  60652. return typeAsPromise.promisedTypeOfPromise = getTypeArguments(promise)[0];
  60653. }
  60654. var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217
  60655. if (isTypeAny(thenFunction)) {
  60656. return undefined;
  60657. }
  60658. var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
  60659. if (thenSignatures.length === 0) {
  60660. if (errorNode) {
  60661. error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
  60662. }
  60663. return undefined;
  60664. }
  60665. var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
  60666. if (isTypeAny(onfulfilledParameterType)) {
  60667. return undefined;
  60668. }
  60669. var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
  60670. if (onfulfilledParameterSignatures.length === 0) {
  60671. if (errorNode) {
  60672. error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
  60673. }
  60674. return undefined;
  60675. }
  60676. return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
  60677. }
  60678. /**
  60679. * Gets the "awaited type" of a type.
  60680. * @param type The type to await.
  60681. * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
  60682. * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
  60683. * The runtime behavior of the `await` keyword.
  60684. */
  60685. function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
  60686. var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
  60687. return awaitedType || errorType;
  60688. }
  60689. function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
  60690. var typeAsAwaitable = type;
  60691. if (typeAsAwaitable.awaitedTypeOfType) {
  60692. return typeAsAwaitable.awaitedTypeOfType;
  60693. }
  60694. if (isTypeAny(type)) {
  60695. return typeAsAwaitable.awaitedTypeOfType = type;
  60696. }
  60697. if (type.flags & 1048576 /* Union */) {
  60698. var types = void 0;
  60699. for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
  60700. var constituentType = _a[_i];
  60701. types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage, arg0));
  60702. }
  60703. if (!types) {
  60704. return undefined;
  60705. }
  60706. return typeAsAwaitable.awaitedTypeOfType = getUnionType(types);
  60707. }
  60708. var promisedType = getPromisedTypeOfPromise(type);
  60709. if (promisedType) {
  60710. if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) {
  60711. // Verify that we don't have a bad actor in the form of a promise whose
  60712. // promised type is the same as the promise type, or a mutually recursive
  60713. // promise. If so, we return undefined as we cannot guess the shape. If this
  60714. // were the actual case in the JavaScript, this Promise would never resolve.
  60715. //
  60716. // An example of a bad actor with a singly-recursive promise type might
  60717. // be:
  60718. //
  60719. // interface BadPromise {
  60720. // then(
  60721. // onfulfilled: (value: BadPromise) => any,
  60722. // onrejected: (error: any) => any): BadPromise;
  60723. // }
  60724. // The above interface will pass the PromiseLike check, and return a
  60725. // promised type of `BadPromise`. Since this is a self reference, we
  60726. // don't want to keep recursing ad infinitum.
  60727. //
  60728. // An example of a bad actor in the form of a mutually-recursive
  60729. // promise type might be:
  60730. //
  60731. // interface BadPromiseA {
  60732. // then(
  60733. // onfulfilled: (value: BadPromiseB) => any,
  60734. // onrejected: (error: any) => any): BadPromiseB;
  60735. // }
  60736. //
  60737. // interface BadPromiseB {
  60738. // then(
  60739. // onfulfilled: (value: BadPromiseA) => any,
  60740. // onrejected: (error: any) => any): BadPromiseA;
  60741. // }
  60742. //
  60743. if (errorNode) {
  60744. error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
  60745. }
  60746. return undefined;
  60747. }
  60748. // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
  60749. // See the comments above for more information.
  60750. awaitedTypeStack.push(type.id);
  60751. var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
  60752. awaitedTypeStack.pop();
  60753. if (!awaitedType) {
  60754. return undefined;
  60755. }
  60756. return typeAsAwaitable.awaitedTypeOfType = awaitedType;
  60757. }
  60758. // The type was not a promise, so it could not be unwrapped any further.
  60759. // As long as the type does not have a callable "then" property, it is
  60760. // safe to return the type; otherwise, an error will be reported in
  60761. // the call to getNonThenableType and we will return undefined.
  60762. //
  60763. // An example of a non-promise "thenable" might be:
  60764. //
  60765. // await { then(): void {} }
  60766. //
  60767. // The "thenable" does not match the minimal definition for a promise. When
  60768. // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
  60769. // will never settle. We treat this as an error to help flag an early indicator
  60770. // of a runtime problem. If the user wants to return this value from an async
  60771. // function, they would need to wrap it in some other value. If they want it to
  60772. // be treated as a promise, they can cast to <any>.
  60773. var thenFunction = getTypeOfPropertyOfType(type, "then");
  60774. if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) {
  60775. if (errorNode) {
  60776. if (!diagnosticMessage)
  60777. return ts.Debug.fail();
  60778. error(errorNode, diagnosticMessage, arg0);
  60779. }
  60780. return undefined;
  60781. }
  60782. return typeAsAwaitable.awaitedTypeOfType = type;
  60783. }
  60784. /**
  60785. * Checks the return type of an async function to ensure it is a compatible
  60786. * Promise implementation.
  60787. *
  60788. * This checks that an async function has a valid Promise-compatible return type.
  60789. * An async function has a valid Promise-compatible return type if the resolved value
  60790. * of the return type has a construct signature that takes in an `initializer` function
  60791. * that in turn supplies a `resolve` function as one of its arguments and results in an
  60792. * object with a callable `then` signature.
  60793. *
  60794. * @param node The signature to check
  60795. */
  60796. function checkAsyncFunctionReturnType(node, returnTypeNode) {
  60797. // As part of our emit for an async function, we will need to emit the entity name of
  60798. // the return type annotation as an expression. To meet the necessary runtime semantics
  60799. // for __awaiter, we must also check that the type of the declaration (e.g. the static
  60800. // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
  60801. //
  60802. // An example might be (from lib.es6.d.ts):
  60803. //
  60804. // interface Promise<T> { ... }
  60805. // interface PromiseConstructor {
  60806. // new <T>(...): Promise<T>;
  60807. // }
  60808. // declare var Promise: PromiseConstructor;
  60809. //
  60810. // When an async function declares a return type annotation of `Promise<T>`, we
  60811. // need to get the type of the `Promise` variable declaration above, which would
  60812. // be `PromiseConstructor`.
  60813. //
  60814. // The same case applies to a class:
  60815. //
  60816. // declare class Promise<T> {
  60817. // constructor(...);
  60818. // then<U>(...): Promise<U>;
  60819. // }
  60820. //
  60821. var returnType = getTypeFromTypeNode(returnTypeNode);
  60822. if (languageVersion >= 2 /* ES2015 */) {
  60823. if (returnType === errorType) {
  60824. return;
  60825. }
  60826. var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
  60827. if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
  60828. // The promise type was not a valid type reference to the global promise type, so we
  60829. // report an error and return the unknown type.
  60830. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
  60831. return;
  60832. }
  60833. }
  60834. else {
  60835. // Always mark the type node as referenced if it points to a value
  60836. markTypeNodeAsReferenced(returnTypeNode);
  60837. if (returnType === errorType) {
  60838. return;
  60839. }
  60840. var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
  60841. if (promiseConstructorName === undefined) {
  60842. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType));
  60843. return;
  60844. }
  60845. var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
  60846. var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
  60847. if (promiseConstructorType === errorType) {
  60848. if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
  60849. error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
  60850. }
  60851. else {
  60852. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
  60853. }
  60854. return;
  60855. }
  60856. var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
  60857. if (globalPromiseConstructorLikeType === emptyObjectType) {
  60858. // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
  60859. // compatibility with __awaiter.
  60860. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
  60861. return;
  60862. }
  60863. if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) {
  60864. return;
  60865. }
  60866. // Verify there is no local declaration that could collide with the promise constructor.
  60867. var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
  60868. var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
  60869. if (collidingSymbol) {
  60870. error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
  60871. return;
  60872. }
  60873. }
  60874. checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
  60875. }
  60876. /** Check a decorator */
  60877. function checkDecorator(node) {
  60878. var signature = getResolvedSignature(node);
  60879. var returnType = getReturnTypeOfSignature(signature);
  60880. if (returnType.flags & 1 /* Any */) {
  60881. return;
  60882. }
  60883. var expectedReturnType;
  60884. var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
  60885. var errorInfo;
  60886. switch (node.parent.kind) {
  60887. case 245 /* ClassDeclaration */:
  60888. var classSymbol = getSymbolOfNode(node.parent);
  60889. var classConstructorType = getTypeOfSymbol(classSymbol);
  60890. expectedReturnType = getUnionType([classConstructorType, voidType]);
  60891. break;
  60892. case 156 /* Parameter */:
  60893. expectedReturnType = voidType;
  60894. errorInfo = ts.chainDiagnosticMessages(
  60895. /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
  60896. break;
  60897. case 159 /* PropertyDeclaration */:
  60898. expectedReturnType = voidType;
  60899. errorInfo = ts.chainDiagnosticMessages(
  60900. /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
  60901. break;
  60902. case 161 /* MethodDeclaration */:
  60903. case 163 /* GetAccessor */:
  60904. case 164 /* SetAccessor */:
  60905. var methodType = getTypeOfNode(node.parent);
  60906. var descriptorType = createTypedPropertyDescriptorType(methodType);
  60907. expectedReturnType = getUnionType([descriptorType, voidType]);
  60908. break;
  60909. default:
  60910. return ts.Debug.fail();
  60911. }
  60912. checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
  60913. }
  60914. /**
  60915. * If a TypeNode can be resolved to a value symbol imported from an external module, it is
  60916. * marked as referenced to prevent import elision.
  60917. */
  60918. function markTypeNodeAsReferenced(node) {
  60919. markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
  60920. }
  60921. function markEntityNameOrEntityExpressionAsReference(typeName) {
  60922. if (!typeName)
  60923. return;
  60924. var rootName = ts.getFirstIdentifier(typeName);
  60925. var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
  60926. var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
  60927. if (rootSymbol
  60928. && rootSymbol.flags & 2097152 /* Alias */
  60929. && symbolIsValue(rootSymbol)
  60930. && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
  60931. && !getTypeOnlyAliasDeclaration(rootSymbol)) {
  60932. markAliasSymbolAsReferenced(rootSymbol);
  60933. }
  60934. }
  60935. /**
  60936. * This function marks the type used for metadata decorator as referenced if it is import
  60937. * from external module.
  60938. * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
  60939. * union and intersection type
  60940. * @param node
  60941. */
  60942. function markDecoratorMedataDataTypeNodeAsReferenced(node) {
  60943. var entityName = getEntityNameForDecoratorMetadata(node);
  60944. if (entityName && ts.isEntityName(entityName)) {
  60945. markEntityNameOrEntityExpressionAsReference(entityName);
  60946. }
  60947. }
  60948. function getEntityNameForDecoratorMetadata(node) {
  60949. if (node) {
  60950. switch (node.kind) {
  60951. case 179 /* IntersectionType */:
  60952. case 178 /* UnionType */:
  60953. return getEntityNameForDecoratorMetadataFromTypeList(node.types);
  60954. case 180 /* ConditionalType */:
  60955. return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
  60956. case 182 /* ParenthesizedType */:
  60957. return getEntityNameForDecoratorMetadata(node.type);
  60958. case 169 /* TypeReference */:
  60959. return node.typeName;
  60960. }
  60961. }
  60962. }
  60963. function getEntityNameForDecoratorMetadataFromTypeList(types) {
  60964. var commonEntityName;
  60965. for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
  60966. var typeNode = types_19[_i];
  60967. while (typeNode.kind === 182 /* ParenthesizedType */) {
  60968. typeNode = typeNode.type; // Skip parens if need be
  60969. }
  60970. if (typeNode.kind === 137 /* NeverKeyword */) {
  60971. continue; // Always elide `never` from the union/intersection if possible
  60972. }
  60973. if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
  60974. continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
  60975. }
  60976. var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
  60977. if (!individualEntityName) {
  60978. // Individual is something like string number
  60979. // So it would be serialized to either that type or object
  60980. // Safe to return here
  60981. return undefined;
  60982. }
  60983. if (commonEntityName) {
  60984. // Note this is in sync with the transformation that happens for type node.
  60985. // Keep this in sync with serializeUnionOrIntersectionType
  60986. // Verify if they refer to same entity and is identifier
  60987. // return undefined if they dont match because we would emit object
  60988. if (!ts.isIdentifier(commonEntityName) ||
  60989. !ts.isIdentifier(individualEntityName) ||
  60990. commonEntityName.escapedText !== individualEntityName.escapedText) {
  60991. return undefined;
  60992. }
  60993. }
  60994. else {
  60995. commonEntityName = individualEntityName;
  60996. }
  60997. }
  60998. return commonEntityName;
  60999. }
  61000. function getParameterTypeNodeForDecoratorCheck(node) {
  61001. var typeNode = ts.getEffectiveTypeAnnotationNode(node);
  61002. return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
  61003. }
  61004. /** Check the decorators of a node */
  61005. function checkDecorators(node) {
  61006. if (!node.decorators) {
  61007. return;
  61008. }
  61009. // skip this check for nodes that cannot have decorators. These should have already had an error reported by
  61010. // checkGrammarDecorators.
  61011. if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
  61012. return;
  61013. }
  61014. if (!compilerOptions.experimentalDecorators) {
  61015. error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning);
  61016. }
  61017. var firstDecorator = node.decorators[0];
  61018. checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
  61019. if (node.kind === 156 /* Parameter */) {
  61020. checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
  61021. }
  61022. if (compilerOptions.emitDecoratorMetadata) {
  61023. checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
  61024. // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
  61025. switch (node.kind) {
  61026. case 245 /* ClassDeclaration */:
  61027. var constructor = ts.getFirstConstructorWithBody(node);
  61028. if (constructor) {
  61029. for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
  61030. var parameter = _a[_i];
  61031. markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
  61032. }
  61033. }
  61034. break;
  61035. case 163 /* GetAccessor */:
  61036. case 164 /* SetAccessor */:
  61037. var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
  61038. var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
  61039. markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
  61040. break;
  61041. case 161 /* MethodDeclaration */:
  61042. for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
  61043. var parameter = _c[_b];
  61044. markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
  61045. }
  61046. markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
  61047. break;
  61048. case 159 /* PropertyDeclaration */:
  61049. markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
  61050. break;
  61051. case 156 /* Parameter */:
  61052. markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
  61053. var containingSignature = node.parent;
  61054. for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
  61055. var parameter = _e[_d];
  61056. markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
  61057. }
  61058. break;
  61059. }
  61060. }
  61061. ts.forEach(node.decorators, checkDecorator);
  61062. }
  61063. function checkFunctionDeclaration(node) {
  61064. if (produceDiagnostics) {
  61065. checkFunctionOrMethodDeclaration(node);
  61066. checkGrammarForGenerator(node);
  61067. checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
  61068. checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
  61069. }
  61070. }
  61071. function checkJSDocTypeAliasTag(node) {
  61072. if (!node.typeExpression) {
  61073. // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
  61074. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
  61075. }
  61076. if (node.name) {
  61077. checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
  61078. }
  61079. checkSourceElement(node.typeExpression);
  61080. }
  61081. function checkJSDocTemplateTag(node) {
  61082. checkSourceElement(node.constraint);
  61083. for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
  61084. var tp = _a[_i];
  61085. checkSourceElement(tp);
  61086. }
  61087. }
  61088. function checkJSDocTypeTag(node) {
  61089. checkSourceElement(node.typeExpression);
  61090. }
  61091. function checkJSDocParameterTag(node) {
  61092. checkSourceElement(node.typeExpression);
  61093. if (!ts.getParameterSymbolFromJSDoc(node)) {
  61094. var decl = ts.getHostSignatureFromJSDoc(node);
  61095. // don't issue an error for invalid hosts -- just functions --
  61096. // and give a better error message when the host function mentions `arguments`
  61097. // but the tag doesn't have an array type
  61098. if (decl) {
  61099. var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
  61100. if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
  61101. return;
  61102. }
  61103. if (!containsArgumentsReference(decl)) {
  61104. if (ts.isQualifiedName(node.name)) {
  61105. error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left));
  61106. }
  61107. else {
  61108. error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
  61109. }
  61110. }
  61111. else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
  61112. node.typeExpression && node.typeExpression.type &&
  61113. !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
  61114. error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 153 /* QualifiedName */ ? node.name.right : node.name));
  61115. }
  61116. }
  61117. }
  61118. }
  61119. function checkJSDocFunctionType(node) {
  61120. if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
  61121. reportImplicitAny(node, anyType);
  61122. }
  61123. checkSignatureDeclaration(node);
  61124. }
  61125. function checkJSDocAugmentsTag(node) {
  61126. var classLike = ts.getJSDocHost(node);
  61127. if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
  61128. error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
  61129. return;
  61130. }
  61131. var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
  61132. ts.Debug.assert(augmentsTags.length > 0);
  61133. if (augmentsTags.length > 1) {
  61134. error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
  61135. }
  61136. var name = getIdentifierFromEntityNameExpression(node.class.expression);
  61137. var extend = ts.getClassExtendsHeritageElement(classLike);
  61138. if (extend) {
  61139. var className = getIdentifierFromEntityNameExpression(extend.expression);
  61140. if (className && name.escapedText !== className.escapedText) {
  61141. error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
  61142. }
  61143. }
  61144. }
  61145. function getIdentifierFromEntityNameExpression(node) {
  61146. switch (node.kind) {
  61147. case 75 /* Identifier */:
  61148. return node;
  61149. case 194 /* PropertyAccessExpression */:
  61150. return node.name;
  61151. default:
  61152. return undefined;
  61153. }
  61154. }
  61155. function checkFunctionOrMethodDeclaration(node) {
  61156. checkDecorators(node);
  61157. checkSignatureDeclaration(node);
  61158. var functionFlags = ts.getFunctionFlags(node);
  61159. // Do not use hasDynamicName here, because that returns false for well known symbols.
  61160. // We want to perform checkComputedPropertyName for all computed properties, including
  61161. // well known symbols.
  61162. if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
  61163. // This check will account for methods in class/interface declarations,
  61164. // as well as accessors in classes/object literals
  61165. checkComputedPropertyName(node.name);
  61166. }
  61167. if (!hasNonBindableDynamicName(node)) {
  61168. // first we want to check the local symbol that contain this declaration
  61169. // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
  61170. // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
  61171. var symbol = getSymbolOfNode(node);
  61172. var localSymbol = node.localSymbol || symbol;
  61173. // Since the javascript won't do semantic analysis like typescript,
  61174. // if the javascript file comes before the typescript file and both contain same name functions,
  61175. // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
  61176. var firstDeclaration = ts.find(localSymbol.declarations,
  61177. // Get first non javascript function declaration
  61178. function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
  61179. // Only type check the symbol once
  61180. if (node === firstDeclaration) {
  61181. checkFunctionOrConstructorSymbol(localSymbol);
  61182. }
  61183. if (symbol.parent) {
  61184. // run check once for the first declaration
  61185. if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
  61186. // run check on export symbol to check that modifiers agree across all exported declarations
  61187. checkFunctionOrConstructorSymbol(symbol);
  61188. }
  61189. }
  61190. }
  61191. var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
  61192. checkSourceElement(body);
  61193. checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
  61194. if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
  61195. // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
  61196. // in an ambient context
  61197. if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
  61198. reportImplicitAny(node, anyType);
  61199. }
  61200. if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
  61201. // A generator with a body and no type annotation can still cause errors. It can error if the
  61202. // yielded values have no common supertype, or it can give an implicit any error if it has no
  61203. // yielded values. The only way to trigger these errors is to try checking its return type.
  61204. getReturnTypeOfSignature(getSignatureFromDeclaration(node));
  61205. }
  61206. }
  61207. // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
  61208. if (ts.isInJSFile(node)) {
  61209. var typeTag = ts.getJSDocTypeTag(node);
  61210. if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
  61211. error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
  61212. }
  61213. }
  61214. }
  61215. function registerForUnusedIdentifiersCheck(node) {
  61216. // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
  61217. if (produceDiagnostics) {
  61218. var sourceFile = ts.getSourceFileOfNode(node);
  61219. var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
  61220. if (!potentiallyUnusedIdentifiers) {
  61221. potentiallyUnusedIdentifiers = [];
  61222. allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
  61223. }
  61224. // TODO: GH#22580
  61225. // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
  61226. potentiallyUnusedIdentifiers.push(node);
  61227. }
  61228. }
  61229. function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
  61230. for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
  61231. var node = potentiallyUnusedIdentifiers_1[_i];
  61232. switch (node.kind) {
  61233. case 245 /* ClassDeclaration */:
  61234. case 214 /* ClassExpression */:
  61235. checkUnusedClassMembers(node, addDiagnostic);
  61236. checkUnusedTypeParameters(node, addDiagnostic);
  61237. break;
  61238. case 290 /* SourceFile */:
  61239. case 249 /* ModuleDeclaration */:
  61240. case 223 /* Block */:
  61241. case 251 /* CaseBlock */:
  61242. case 230 /* ForStatement */:
  61243. case 231 /* ForInStatement */:
  61244. case 232 /* ForOfStatement */:
  61245. checkUnusedLocalsAndParameters(node, addDiagnostic);
  61246. break;
  61247. case 162 /* Constructor */:
  61248. case 201 /* FunctionExpression */:
  61249. case 244 /* FunctionDeclaration */:
  61250. case 202 /* ArrowFunction */:
  61251. case 161 /* MethodDeclaration */:
  61252. case 163 /* GetAccessor */:
  61253. case 164 /* SetAccessor */:
  61254. if (node.body) { // Don't report unused parameters in overloads
  61255. checkUnusedLocalsAndParameters(node, addDiagnostic);
  61256. }
  61257. checkUnusedTypeParameters(node, addDiagnostic);
  61258. break;
  61259. case 160 /* MethodSignature */:
  61260. case 165 /* CallSignature */:
  61261. case 166 /* ConstructSignature */:
  61262. case 170 /* FunctionType */:
  61263. case 171 /* ConstructorType */:
  61264. case 247 /* TypeAliasDeclaration */:
  61265. case 246 /* InterfaceDeclaration */:
  61266. checkUnusedTypeParameters(node, addDiagnostic);
  61267. break;
  61268. case 181 /* InferType */:
  61269. checkUnusedInferTypeParameter(node, addDiagnostic);
  61270. break;
  61271. default:
  61272. ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
  61273. }
  61274. }
  61275. }
  61276. function errorUnusedLocal(declaration, name, addDiagnostic) {
  61277. var node = ts.getNameOfDeclaration(declaration) || declaration;
  61278. var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
  61279. addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
  61280. }
  61281. function isIdentifierThatStartsWithUnderscore(node) {
  61282. return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
  61283. }
  61284. function checkUnusedClassMembers(node, addDiagnostic) {
  61285. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  61286. var member = _a[_i];
  61287. switch (member.kind) {
  61288. case 161 /* MethodDeclaration */:
  61289. case 159 /* PropertyDeclaration */:
  61290. case 163 /* GetAccessor */:
  61291. case 164 /* SetAccessor */:
  61292. if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
  61293. // Already would have reported an error on the getter.
  61294. break;
  61295. }
  61296. var symbol = getSymbolOfNode(member);
  61297. if (!symbol.isReferenced && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))) {
  61298. addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
  61299. }
  61300. break;
  61301. case 162 /* Constructor */:
  61302. for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
  61303. var parameter = _c[_b];
  61304. if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
  61305. addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
  61306. }
  61307. }
  61308. break;
  61309. case 167 /* IndexSignature */:
  61310. case 222 /* SemicolonClassElement */:
  61311. // Can't be private
  61312. break;
  61313. default:
  61314. ts.Debug.fail();
  61315. }
  61316. }
  61317. }
  61318. function checkUnusedInferTypeParameter(node, addDiagnostic) {
  61319. var typeParameter = node.typeParameter;
  61320. if (isTypeParameterUnused(typeParameter)) {
  61321. addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
  61322. }
  61323. }
  61324. function checkUnusedTypeParameters(node, addDiagnostic) {
  61325. // Only report errors on the last declaration for the type parameter container;
  61326. // this ensures that all uses have been accounted for.
  61327. if (ts.last(getSymbolOfNode(node).declarations) !== node)
  61328. return;
  61329. var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
  61330. var seenParentsWithEveryUnused = new ts.NodeSet();
  61331. for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
  61332. var typeParameter = typeParameters_3[_i];
  61333. if (!isTypeParameterUnused(typeParameter))
  61334. continue;
  61335. var name = ts.idText(typeParameter.name);
  61336. var parent = typeParameter.parent;
  61337. if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
  61338. if (seenParentsWithEveryUnused.tryAdd(parent)) {
  61339. var range = ts.isJSDocTemplateTag(parent)
  61340. // Whole @template tag
  61341. ? ts.rangeOfNode(parent)
  61342. // Include the `<>` in the error message
  61343. : ts.rangeOfTypeParameters(parent.typeParameters);
  61344. var only = typeParameters.length === 1;
  61345. var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
  61346. var arg0 = only ? name : undefined;
  61347. addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
  61348. }
  61349. }
  61350. else {
  61351. addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
  61352. }
  61353. }
  61354. }
  61355. function isTypeParameterUnused(typeParameter) {
  61356. return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
  61357. }
  61358. function addToGroup(map, key, value, getKey) {
  61359. var keyString = String(getKey(key));
  61360. var group = map.get(keyString);
  61361. if (group) {
  61362. group[1].push(value);
  61363. }
  61364. else {
  61365. map.set(keyString, [key, [value]]);
  61366. }
  61367. }
  61368. function tryGetRootParameterDeclaration(node) {
  61369. return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
  61370. }
  61371. function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
  61372. // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
  61373. var unusedImports = ts.createMap();
  61374. var unusedDestructures = ts.createMap();
  61375. var unusedVariables = ts.createMap();
  61376. nodeWithLocals.locals.forEach(function (local) {
  61377. // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
  61378. // If it's a type parameter merged with a parameter, check if the parameter-side is used.
  61379. if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
  61380. return;
  61381. }
  61382. for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
  61383. var declaration = _a[_i];
  61384. if (ts.isAmbientModule(declaration) ||
  61385. (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
  61386. continue;
  61387. }
  61388. if (isImportedDeclaration(declaration)) {
  61389. addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
  61390. }
  61391. else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
  61392. // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
  61393. var lastElement = ts.last(declaration.parent.elements);
  61394. if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
  61395. addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
  61396. }
  61397. }
  61398. else if (ts.isVariableDeclaration(declaration)) {
  61399. addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
  61400. }
  61401. else {
  61402. var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
  61403. var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
  61404. if (parameter && name) {
  61405. if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
  61406. addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
  61407. }
  61408. }
  61409. else {
  61410. errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
  61411. }
  61412. }
  61413. }
  61414. });
  61415. unusedImports.forEach(function (_a) {
  61416. var importClause = _a[0], unuseds = _a[1];
  61417. var importDecl = importClause.parent;
  61418. var nDeclarations = (importClause.name ? 1 : 0) +
  61419. (importClause.namedBindings ?
  61420. (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
  61421. : 0);
  61422. if (nDeclarations === unuseds.length) {
  61423. addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
  61424. ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
  61425. : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
  61426. }
  61427. else {
  61428. for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
  61429. var unused = unuseds_1[_i];
  61430. errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
  61431. }
  61432. }
  61433. });
  61434. unusedDestructures.forEach(function (_a) {
  61435. var bindingPattern = _a[0], bindingElements = _a[1];
  61436. var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
  61437. if (bindingPattern.elements.length === bindingElements.length) {
  61438. if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
  61439. addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
  61440. }
  61441. else {
  61442. addDiagnostic(bindingPattern, kind, bindingElements.length === 1
  61443. ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
  61444. : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
  61445. }
  61446. }
  61447. else {
  61448. for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
  61449. var e = bindingElements_1[_i];
  61450. addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
  61451. }
  61452. }
  61453. });
  61454. unusedVariables.forEach(function (_a) {
  61455. var declarationList = _a[0], declarations = _a[1];
  61456. if (declarationList.declarations.length === declarations.length) {
  61457. addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
  61458. ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
  61459. : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
  61460. }
  61461. else {
  61462. for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
  61463. var decl = declarations_5[_i];
  61464. addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
  61465. }
  61466. }
  61467. });
  61468. }
  61469. function bindingNameText(name) {
  61470. switch (name.kind) {
  61471. case 75 /* Identifier */:
  61472. return ts.idText(name);
  61473. case 190 /* ArrayBindingPattern */:
  61474. case 189 /* ObjectBindingPattern */:
  61475. return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
  61476. default:
  61477. return ts.Debug.assertNever(name);
  61478. }
  61479. }
  61480. function isImportedDeclaration(node) {
  61481. return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
  61482. }
  61483. function importClauseFromImported(decl) {
  61484. return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
  61485. }
  61486. function checkBlock(node) {
  61487. // Grammar checking for SyntaxKind.Block
  61488. if (node.kind === 223 /* Block */) {
  61489. checkGrammarStatementInAmbientContext(node);
  61490. }
  61491. if (ts.isFunctionOrModuleBlock(node)) {
  61492. var saveFlowAnalysisDisabled = flowAnalysisDisabled;
  61493. ts.forEach(node.statements, checkSourceElement);
  61494. flowAnalysisDisabled = saveFlowAnalysisDisabled;
  61495. }
  61496. else {
  61497. ts.forEach(node.statements, checkSourceElement);
  61498. }
  61499. if (node.locals) {
  61500. registerForUnusedIdentifiersCheck(node);
  61501. }
  61502. }
  61503. function checkCollisionWithArgumentsInGeneratedCode(node) {
  61504. // no rest parameters \ declaration context \ overload - no codegen impact
  61505. if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
  61506. return;
  61507. }
  61508. ts.forEach(node.parameters, function (p) {
  61509. if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
  61510. error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
  61511. }
  61512. });
  61513. }
  61514. function needCollisionCheckForIdentifier(node, identifier, name) {
  61515. if (!(identifier && identifier.escapedText === name)) {
  61516. return false;
  61517. }
  61518. if (node.kind === 159 /* PropertyDeclaration */ ||
  61519. node.kind === 158 /* PropertySignature */ ||
  61520. node.kind === 161 /* MethodDeclaration */ ||
  61521. node.kind === 160 /* MethodSignature */ ||
  61522. node.kind === 163 /* GetAccessor */ ||
  61523. node.kind === 164 /* SetAccessor */) {
  61524. // it is ok to have member named '_super' or '_this' - member access is always qualified
  61525. return false;
  61526. }
  61527. if (node.flags & 8388608 /* Ambient */) {
  61528. // ambient context - no codegen impact
  61529. return false;
  61530. }
  61531. var root = ts.getRootDeclaration(node);
  61532. if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
  61533. // just an overload - no codegen impact
  61534. return false;
  61535. }
  61536. return true;
  61537. }
  61538. // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
  61539. function checkIfThisIsCapturedInEnclosingScope(node) {
  61540. ts.findAncestor(node, function (current) {
  61541. if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
  61542. var isDeclaration_1 = node.kind !== 75 /* Identifier */;
  61543. if (isDeclaration_1) {
  61544. error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
  61545. }
  61546. else {
  61547. error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
  61548. }
  61549. return true;
  61550. }
  61551. return false;
  61552. });
  61553. }
  61554. function checkIfNewTargetIsCapturedInEnclosingScope(node) {
  61555. ts.findAncestor(node, function (current) {
  61556. if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
  61557. var isDeclaration_2 = node.kind !== 75 /* Identifier */;
  61558. if (isDeclaration_2) {
  61559. error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
  61560. }
  61561. else {
  61562. error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
  61563. }
  61564. return true;
  61565. }
  61566. return false;
  61567. });
  61568. }
  61569. function checkWeakMapCollision(node) {
  61570. var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
  61571. if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
  61572. error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
  61573. }
  61574. }
  61575. function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
  61576. // No need to check for require or exports for ES6 modules and later
  61577. if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
  61578. return;
  61579. }
  61580. if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
  61581. return;
  61582. }
  61583. // Uninstantiated modules shouldnt do this check
  61584. if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
  61585. return;
  61586. }
  61587. // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
  61588. var parent = getDeclarationContainer(node);
  61589. if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
  61590. // If the declaration happens to be in external module, report error that require and exports are reserved keywords
  61591. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
  61592. }
  61593. }
  61594. function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
  61595. if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
  61596. return;
  61597. }
  61598. // Uninstantiated modules shouldnt do this check
  61599. if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
  61600. return;
  61601. }
  61602. // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
  61603. var parent = getDeclarationContainer(node);
  61604. if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
  61605. // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
  61606. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
  61607. }
  61608. }
  61609. function checkVarDeclaredNamesNotShadowed(node) {
  61610. // - ScriptBody : StatementList
  61611. // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
  61612. // also occurs in the VarDeclaredNames of StatementList.
  61613. // - Block : { StatementList }
  61614. // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
  61615. // also occurs in the VarDeclaredNames of StatementList.
  61616. // Variable declarations are hoisted to the top of their function scope. They can shadow
  61617. // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
  61618. // by the binder as the declaration scope is different.
  61619. // A non-initialized declaration is a no-op as the block declaration will resolve before the var
  61620. // declaration. the problem is if the declaration has an initializer. this will act as a write to the
  61621. // block declared value. this is fine for let, but not const.
  61622. // Only consider declarations with initializers, uninitialized const declarations will not
  61623. // step on a let/const variable.
  61624. // Do not consider const and const declarations, as duplicate block-scoped declarations
  61625. // are handled by the binder.
  61626. // We are only looking for const declarations that step on let\const declarations from a
  61627. // different scope. e.g.:
  61628. // {
  61629. // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
  61630. // const x = 0; // symbol for this declaration will be 'symbol'
  61631. // }
  61632. // skip block-scoped variables and parameters
  61633. if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
  61634. return;
  61635. }
  61636. // skip variable declarations that don't have initializers
  61637. // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
  61638. // so we'll always treat binding elements as initialized
  61639. if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
  61640. return;
  61641. }
  61642. var symbol = getSymbolOfNode(node);
  61643. if (symbol.flags & 1 /* FunctionScopedVariable */) {
  61644. if (!ts.isIdentifier(node.name))
  61645. return ts.Debug.fail();
  61646. var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
  61647. if (localDeclarationSymbol &&
  61648. localDeclarationSymbol !== symbol &&
  61649. localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
  61650. if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
  61651. var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
  61652. var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
  61653. ? varDeclList.parent.parent
  61654. : undefined;
  61655. // names of block-scoped and function scoped variables can collide only
  61656. // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
  61657. var namesShareScope = container &&
  61658. (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
  61659. container.kind === 250 /* ModuleBlock */ ||
  61660. container.kind === 249 /* ModuleDeclaration */ ||
  61661. container.kind === 290 /* SourceFile */);
  61662. // here we know that function scoped variable is shadowed by block scoped one
  61663. // if they are defined in the same scope - binder has already reported redeclaration error
  61664. // otherwise if variable has an initializer - show error that initialization will fail
  61665. // since LHS will be block scoped name instead of function scoped
  61666. if (!namesShareScope) {
  61667. var name = symbolToString(localDeclarationSymbol);
  61668. error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
  61669. }
  61670. }
  61671. }
  61672. }
  61673. }
  61674. function convertAutoToAny(type) {
  61675. return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
  61676. }
  61677. // Check variable, parameter, or property declaration
  61678. function checkVariableLikeDeclaration(node) {
  61679. checkDecorators(node);
  61680. if (!ts.isBindingElement(node)) {
  61681. checkSourceElement(node.type);
  61682. }
  61683. // JSDoc `function(string, string): string` syntax results in parameters with no name
  61684. if (!node.name) {
  61685. return;
  61686. }
  61687. // For a computed property, just check the initializer and exit
  61688. // Do not use hasDynamicName here, because that returns false for well known symbols.
  61689. // We want to perform checkComputedPropertyName for all computed properties, including
  61690. // well known symbols.
  61691. if (node.name.kind === 154 /* ComputedPropertyName */) {
  61692. checkComputedPropertyName(node.name);
  61693. if (node.initializer) {
  61694. checkExpressionCached(node.initializer);
  61695. }
  61696. }
  61697. if (node.kind === 191 /* BindingElement */) {
  61698. if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
  61699. checkExternalEmitHelpers(node, 4 /* Rest */);
  61700. }
  61701. // check computed properties inside property names of binding elements
  61702. if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
  61703. checkComputedPropertyName(node.propertyName);
  61704. }
  61705. // check private/protected variable access
  61706. var parent = node.parent.parent;
  61707. var parentType = getTypeForBindingElementParent(parent);
  61708. var name = node.propertyName || node.name;
  61709. if (parentType && !ts.isBindingPattern(name)) {
  61710. var exprType = getLiteralTypeFromPropertyName(name);
  61711. if (isTypeUsableAsPropertyName(exprType)) {
  61712. var nameText = getPropertyNameFromType(exprType);
  61713. var property = getPropertyOfType(parentType, nameText);
  61714. if (property) {
  61715. markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
  61716. checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
  61717. }
  61718. }
  61719. }
  61720. }
  61721. // For a binding pattern, check contained binding elements
  61722. if (ts.isBindingPattern(node.name)) {
  61723. if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
  61724. checkExternalEmitHelpers(node, 512 /* Read */);
  61725. }
  61726. ts.forEach(node.name.elements, checkSourceElement);
  61727. }
  61728. // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
  61729. if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
  61730. error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
  61731. return;
  61732. }
  61733. // For a binding pattern, validate the initializer and exit
  61734. if (ts.isBindingPattern(node.name)) {
  61735. var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
  61736. var needCheckWidenedType = node.name.elements.length === 0;
  61737. if (needCheckInitializer || needCheckWidenedType) {
  61738. // Don't validate for-in initializer as it is already an error
  61739. var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
  61740. if (needCheckInitializer) {
  61741. var initializerType = checkExpressionCached(node.initializer);
  61742. if (strictNullChecks && needCheckWidenedType) {
  61743. checkNonNullNonVoidType(initializerType, node);
  61744. }
  61745. else {
  61746. checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
  61747. }
  61748. }
  61749. // check the binding pattern with empty elements
  61750. if (needCheckWidenedType) {
  61751. if (ts.isArrayBindingPattern(node.name)) {
  61752. checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
  61753. }
  61754. else if (strictNullChecks) {
  61755. checkNonNullNonVoidType(widenedType, node);
  61756. }
  61757. }
  61758. }
  61759. return;
  61760. }
  61761. var symbol = getSymbolOfNode(node);
  61762. var type = convertAutoToAny(getTypeOfSymbol(symbol));
  61763. if (node === symbol.valueDeclaration) {
  61764. // Node is the primary declaration of the symbol, just validate the initializer
  61765. // Don't validate for-in initializer as it is already an error
  61766. var initializer = ts.getEffectiveInitializer(node);
  61767. if (initializer) {
  61768. var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
  61769. ts.isObjectLiteralExpression(initializer) &&
  61770. (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
  61771. ts.hasEntries(symbol.exports);
  61772. if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
  61773. checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
  61774. }
  61775. }
  61776. if (symbol.declarations.length > 1) {
  61777. if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
  61778. error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
  61779. }
  61780. }
  61781. }
  61782. else {
  61783. // Node is a secondary declaration, check that type is identical to primary declaration and check that
  61784. // initializer is consistent with type associated with the node
  61785. var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
  61786. if (type !== errorType && declarationType !== errorType &&
  61787. !isTypeIdenticalTo(type, declarationType) &&
  61788. !(symbol.flags & 67108864 /* Assignment */)) {
  61789. errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
  61790. }
  61791. if (node.initializer) {
  61792. checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
  61793. }
  61794. if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
  61795. error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
  61796. }
  61797. }
  61798. if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
  61799. // We know we don't have a binding pattern or computed name here
  61800. checkExportsOnMergedDeclarations(node);
  61801. if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
  61802. checkVarDeclaredNamesNotShadowed(node);
  61803. }
  61804. checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
  61805. checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
  61806. if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
  61807. potentialWeakMapCollisions.push(node);
  61808. }
  61809. }
  61810. }
  61811. function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
  61812. var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
  61813. var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
  61814. ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
  61815. : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
  61816. var declName = ts.declarationNameToString(nextDeclarationName);
  61817. var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
  61818. if (firstDeclaration) {
  61819. ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
  61820. }
  61821. }
  61822. function areDeclarationFlagsIdentical(left, right) {
  61823. if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
  61824. (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
  61825. // Differences in optionality between parameters and variables are allowed.
  61826. return true;
  61827. }
  61828. if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
  61829. return false;
  61830. }
  61831. var interestingFlags = 8 /* Private */ |
  61832. 16 /* Protected */ |
  61833. 256 /* Async */ |
  61834. 128 /* Abstract */ |
  61835. 64 /* Readonly */ |
  61836. 32 /* Static */;
  61837. return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
  61838. }
  61839. function checkVariableDeclaration(node) {
  61840. checkGrammarVariableDeclaration(node);
  61841. return checkVariableLikeDeclaration(node);
  61842. }
  61843. function checkBindingElement(node) {
  61844. checkGrammarBindingElement(node);
  61845. return checkVariableLikeDeclaration(node);
  61846. }
  61847. function checkVariableStatement(node) {
  61848. // Grammar checking
  61849. if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
  61850. checkGrammarForDisallowedLetOrConstStatement(node);
  61851. ts.forEach(node.declarationList.declarations, checkSourceElement);
  61852. }
  61853. function checkExpressionStatement(node) {
  61854. // Grammar checking
  61855. checkGrammarStatementInAmbientContext(node);
  61856. checkExpression(node.expression);
  61857. }
  61858. function checkIfStatement(node) {
  61859. // Grammar checking
  61860. checkGrammarStatementInAmbientContext(node);
  61861. var type = checkTruthinessExpression(node.expression);
  61862. checkTestingKnownTruthyCallableType(node, type);
  61863. checkSourceElement(node.thenStatement);
  61864. if (node.thenStatement.kind === 224 /* EmptyStatement */) {
  61865. error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
  61866. }
  61867. checkSourceElement(node.elseStatement);
  61868. }
  61869. function checkTestingKnownTruthyCallableType(ifStatement, type) {
  61870. if (!strictNullChecks) {
  61871. return;
  61872. }
  61873. var testedNode = ts.isIdentifier(ifStatement.expression)
  61874. ? ifStatement.expression
  61875. : ts.isPropertyAccessExpression(ifStatement.expression)
  61876. ? ifStatement.expression.name
  61877. : undefined;
  61878. if (!testedNode) {
  61879. return;
  61880. }
  61881. var possiblyFalsy = getFalsyFlags(type);
  61882. if (possiblyFalsy) {
  61883. return;
  61884. }
  61885. // While it technically should be invalid for any known-truthy value
  61886. // to be tested, we de-scope to functions unrefenced in the block as a
  61887. // heuristic to identify the most common bugs. There are too many
  61888. // false positives for values sourced from type definitions without
  61889. // strictNullChecks otherwise.
  61890. var callSignatures = getSignaturesOfType(type, 0 /* Call */);
  61891. if (callSignatures.length === 0) {
  61892. return;
  61893. }
  61894. var testedFunctionSymbol = getSymbolAtLocation(testedNode);
  61895. if (!testedFunctionSymbol) {
  61896. return;
  61897. }
  61898. var functionIsUsedInBody = ts.forEachChild(ifStatement.thenStatement, function check(childNode) {
  61899. if (ts.isIdentifier(childNode)) {
  61900. var childSymbol = getSymbolAtLocation(childNode);
  61901. if (childSymbol && childSymbol.id === testedFunctionSymbol.id) {
  61902. return true;
  61903. }
  61904. }
  61905. return ts.forEachChild(childNode, check);
  61906. });
  61907. if (!functionIsUsedInBody) {
  61908. error(ifStatement.expression, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
  61909. }
  61910. }
  61911. function checkDoStatement(node) {
  61912. // Grammar checking
  61913. checkGrammarStatementInAmbientContext(node);
  61914. checkSourceElement(node.statement);
  61915. checkTruthinessExpression(node.expression);
  61916. }
  61917. function checkWhileStatement(node) {
  61918. // Grammar checking
  61919. checkGrammarStatementInAmbientContext(node);
  61920. checkTruthinessExpression(node.expression);
  61921. checkSourceElement(node.statement);
  61922. }
  61923. function checkTruthinessOfType(type, node) {
  61924. if (type.flags & 16384 /* Void */) {
  61925. error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
  61926. }
  61927. return type;
  61928. }
  61929. function checkTruthinessExpression(node, checkMode) {
  61930. return checkTruthinessOfType(checkExpression(node, checkMode), node);
  61931. }
  61932. function checkForStatement(node) {
  61933. // Grammar checking
  61934. if (!checkGrammarStatementInAmbientContext(node)) {
  61935. if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
  61936. checkGrammarVariableDeclarationList(node.initializer);
  61937. }
  61938. }
  61939. if (node.initializer) {
  61940. if (node.initializer.kind === 243 /* VariableDeclarationList */) {
  61941. ts.forEach(node.initializer.declarations, checkVariableDeclaration);
  61942. }
  61943. else {
  61944. checkExpression(node.initializer);
  61945. }
  61946. }
  61947. if (node.condition)
  61948. checkTruthinessExpression(node.condition);
  61949. if (node.incrementor)
  61950. checkExpression(node.incrementor);
  61951. checkSourceElement(node.statement);
  61952. if (node.locals) {
  61953. registerForUnusedIdentifiersCheck(node);
  61954. }
  61955. }
  61956. function checkForOfStatement(node) {
  61957. checkGrammarForInOrForOfStatement(node);
  61958. if (node.awaitModifier) {
  61959. var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
  61960. if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
  61961. // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
  61962. checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
  61963. }
  61964. }
  61965. else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
  61966. // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
  61967. checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
  61968. }
  61969. // Check the LHS and RHS
  61970. // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
  61971. // via checkRightHandSideOfForOf.
  61972. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
  61973. // Then check that the RHS is assignable to it.
  61974. if (node.initializer.kind === 243 /* VariableDeclarationList */) {
  61975. checkForInOrForOfVariableDeclaration(node);
  61976. }
  61977. else {
  61978. var varExpr = node.initializer;
  61979. var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier);
  61980. // There may be a destructuring assignment on the left side
  61981. if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
  61982. // iteratedType may be undefined. In this case, we still want to check the structure of
  61983. // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
  61984. // to short circuit the type relation checking as much as possible, so we pass the unknownType.
  61985. checkDestructuringAssignment(varExpr, iteratedType || errorType);
  61986. }
  61987. else {
  61988. var leftType = checkExpression(varExpr);
  61989. checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access);
  61990. // iteratedType will be undefined if the rightType was missing properties/signatures
  61991. // required to get its iteratedType (like [Symbol.iterator] or next). This may be
  61992. // because we accessed properties from anyType, or it may have led to an error inside
  61993. // getElementTypeOfIterable.
  61994. if (iteratedType) {
  61995. checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
  61996. }
  61997. }
  61998. }
  61999. checkSourceElement(node.statement);
  62000. if (node.locals) {
  62001. registerForUnusedIdentifiersCheck(node);
  62002. }
  62003. }
  62004. function checkForInStatement(node) {
  62005. // Grammar checking
  62006. checkGrammarForInOrForOfStatement(node);
  62007. var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
  62008. // TypeScript 1.0 spec (April 2014): 5.4
  62009. // In a 'for-in' statement of the form
  62010. // for (let VarDecl in Expr) Statement
  62011. // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
  62012. // and Expr must be an expression of type Any, an object type, or a type parameter type.
  62013. if (node.initializer.kind === 243 /* VariableDeclarationList */) {
  62014. var variable = node.initializer.declarations[0];
  62015. if (variable && ts.isBindingPattern(variable.name)) {
  62016. error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
  62017. }
  62018. checkForInOrForOfVariableDeclaration(node);
  62019. }
  62020. else {
  62021. // In a 'for-in' statement of the form
  62022. // for (Var in Expr) Statement
  62023. // Var must be an expression classified as a reference of type Any or the String primitive type,
  62024. // and Expr must be an expression of type Any, an object type, or a type parameter type.
  62025. var varExpr = node.initializer;
  62026. var leftType = checkExpression(varExpr);
  62027. if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
  62028. error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
  62029. }
  62030. else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
  62031. error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
  62032. }
  62033. else {
  62034. // run check only former check succeeded to avoid cascading errors
  62035. checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access);
  62036. }
  62037. }
  62038. // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
  62039. // in this case error about missing name is already reported - do not report extra one
  62040. if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
  62041. error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType));
  62042. }
  62043. checkSourceElement(node.statement);
  62044. if (node.locals) {
  62045. registerForUnusedIdentifiersCheck(node);
  62046. }
  62047. }
  62048. function checkForInOrForOfVariableDeclaration(iterationStatement) {
  62049. var variableDeclarationList = iterationStatement.initializer;
  62050. // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
  62051. if (variableDeclarationList.declarations.length >= 1) {
  62052. var decl = variableDeclarationList.declarations[0];
  62053. checkVariableDeclaration(decl);
  62054. }
  62055. }
  62056. function checkRightHandSideOfForOf(rhsExpression, awaitModifier) {
  62057. var expressionType = checkNonNullExpression(rhsExpression);
  62058. var use = awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
  62059. return checkIteratedTypeOrElementType(use, expressionType, undefinedType, rhsExpression);
  62060. }
  62061. function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
  62062. if (isTypeAny(inputType)) {
  62063. return inputType;
  62064. }
  62065. return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
  62066. }
  62067. /**
  62068. * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
  62069. * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
  62070. * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
  62071. */
  62072. function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
  62073. var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
  62074. if (inputType === neverType) {
  62075. reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
  62076. return undefined;
  62077. }
  62078. var uplevelIteration = languageVersion >= 2 /* ES2015 */;
  62079. var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
  62080. // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
  62081. // or higher, when inside of an async generator or for-await-if, or when
  62082. // downlevelIteration is requested.
  62083. if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
  62084. // We only report errors for an invalid iterable type in ES2015 or higher.
  62085. var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
  62086. if (checkAssignability) {
  62087. if (iterationTypes) {
  62088. var diagnostic = use & 8 /* ForOfFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 :
  62089. use & 32 /* SpreadFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 :
  62090. use & 64 /* DestructuringFlag */ ? ts.Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 :
  62091. use & 16 /* YieldStarFlag */ ? ts.Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 :
  62092. undefined;
  62093. if (diagnostic) {
  62094. checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
  62095. }
  62096. }
  62097. }
  62098. if (iterationTypes || uplevelIteration) {
  62099. return iterationTypes && iterationTypes.yieldType;
  62100. }
  62101. }
  62102. var arrayType = inputType;
  62103. var reportedError = false;
  62104. var hasStringConstituent = false;
  62105. // If strings are permitted, remove any string-like constituents from the array type.
  62106. // This allows us to find other non-string element types from an array unioned with
  62107. // a string.
  62108. if (use & 4 /* AllowsStringInputFlag */) {
  62109. if (arrayType.flags & 1048576 /* Union */) {
  62110. // After we remove all types that are StringLike, we will know if there was a string constituent
  62111. // based on whether the result of filter is a new array.
  62112. var arrayTypes = inputType.types;
  62113. var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
  62114. if (filteredTypes !== arrayTypes) {
  62115. arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
  62116. }
  62117. }
  62118. else if (arrayType.flags & 132 /* StringLike */) {
  62119. arrayType = neverType;
  62120. }
  62121. hasStringConstituent = arrayType !== inputType;
  62122. if (hasStringConstituent) {
  62123. if (languageVersion < 1 /* ES5 */) {
  62124. if (errorNode) {
  62125. error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
  62126. reportedError = true;
  62127. }
  62128. }
  62129. // Now that we've removed all the StringLike types, if no constituents remain, then the entire
  62130. // arrayOrStringType was a string.
  62131. if (arrayType.flags & 131072 /* Never */) {
  62132. return stringType;
  62133. }
  62134. }
  62135. }
  62136. if (!isArrayLikeType(arrayType)) {
  62137. if (errorNode && !reportedError) {
  62138. // Which error we report depends on whether we allow strings or if there was a
  62139. // string constituent. For example, if the input type is number | string, we
  62140. // want to say that number is not an array type. But if the input was just
  62141. // number and string input is allowed, we want to say that number is not an
  62142. // array type or a string type.
  62143. var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
  62144. var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
  62145. ? downlevelIteration
  62146. ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
  62147. : yieldType
  62148. ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
  62149. : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
  62150. : downlevelIteration
  62151. ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
  62152. : yieldType
  62153. ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
  62154. : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
  62155. errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
  62156. }
  62157. return hasStringConstituent ? stringType : undefined;
  62158. }
  62159. var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
  62160. if (hasStringConstituent && arrayElementType) {
  62161. // This is just an optimization for the case where arrayOrStringType is string | string[]
  62162. if (arrayElementType.flags & 132 /* StringLike */) {
  62163. return stringType;
  62164. }
  62165. return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
  62166. }
  62167. return arrayElementType;
  62168. }
  62169. /**
  62170. * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
  62171. */
  62172. function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
  62173. if (isTypeAny(inputType)) {
  62174. return undefined;
  62175. }
  62176. var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
  62177. return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
  62178. }
  62179. function createIterationTypes(yieldType, returnType, nextType) {
  62180. // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
  62181. // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
  62182. // as it is combined via `getIntersectionType` when merging iteration types.
  62183. if (yieldType === void 0) { yieldType = neverType; }
  62184. if (returnType === void 0) { returnType = neverType; }
  62185. if (nextType === void 0) { nextType = unknownType; }
  62186. // Use the cache only for intrinsic types to keep it small as they are likely to be
  62187. // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
  62188. // are also cached on the type they are requested for, so we shouldn't need to maintain
  62189. // the cache for less-frequently used types.
  62190. if (yieldType.flags & 67359327 /* Intrinsic */ &&
  62191. returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
  62192. nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
  62193. var id = getTypeListId([yieldType, returnType, nextType]);
  62194. var iterationTypes = iterationTypesCache.get(id);
  62195. if (!iterationTypes) {
  62196. iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
  62197. iterationTypesCache.set(id, iterationTypes);
  62198. }
  62199. return iterationTypes;
  62200. }
  62201. return { yieldType: yieldType, returnType: returnType, nextType: nextType };
  62202. }
  62203. /**
  62204. * Combines multiple `IterationTypes` records.
  62205. *
  62206. * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
  62207. * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
  62208. * for the combined iteration types.
  62209. */
  62210. function combineIterationTypes(array) {
  62211. var yieldTypes;
  62212. var returnTypes;
  62213. var nextTypes;
  62214. for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
  62215. var iterationTypes = array_10[_i];
  62216. if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
  62217. continue;
  62218. }
  62219. if (iterationTypes === anyIterationTypes) {
  62220. return anyIterationTypes;
  62221. }
  62222. yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
  62223. returnTypes = ts.append(returnTypes, iterationTypes.returnType);
  62224. nextTypes = ts.append(nextTypes, iterationTypes.nextType);
  62225. }
  62226. if (yieldTypes || returnTypes || nextTypes) {
  62227. return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
  62228. }
  62229. return noIterationTypes;
  62230. }
  62231. function getCachedIterationTypes(type, cacheKey) {
  62232. return type[cacheKey];
  62233. }
  62234. function setCachedIterationTypes(type, cacheKey, cachedTypes) {
  62235. return type[cacheKey] = cachedTypes;
  62236. }
  62237. /**
  62238. * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
  62239. *
  62240. * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
  62241. *
  62242. * Another thing to note is that at any step of this process, we could run into a dead end,
  62243. * meaning either the property is missing, or we run into the anyType. If either of these things
  62244. * happens, we return `undefined` to signal that we could not find the iteration type. If a property
  62245. * is missing, and the previous step did not result in `any`, then we also give an error if the
  62246. * caller requested it. Then the caller can decide what to do in the case where there is no iterated
  62247. * type.
  62248. *
  62249. * For a **for-of** statement, `yield*` (in a normal generator), spread, array
  62250. * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
  62251. * method.
  62252. *
  62253. * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
  62254. *
  62255. * For a **for-await-of** statement or a `yield*` in an async generator we will look for
  62256. * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
  62257. */
  62258. function getIterationTypesOfIterable(type, use, errorNode) {
  62259. if (isTypeAny(type)) {
  62260. return anyIterationTypes;
  62261. }
  62262. if (!(type.flags & 1048576 /* Union */)) {
  62263. var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
  62264. if (iterationTypes_1 === noIterationTypes) {
  62265. if (errorNode) {
  62266. reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
  62267. }
  62268. return undefined;
  62269. }
  62270. return iterationTypes_1;
  62271. }
  62272. var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
  62273. var cachedTypes = getCachedIterationTypes(type, cacheKey);
  62274. if (cachedTypes)
  62275. return cachedTypes === noIterationTypes ? undefined : cachedTypes;
  62276. var allIterationTypes;
  62277. for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
  62278. var constituent = _a[_i];
  62279. var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
  62280. if (iterationTypes_2 === noIterationTypes) {
  62281. if (errorNode) {
  62282. reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
  62283. errorNode = undefined;
  62284. }
  62285. }
  62286. else {
  62287. allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
  62288. }
  62289. }
  62290. var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
  62291. setCachedIterationTypes(type, cacheKey, iterationTypes);
  62292. return iterationTypes === noIterationTypes ? undefined : iterationTypes;
  62293. }
  62294. function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
  62295. if (iterationTypes === noIterationTypes)
  62296. return noIterationTypes;
  62297. if (iterationTypes === anyIterationTypes)
  62298. return anyIterationTypes;
  62299. var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
  62300. return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
  62301. }
  62302. /**
  62303. * Gets the *yield*, *return*, and *next* types from a non-union type.
  62304. *
  62305. * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
  62306. * returned to indicate to the caller that it should report an error. Otherwise, an
  62307. * `IterationTypes` record is returned.
  62308. *
  62309. * NOTE: You probably don't want to call this directly and should be calling
  62310. * `getIterationTypesOfIterable` instead.
  62311. */
  62312. function getIterationTypesOfIterableWorker(type, use, errorNode) {
  62313. if (isTypeAny(type)) {
  62314. return anyIterationTypes;
  62315. }
  62316. if (use & 2 /* AllowsAsyncIterablesFlag */) {
  62317. var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
  62318. getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
  62319. if (iterationTypes) {
  62320. return iterationTypes;
  62321. }
  62322. }
  62323. if (use & 1 /* AllowsSyncIterablesFlag */) {
  62324. var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
  62325. getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
  62326. if (iterationTypes) {
  62327. if (use & 2 /* AllowsAsyncIterablesFlag */) {
  62328. // for a sync iterable in an async context, only use the cached types if they are valid.
  62329. if (iterationTypes !== noIterationTypes) {
  62330. return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
  62331. }
  62332. }
  62333. else {
  62334. return iterationTypes;
  62335. }
  62336. }
  62337. }
  62338. if (use & 2 /* AllowsAsyncIterablesFlag */) {
  62339. var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
  62340. if (iterationTypes !== noIterationTypes) {
  62341. return iterationTypes;
  62342. }
  62343. }
  62344. if (use & 1 /* AllowsSyncIterablesFlag */) {
  62345. var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
  62346. if (iterationTypes !== noIterationTypes) {
  62347. if (use & 2 /* AllowsAsyncIterablesFlag */) {
  62348. return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
  62349. ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
  62350. : noIterationTypes);
  62351. }
  62352. else {
  62353. return iterationTypes;
  62354. }
  62355. }
  62356. }
  62357. return noIterationTypes;
  62358. }
  62359. /**
  62360. * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
  62361. * `AsyncIterable`-like type from the cache.
  62362. *
  62363. * NOTE: You probably don't want to call this directly and should be calling
  62364. * `getIterationTypesOfIterable` instead.
  62365. */
  62366. function getIterationTypesOfIterableCached(type, resolver) {
  62367. return getCachedIterationTypes(type, resolver.iterableCacheKey);
  62368. }
  62369. function getIterationTypesOfGlobalIterableType(globalType, resolver) {
  62370. var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
  62371. getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
  62372. return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
  62373. }
  62374. /**
  62375. * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
  62376. * type from from common heuristics.
  62377. *
  62378. * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
  62379. * returned. If we found iteration types, an `IterationTypes` record is returned.
  62380. * Otherwise, we return `undefined` to indicate to the caller it should perform a more
  62381. * exhaustive analysis.
  62382. *
  62383. * NOTE: You probably don't want to call this directly and should be calling
  62384. * `getIterationTypesOfIterable` instead.
  62385. */
  62386. function getIterationTypesOfIterableFast(type, resolver) {
  62387. // As an optimization, if the type is an instantiation of one of the following global types, then
  62388. // just grab its related type argument:
  62389. // - `Iterable<T>` or `AsyncIterable<T>`
  62390. // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
  62391. var globalType;
  62392. if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
  62393. isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
  62394. var yieldType = getTypeArguments(type)[0];
  62395. // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
  62396. // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
  62397. // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
  62398. // different definitions.
  62399. var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
  62400. return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
  62401. }
  62402. // As an optimization, if the type is an instantiation of the following global type, then
  62403. // just grab its related type arguments:
  62404. // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
  62405. if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
  62406. var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
  62407. return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
  62408. }
  62409. }
  62410. /**
  62411. * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
  62412. * type from its members.
  62413. *
  62414. * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
  62415. * record is returned. Otherwise, `noIterationTypes` is returned.
  62416. *
  62417. * NOTE: You probably don't want to call this directly and should be calling
  62418. * `getIterationTypesOfIterable` instead.
  62419. */
  62420. function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
  62421. var _a;
  62422. var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
  62423. var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
  62424. if (isTypeAny(methodType)) {
  62425. return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
  62426. }
  62427. var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
  62428. if (!ts.some(signatures)) {
  62429. return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
  62430. }
  62431. var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
  62432. var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
  62433. return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
  62434. }
  62435. function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
  62436. var message = allowAsyncIterables
  62437. ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
  62438. : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
  62439. errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
  62440. }
  62441. /**
  62442. * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
  62443. *
  62444. * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
  62445. * record is returned. Otherwise, `undefined` is returned.
  62446. */
  62447. function getIterationTypesOfIterator(type, resolver, errorNode) {
  62448. if (isTypeAny(type)) {
  62449. return anyIterationTypes;
  62450. }
  62451. var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
  62452. getIterationTypesOfIteratorFast(type, resolver) ||
  62453. getIterationTypesOfIteratorSlow(type, resolver, errorNode);
  62454. return iterationTypes === noIterationTypes ? undefined : iterationTypes;
  62455. }
  62456. /**
  62457. * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
  62458. * cache.
  62459. *
  62460. * NOTE: You probably don't want to call this directly and should be calling
  62461. * `getIterationTypesOfIterator` instead.
  62462. */
  62463. function getIterationTypesOfIteratorCached(type, resolver) {
  62464. return getCachedIterationTypes(type, resolver.iteratorCacheKey);
  62465. }
  62466. /**
  62467. * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
  62468. * cache or from common heuristics.
  62469. *
  62470. * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
  62471. * returned. If we found iteration types, an `IterationTypes` record is returned.
  62472. * Otherwise, we return `undefined` to indicate to the caller it should perform a more
  62473. * exhaustive analysis.
  62474. *
  62475. * NOTE: You probably don't want to call this directly and should be calling
  62476. * `getIterationTypesOfIterator` instead.
  62477. */
  62478. function getIterationTypesOfIteratorFast(type, resolver) {
  62479. // As an optimization, if the type is an instantiation of one of the following global types,
  62480. // then just grab its related type argument:
  62481. // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
  62482. // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
  62483. // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
  62484. var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
  62485. if (isReferenceToType(type, globalType)) {
  62486. var yieldType = getTypeArguments(type)[0];
  62487. // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
  62488. // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
  62489. // and `undefined` in our libs by default, a custom lib *could* use different definitions.
  62490. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
  62491. getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
  62492. var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
  62493. return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
  62494. }
  62495. if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
  62496. isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
  62497. var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
  62498. return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
  62499. }
  62500. }
  62501. function isIteratorResult(type, kind) {
  62502. // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
  62503. // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
  62504. // > If the end was not reached `done` is `false` and a value is available.
  62505. // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
  62506. var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
  62507. return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
  62508. }
  62509. function isYieldIteratorResult(type) {
  62510. return isIteratorResult(type, 0 /* Yield */);
  62511. }
  62512. function isReturnIteratorResult(type) {
  62513. return isIteratorResult(type, 1 /* Return */);
  62514. }
  62515. /**
  62516. * Gets the *yield* and *return* types of an `IteratorResult`-like type.
  62517. *
  62518. * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
  62519. * returned to indicate to the caller that it should handle the error. Otherwise, an
  62520. * `IterationTypes` record is returned.
  62521. */
  62522. function getIterationTypesOfIteratorResult(type) {
  62523. if (isTypeAny(type)) {
  62524. return anyIterationTypes;
  62525. }
  62526. var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
  62527. if (cachedTypes) {
  62528. return cachedTypes;
  62529. }
  62530. // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
  62531. // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
  62532. if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
  62533. var yieldType_1 = getTypeArguments(type)[0];
  62534. return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
  62535. }
  62536. if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
  62537. var returnType_1 = getTypeArguments(type)[0];
  62538. return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
  62539. }
  62540. // Choose any constituents that can produce the requested iteration type.
  62541. var yieldIteratorResult = filterType(type, isYieldIteratorResult);
  62542. var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
  62543. var returnIteratorResult = filterType(type, isReturnIteratorResult);
  62544. var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
  62545. if (!yieldType && !returnType) {
  62546. return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
  62547. }
  62548. // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
  62549. // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
  62550. // > `value` property may be absent from the conforming object if it does not inherit an explicit
  62551. // > `value` property.
  62552. return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
  62553. }
  62554. /**
  62555. * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
  62556. * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
  62557. *
  62558. * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
  62559. * record is returned. Otherwise, we return `undefined`.
  62560. */
  62561. function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
  62562. var method = getPropertyOfType(type, methodName);
  62563. // Ignore 'return' or 'throw' if they are missing.
  62564. if (!method && methodName !== "next") {
  62565. return undefined;
  62566. }
  62567. var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
  62568. ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
  62569. : undefined;
  62570. if (isTypeAny(methodType)) {
  62571. // `return()` and `throw()` don't provide a *next* type.
  62572. return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
  62573. }
  62574. // Both async and non-async iterators *must* have a `next` method.
  62575. var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
  62576. if (methodSignatures.length === 0) {
  62577. if (errorNode) {
  62578. var diagnostic = methodName === "next"
  62579. ? resolver.mustHaveANextMethodDiagnostic
  62580. : resolver.mustBeAMethodDiagnostic;
  62581. error(errorNode, diagnostic, methodName);
  62582. }
  62583. return methodName === "next" ? anyIterationTypes : undefined;
  62584. }
  62585. // Extract the first parameter and return type of each signature.
  62586. var methodParameterTypes;
  62587. var methodReturnTypes;
  62588. for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
  62589. var signature = methodSignatures_1[_i];
  62590. if (methodName !== "throw" && ts.some(signature.parameters)) {
  62591. methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
  62592. }
  62593. methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
  62594. }
  62595. // Resolve the *next* or *return* type from the first parameter of a `next()` or
  62596. // `return()` method, respectively.
  62597. var returnTypes;
  62598. var nextType;
  62599. if (methodName !== "throw") {
  62600. var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
  62601. if (methodName === "next") {
  62602. // The value of `next(value)` is *not* awaited by async generators
  62603. nextType = methodParameterType;
  62604. }
  62605. else if (methodName === "return") {
  62606. // The value of `return(value)` *is* awaited by async generators
  62607. var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
  62608. returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
  62609. }
  62610. }
  62611. // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
  62612. var yieldType;
  62613. var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
  62614. var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
  62615. var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
  62616. if (iterationTypes === noIterationTypes) {
  62617. if (errorNode) {
  62618. error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
  62619. }
  62620. yieldType = anyType;
  62621. returnTypes = ts.append(returnTypes, anyType);
  62622. }
  62623. else {
  62624. yieldType = iterationTypes.yieldType;
  62625. returnTypes = ts.append(returnTypes, iterationTypes.returnType);
  62626. }
  62627. return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
  62628. }
  62629. /**
  62630. * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
  62631. * type from its members.
  62632. *
  62633. * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
  62634. * record is returned. Otherwise, `noIterationTypes` is returned.
  62635. *
  62636. * NOTE: You probably don't want to call this directly and should be calling
  62637. * `getIterationTypesOfIterator` instead.
  62638. */
  62639. function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
  62640. var iterationTypes = combineIterationTypes([
  62641. getIterationTypesOfMethod(type, resolver, "next", errorNode),
  62642. getIterationTypesOfMethod(type, resolver, "return", errorNode),
  62643. getIterationTypesOfMethod(type, resolver, "throw", errorNode),
  62644. ]);
  62645. return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
  62646. }
  62647. /**
  62648. * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
  62649. * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
  62650. * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
  62651. */
  62652. function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
  62653. if (isTypeAny(returnType)) {
  62654. return undefined;
  62655. }
  62656. var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
  62657. return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
  62658. }
  62659. function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
  62660. if (isTypeAny(type)) {
  62661. return anyIterationTypes;
  62662. }
  62663. var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
  62664. var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
  62665. return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
  62666. getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
  62667. }
  62668. function checkBreakOrContinueStatement(node) {
  62669. // Grammar checking
  62670. if (!checkGrammarStatementInAmbientContext(node))
  62671. checkGrammarBreakOrContinueStatement(node);
  62672. // TODO: Check that target label is valid
  62673. }
  62674. function unwrapReturnType(returnType, functionFlags) {
  62675. var isGenerator = !!(functionFlags & 1 /* Generator */);
  62676. var isAsync = !!(functionFlags & 2 /* Async */);
  62677. return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType :
  62678. isAsync ? getPromisedTypeOfPromise(returnType) || errorType :
  62679. returnType;
  62680. }
  62681. function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
  62682. var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
  62683. return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
  62684. }
  62685. function checkReturnStatement(node) {
  62686. // Grammar checking
  62687. if (checkGrammarStatementInAmbientContext(node)) {
  62688. return;
  62689. }
  62690. var func = ts.getContainingFunction(node);
  62691. if (!func) {
  62692. grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
  62693. return;
  62694. }
  62695. var signature = getSignatureFromDeclaration(func);
  62696. var returnType = getReturnTypeOfSignature(signature);
  62697. var functionFlags = ts.getFunctionFlags(func);
  62698. if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
  62699. var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
  62700. if (func.kind === 164 /* SetAccessor */) {
  62701. if (node.expression) {
  62702. error(node, ts.Diagnostics.Setters_cannot_return_a_value);
  62703. }
  62704. }
  62705. else if (func.kind === 162 /* Constructor */) {
  62706. if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
  62707. error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
  62708. }
  62709. }
  62710. else if (getReturnTypeFromAnnotation(func)) {
  62711. var unwrappedReturnType = unwrapReturnType(returnType, functionFlags);
  62712. var unwrappedExprType = functionFlags & 2 /* Async */
  62713. ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)
  62714. : exprType;
  62715. if (unwrappedReturnType) {
  62716. // If the function has a return type, but promisedType is
  62717. // undefined, an error will be reported in checkAsyncFunctionReturnType
  62718. // so we don't need to report one here.
  62719. checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
  62720. }
  62721. }
  62722. }
  62723. else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
  62724. // The function has a return type, but the return statement doesn't have an expression.
  62725. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
  62726. }
  62727. }
  62728. function checkWithStatement(node) {
  62729. // Grammar checking for withStatement
  62730. if (!checkGrammarStatementInAmbientContext(node)) {
  62731. if (node.flags & 32768 /* AwaitContext */) {
  62732. grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
  62733. }
  62734. }
  62735. checkExpression(node.expression);
  62736. var sourceFile = ts.getSourceFileOfNode(node);
  62737. if (!hasParseDiagnostics(sourceFile)) {
  62738. var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
  62739. var end = node.statement.pos;
  62740. grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
  62741. }
  62742. }
  62743. function checkSwitchStatement(node) {
  62744. // Grammar checking
  62745. checkGrammarStatementInAmbientContext(node);
  62746. var firstDefaultClause;
  62747. var hasDuplicateDefaultClause = false;
  62748. var expressionType = checkExpression(node.expression);
  62749. var expressionIsLiteral = isLiteralType(expressionType);
  62750. ts.forEach(node.caseBlock.clauses, function (clause) {
  62751. // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
  62752. if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
  62753. if (firstDefaultClause === undefined) {
  62754. firstDefaultClause = clause;
  62755. }
  62756. else {
  62757. grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
  62758. hasDuplicateDefaultClause = true;
  62759. }
  62760. }
  62761. if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
  62762. // TypeScript 1.0 spec (April 2014): 5.9
  62763. // In a 'switch' statement, each 'case' expression must be of a type that is comparable
  62764. // to or from the type of the 'switch' expression.
  62765. var caseType = checkExpression(clause.expression);
  62766. var caseIsLiteral = isLiteralType(caseType);
  62767. var comparedExpressionType = expressionType;
  62768. if (!caseIsLiteral || !expressionIsLiteral) {
  62769. caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
  62770. comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
  62771. }
  62772. if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
  62773. // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
  62774. checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
  62775. }
  62776. }
  62777. ts.forEach(clause.statements, checkSourceElement);
  62778. if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
  62779. error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
  62780. }
  62781. });
  62782. if (node.caseBlock.locals) {
  62783. registerForUnusedIdentifiersCheck(node.caseBlock);
  62784. }
  62785. }
  62786. function checkLabeledStatement(node) {
  62787. // Grammar checking
  62788. if (!checkGrammarStatementInAmbientContext(node)) {
  62789. ts.findAncestor(node.parent, function (current) {
  62790. if (ts.isFunctionLike(current)) {
  62791. return "quit";
  62792. }
  62793. if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
  62794. grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
  62795. return true;
  62796. }
  62797. return false;
  62798. });
  62799. }
  62800. // ensure that label is unique
  62801. checkSourceElement(node.statement);
  62802. }
  62803. function checkThrowStatement(node) {
  62804. // Grammar checking
  62805. if (!checkGrammarStatementInAmbientContext(node)) {
  62806. if (node.expression === undefined) {
  62807. grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
  62808. }
  62809. }
  62810. if (node.expression) {
  62811. checkExpression(node.expression);
  62812. }
  62813. }
  62814. function checkTryStatement(node) {
  62815. // Grammar checking
  62816. checkGrammarStatementInAmbientContext(node);
  62817. checkBlock(node.tryBlock);
  62818. var catchClause = node.catchClause;
  62819. if (catchClause) {
  62820. // Grammar checking
  62821. if (catchClause.variableDeclaration) {
  62822. if (catchClause.variableDeclaration.type) {
  62823. grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
  62824. }
  62825. else if (catchClause.variableDeclaration.initializer) {
  62826. grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
  62827. }
  62828. else {
  62829. var blockLocals_1 = catchClause.block.locals;
  62830. if (blockLocals_1) {
  62831. ts.forEachKey(catchClause.locals, function (caughtName) {
  62832. var blockLocal = blockLocals_1.get(caughtName);
  62833. if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
  62834. grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
  62835. }
  62836. });
  62837. }
  62838. }
  62839. }
  62840. checkBlock(catchClause.block);
  62841. }
  62842. if (node.finallyBlock) {
  62843. checkBlock(node.finallyBlock);
  62844. }
  62845. }
  62846. function checkIndexConstraints(type) {
  62847. var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
  62848. var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
  62849. var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
  62850. var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
  62851. if (stringIndexType || numberIndexType) {
  62852. ts.forEach(getPropertiesOfObjectType(type), function (prop) {
  62853. var propType = getTypeOfSymbol(prop);
  62854. checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
  62855. checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
  62856. });
  62857. var classDeclaration = type.symbol.valueDeclaration;
  62858. if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
  62859. for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
  62860. var member = _a[_i];
  62861. // Only process instance properties with computed names here.
  62862. // Static properties cannot be in conflict with indexers,
  62863. // and properties with literal names were already checked.
  62864. if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
  62865. var symbol = getSymbolOfNode(member);
  62866. var propType = getTypeOfSymbol(symbol);
  62867. checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
  62868. checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
  62869. }
  62870. }
  62871. }
  62872. }
  62873. var errorNode;
  62874. if (stringIndexType && numberIndexType) {
  62875. errorNode = declaredNumberIndexer || declaredStringIndexer;
  62876. // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
  62877. if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
  62878. var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
  62879. errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
  62880. }
  62881. }
  62882. if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
  62883. error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
  62884. }
  62885. function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
  62886. // ESSymbol properties apply to neither string nor numeric indexers.
  62887. if (!indexType || ts.isKnownSymbol(prop)) {
  62888. return;
  62889. }
  62890. var propDeclaration = prop.valueDeclaration;
  62891. var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
  62892. // index is numeric and property name is not valid numeric literal
  62893. if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
  62894. return;
  62895. }
  62896. // perform property check if property or indexer is declared in 'type'
  62897. // this allows us to rule out cases when both property and indexer are inherited from the base class
  62898. var errorNode;
  62899. if (propDeclaration && name &&
  62900. (propDeclaration.kind === 209 /* BinaryExpression */ ||
  62901. name.kind === 154 /* ComputedPropertyName */ ||
  62902. prop.parent === containingType.symbol)) {
  62903. errorNode = propDeclaration;
  62904. }
  62905. else if (indexDeclaration) {
  62906. errorNode = indexDeclaration;
  62907. }
  62908. else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
  62909. // for interfaces property and indexer might be inherited from different bases
  62910. // check if any base class already has both property and indexer.
  62911. // check should be performed only if 'type' is the first type that brings property\indexer together
  62912. var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
  62913. errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
  62914. }
  62915. if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
  62916. var errorMessage = indexKind === 0 /* String */
  62917. ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
  62918. : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
  62919. error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
  62920. }
  62921. }
  62922. }
  62923. function checkTypeNameIsReserved(name, message) {
  62924. // TS 1.0 spec (April 2014): 3.6.1
  62925. // The predefined type keywords are reserved and cannot be used as names of user defined types.
  62926. switch (name.escapedText) {
  62927. case "any":
  62928. case "unknown":
  62929. case "number":
  62930. case "bigint":
  62931. case "boolean":
  62932. case "string":
  62933. case "symbol":
  62934. case "void":
  62935. case "object":
  62936. error(name, message, name.escapedText);
  62937. }
  62938. }
  62939. /**
  62940. * The name cannot be used as 'Object' of user defined types with special target.
  62941. */
  62942. function checkClassNameCollisionWithObject(name) {
  62943. if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
  62944. && moduleKind < ts.ModuleKind.ES2015) {
  62945. error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494
  62946. }
  62947. }
  62948. /**
  62949. * Check each type parameter and check that type parameters have no duplicate type parameter declarations
  62950. */
  62951. function checkTypeParameters(typeParameterDeclarations) {
  62952. if (typeParameterDeclarations) {
  62953. var seenDefault = false;
  62954. for (var i = 0; i < typeParameterDeclarations.length; i++) {
  62955. var node = typeParameterDeclarations[i];
  62956. checkTypeParameter(node);
  62957. if (produceDiagnostics) {
  62958. if (node.default) {
  62959. seenDefault = true;
  62960. checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
  62961. }
  62962. else if (seenDefault) {
  62963. error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
  62964. }
  62965. for (var j = 0; j < i; j++) {
  62966. if (typeParameterDeclarations[j].symbol === node.symbol) {
  62967. error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
  62968. }
  62969. }
  62970. }
  62971. }
  62972. }
  62973. }
  62974. /** Check that type parameter defaults only reference previously declared type parameters */
  62975. function checkTypeParametersNotReferenced(root, typeParameters, index) {
  62976. visit(root);
  62977. function visit(node) {
  62978. if (node.kind === 169 /* TypeReference */) {
  62979. var type = getTypeFromTypeReference(node);
  62980. if (type.flags & 262144 /* TypeParameter */) {
  62981. for (var i = index; i < typeParameters.length; i++) {
  62982. if (type.symbol === getSymbolOfNode(typeParameters[i])) {
  62983. error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
  62984. }
  62985. }
  62986. }
  62987. }
  62988. ts.forEachChild(node, visit);
  62989. }
  62990. }
  62991. /** Check that type parameter lists are identical across multiple declarations */
  62992. function checkTypeParameterListsIdentical(symbol) {
  62993. if (symbol.declarations.length === 1) {
  62994. return;
  62995. }
  62996. var links = getSymbolLinks(symbol);
  62997. if (!links.typeParametersChecked) {
  62998. links.typeParametersChecked = true;
  62999. var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
  63000. if (declarations.length <= 1) {
  63001. return;
  63002. }
  63003. var type = getDeclaredTypeOfSymbol(symbol);
  63004. if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
  63005. // Report an error on every conflicting declaration.
  63006. var name = symbolToString(symbol);
  63007. for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
  63008. var declaration = declarations_6[_i];
  63009. error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
  63010. }
  63011. }
  63012. }
  63013. }
  63014. function areTypeParametersIdentical(declarations, targetParameters) {
  63015. var maxTypeArgumentCount = ts.length(targetParameters);
  63016. var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
  63017. for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
  63018. var declaration = declarations_7[_i];
  63019. // If this declaration has too few or too many type parameters, we report an error
  63020. var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
  63021. var numTypeParameters = sourceParameters.length;
  63022. if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
  63023. return false;
  63024. }
  63025. for (var i = 0; i < numTypeParameters; i++) {
  63026. var source = sourceParameters[i];
  63027. var target = targetParameters[i];
  63028. // If the type parameter node does not have the same as the resolved type
  63029. // parameter at this position, we report an error.
  63030. if (source.name.escapedText !== target.symbol.escapedName) {
  63031. return false;
  63032. }
  63033. // If the type parameter node does not have an identical constraint as the resolved
  63034. // type parameter at this position, we report an error.
  63035. var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
  63036. var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
  63037. var targetConstraint = getConstraintOfTypeParameter(target);
  63038. // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
  63039. // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
  63040. if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
  63041. return false;
  63042. }
  63043. // If the type parameter node has a default and it is not identical to the default
  63044. // for the type parameter at this position, we report an error.
  63045. var sourceDefault = source.default && getTypeFromTypeNode(source.default);
  63046. var targetDefault = getDefaultFromTypeParameter(target);
  63047. if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
  63048. return false;
  63049. }
  63050. }
  63051. }
  63052. return true;
  63053. }
  63054. function checkClassExpression(node) {
  63055. checkClassLikeDeclaration(node);
  63056. checkNodeDeferred(node);
  63057. return getTypeOfSymbol(getSymbolOfNode(node));
  63058. }
  63059. function checkClassExpressionDeferred(node) {
  63060. ts.forEach(node.members, checkSourceElement);
  63061. registerForUnusedIdentifiersCheck(node);
  63062. }
  63063. function checkClassDeclaration(node) {
  63064. if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
  63065. grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
  63066. }
  63067. checkClassLikeDeclaration(node);
  63068. ts.forEach(node.members, checkSourceElement);
  63069. registerForUnusedIdentifiersCheck(node);
  63070. }
  63071. function checkClassLikeDeclaration(node) {
  63072. checkGrammarClassLikeDeclaration(node);
  63073. checkDecorators(node);
  63074. if (node.name) {
  63075. checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
  63076. checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
  63077. checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
  63078. if (!(node.flags & 8388608 /* Ambient */)) {
  63079. checkClassNameCollisionWithObject(node.name);
  63080. }
  63081. }
  63082. checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
  63083. checkExportsOnMergedDeclarations(node);
  63084. var symbol = getSymbolOfNode(node);
  63085. var type = getDeclaredTypeOfSymbol(symbol);
  63086. var typeWithThis = getTypeWithThisArgument(type);
  63087. var staticType = getTypeOfSymbol(symbol);
  63088. checkTypeParameterListsIdentical(symbol);
  63089. checkClassForDuplicateDeclarations(node);
  63090. // Only check for reserved static identifiers on non-ambient context.
  63091. if (!(node.flags & 8388608 /* Ambient */)) {
  63092. checkClassForStaticPropertyNameConflicts(node);
  63093. }
  63094. var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
  63095. if (baseTypeNode) {
  63096. ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
  63097. if (languageVersion < 2 /* ES2015 */) {
  63098. checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
  63099. }
  63100. // check both @extends and extends if both are specified.
  63101. var extendsNode = ts.getClassExtendsHeritageElement(node);
  63102. if (extendsNode && extendsNode !== baseTypeNode) {
  63103. checkExpression(extendsNode.expression);
  63104. }
  63105. var baseTypes = getBaseTypes(type);
  63106. if (baseTypes.length && produceDiagnostics) {
  63107. var baseType_1 = baseTypes[0];
  63108. var baseConstructorType = getBaseConstructorTypeOfClass(type);
  63109. var staticBaseType = getApparentType(baseConstructorType);
  63110. checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
  63111. checkSourceElement(baseTypeNode.expression);
  63112. if (ts.some(baseTypeNode.typeArguments)) {
  63113. ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
  63114. for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
  63115. var constructor = _a[_i];
  63116. if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
  63117. break;
  63118. }
  63119. }
  63120. }
  63121. var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
  63122. if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
  63123. issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
  63124. }
  63125. else {
  63126. // Report static side error only when instance type is assignable
  63127. checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
  63128. }
  63129. if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
  63130. error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
  63131. }
  63132. if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
  63133. // When the static base type is a "class-like" constructor function (but not actually a class), we verify
  63134. // that all instantiated base constructor signatures return the same type.
  63135. var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
  63136. if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
  63137. error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
  63138. }
  63139. }
  63140. checkKindsOfPropertyMemberOverrides(type, baseType_1);
  63141. }
  63142. }
  63143. var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node);
  63144. if (implementedTypeNodes) {
  63145. for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
  63146. var typeRefNode = implementedTypeNodes_1[_b];
  63147. if (!ts.isEntityNameExpression(typeRefNode.expression)) {
  63148. error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
  63149. }
  63150. checkTypeReferenceNode(typeRefNode);
  63151. if (produceDiagnostics) {
  63152. var t = getTypeFromTypeNode(typeRefNode);
  63153. if (t !== errorType) {
  63154. if (isValidBaseType(t)) {
  63155. var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
  63156. ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
  63157. ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
  63158. var baseWithThis = getTypeWithThisArgument(t, type.thisType);
  63159. if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
  63160. issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
  63161. }
  63162. }
  63163. else {
  63164. error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
  63165. }
  63166. }
  63167. }
  63168. }
  63169. }
  63170. if (produceDiagnostics) {
  63171. checkIndexConstraints(type);
  63172. checkTypeForDuplicateIndexSignatures(node);
  63173. checkPropertyInitialization(node);
  63174. }
  63175. }
  63176. function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
  63177. // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
  63178. var issuedMemberError = false;
  63179. var _loop_17 = function (member) {
  63180. if (ts.hasStaticModifier(member)) {
  63181. return "continue";
  63182. }
  63183. var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
  63184. if (declaredProp) {
  63185. var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
  63186. var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
  63187. if (prop && baseProp) {
  63188. var rootChain = function () { return ts.chainDiagnosticMessages(
  63189. /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
  63190. if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
  63191. issuedMemberError = true;
  63192. }
  63193. }
  63194. }
  63195. };
  63196. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  63197. var member = _a[_i];
  63198. _loop_17(member);
  63199. }
  63200. if (!issuedMemberError) {
  63201. // check again with diagnostics to generate a less-specific error
  63202. checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
  63203. }
  63204. }
  63205. function checkBaseTypeAccessibility(type, node) {
  63206. var signatures = getSignaturesOfType(type, 1 /* Construct */);
  63207. if (signatures.length) {
  63208. var declaration = signatures[0].declaration;
  63209. if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
  63210. var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
  63211. if (!isNodeWithinClass(node, typeClassDeclaration)) {
  63212. error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
  63213. }
  63214. }
  63215. }
  63216. }
  63217. function getTargetSymbol(s) {
  63218. // if symbol is instantiated its flags are not copied from the 'target'
  63219. // so we'll need to get back original 'target' symbol to work with correct set of flags
  63220. return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
  63221. }
  63222. function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
  63223. return ts.filter(symbol.declarations, function (d) {
  63224. return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
  63225. });
  63226. }
  63227. function checkKindsOfPropertyMemberOverrides(type, baseType) {
  63228. // TypeScript 1.0 spec (April 2014): 8.2.3
  63229. // A derived class inherits all members from its base class it doesn't override.
  63230. // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
  63231. // Both public and private property members are inherited, but only public property members can be overridden.
  63232. // A property member in a derived class is said to override a property member in a base class
  63233. // when the derived class property member has the same name and kind(instance or static)
  63234. // as the base class property member.
  63235. // The type of an overriding property member must be assignable(section 3.8.4)
  63236. // to the type of the overridden property member, or otherwise a compile - time error occurs.
  63237. // Base class instance member functions can be overridden by derived class instance member functions,
  63238. // but not by other kinds of members.
  63239. // Base class instance member variables and accessors can be overridden by
  63240. // derived class instance member variables and accessors, but not by other kinds of members.
  63241. // NOTE: assignability is checked in checkClassDeclaration
  63242. var baseProperties = getPropertiesOfType(baseType);
  63243. basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
  63244. var baseProperty = baseProperties_1[_i];
  63245. var base = getTargetSymbol(baseProperty);
  63246. if (base.flags & 4194304 /* Prototype */) {
  63247. continue;
  63248. }
  63249. var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
  63250. if (!baseSymbol) {
  63251. continue;
  63252. }
  63253. var derived = getTargetSymbol(baseSymbol);
  63254. var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
  63255. ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
  63256. // In order to resolve whether the inherited method was overridden in the base class or not,
  63257. // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
  63258. // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
  63259. if (derived === base) {
  63260. // derived class inherits base without override/redeclaration
  63261. var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
  63262. // It is an error to inherit an abstract member without implementing it or being declared abstract.
  63263. // If there is no declaration for the derived class (as in the case of class expressions),
  63264. // then the class cannot be declared abstract.
  63265. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
  63266. // Searches other base types for a declaration that would satisfy the inherited abstract member.
  63267. // (The class may have more than one base type via declaration merging with an interface with the
  63268. // same name.)
  63269. for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
  63270. var otherBaseType = _b[_a];
  63271. if (otherBaseType === baseType)
  63272. continue;
  63273. var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
  63274. var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
  63275. if (derivedElsewhere && derivedElsewhere !== base) {
  63276. continue basePropertyCheck;
  63277. }
  63278. }
  63279. if (derivedClassDecl.kind === 214 /* ClassExpression */) {
  63280. error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
  63281. }
  63282. else {
  63283. error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
  63284. }
  63285. }
  63286. }
  63287. else {
  63288. // derived overrides base.
  63289. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
  63290. if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
  63291. // either base or derived property is private - not override, skip it
  63292. continue;
  63293. }
  63294. var errorMessage = void 0;
  63295. var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
  63296. var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
  63297. if (basePropertyFlags && derivedPropertyFlags) {
  63298. // property/accessor is overridden with property/accessor
  63299. if (!compilerOptions.useDefineForClassFields
  63300. || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
  63301. || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
  63302. || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
  63303. // when the base property is abstract or from an interface, base/derived flags don't need to match
  63304. // same when the derived property is from an assignment
  63305. continue;
  63306. }
  63307. var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
  63308. var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
  63309. if (overriddenInstanceProperty || overriddenInstanceAccessor) {
  63310. var errorMessage_1 = overriddenInstanceProperty ?
  63311. ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
  63312. ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
  63313. error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
  63314. }
  63315. else {
  63316. var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
  63317. if (uninitialized
  63318. && !(derived.flags & 33554432 /* Transient */)
  63319. && !(baseDeclarationFlags & 128 /* Abstract */)
  63320. && !(derivedDeclarationFlags & 128 /* Abstract */)
  63321. && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
  63322. var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
  63323. var propName = uninitialized.name;
  63324. if (uninitialized.exclamationToken
  63325. || !constructor
  63326. || !ts.isIdentifier(propName)
  63327. || !strictNullChecks
  63328. || !isPropertyInitializedInConstructor(propName, type, constructor)) {
  63329. var errorMessage_2 = ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration;
  63330. error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
  63331. }
  63332. }
  63333. }
  63334. // correct case
  63335. continue;
  63336. }
  63337. else if (isPrototypeProperty(base)) {
  63338. if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
  63339. // method is overridden with method or property -- correct case
  63340. continue;
  63341. }
  63342. else {
  63343. ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
  63344. errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
  63345. }
  63346. }
  63347. else if (base.flags & 98304 /* Accessor */) {
  63348. errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
  63349. }
  63350. else {
  63351. errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
  63352. }
  63353. error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
  63354. }
  63355. }
  63356. }
  63357. function checkInheritedPropertiesAreIdentical(type, typeNode) {
  63358. var baseTypes = getBaseTypes(type);
  63359. if (baseTypes.length < 2) {
  63360. return true;
  63361. }
  63362. var seen = ts.createUnderscoreEscapedMap();
  63363. ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
  63364. var ok = true;
  63365. for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
  63366. var base = baseTypes_2[_i];
  63367. var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
  63368. for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) {
  63369. var prop = properties_4[_a];
  63370. var existing = seen.get(prop.escapedName);
  63371. if (!existing) {
  63372. seen.set(prop.escapedName, { prop: prop, containingType: base });
  63373. }
  63374. else {
  63375. var isInheritedProperty = existing.containingType !== type;
  63376. if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
  63377. ok = false;
  63378. var typeName1 = typeToString(existing.containingType);
  63379. var typeName2 = typeToString(base);
  63380. var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
  63381. errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
  63382. diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
  63383. }
  63384. }
  63385. }
  63386. }
  63387. return ok;
  63388. }
  63389. function checkPropertyInitialization(node) {
  63390. if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
  63391. return;
  63392. }
  63393. var constructor = findConstructorDeclaration(node);
  63394. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  63395. var member = _a[_i];
  63396. if (ts.getModifierFlags(member) & 2 /* Ambient */) {
  63397. continue;
  63398. }
  63399. if (isInstancePropertyWithoutInitializer(member)) {
  63400. var propName = member.name;
  63401. if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
  63402. var type = getTypeOfSymbol(getSymbolOfNode(member));
  63403. if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
  63404. if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
  63405. error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
  63406. }
  63407. }
  63408. }
  63409. }
  63410. }
  63411. }
  63412. function isInstancePropertyWithoutInitializer(node) {
  63413. return node.kind === 159 /* PropertyDeclaration */ &&
  63414. !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
  63415. !node.exclamationToken &&
  63416. !node.initializer;
  63417. }
  63418. function isPropertyInitializedInConstructor(propName, propType, constructor) {
  63419. var reference = ts.createPropertyAccess(ts.createThis(), propName);
  63420. reference.expression.parent = reference;
  63421. reference.parent = constructor;
  63422. reference.flowNode = constructor.returnFlowNode;
  63423. var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
  63424. return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
  63425. }
  63426. function checkInterfaceDeclaration(node) {
  63427. // Grammar checking
  63428. if (!checkGrammarDecoratorsAndModifiers(node))
  63429. checkGrammarInterfaceDeclaration(node);
  63430. checkTypeParameters(node.typeParameters);
  63431. if (produceDiagnostics) {
  63432. checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
  63433. checkExportsOnMergedDeclarations(node);
  63434. var symbol = getSymbolOfNode(node);
  63435. checkTypeParameterListsIdentical(symbol);
  63436. // Only check this symbol once
  63437. var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
  63438. if (node === firstInterfaceDecl) {
  63439. var type = getDeclaredTypeOfSymbol(symbol);
  63440. var typeWithThis = getTypeWithThisArgument(type);
  63441. // run subsequent checks only if first set succeeded
  63442. if (checkInheritedPropertiesAreIdentical(type, node.name)) {
  63443. for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
  63444. var baseType = _a[_i];
  63445. checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
  63446. }
  63447. checkIndexConstraints(type);
  63448. }
  63449. }
  63450. checkObjectTypeForDuplicateDeclarations(node);
  63451. }
  63452. ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
  63453. if (!ts.isEntityNameExpression(heritageElement.expression)) {
  63454. error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
  63455. }
  63456. checkTypeReferenceNode(heritageElement);
  63457. });
  63458. ts.forEach(node.members, checkSourceElement);
  63459. if (produceDiagnostics) {
  63460. checkTypeForDuplicateIndexSignatures(node);
  63461. registerForUnusedIdentifiersCheck(node);
  63462. }
  63463. }
  63464. function checkTypeAliasDeclaration(node) {
  63465. // Grammar checking
  63466. checkGrammarDecoratorsAndModifiers(node);
  63467. checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
  63468. checkExportsOnMergedDeclarations(node);
  63469. checkTypeParameters(node.typeParameters);
  63470. checkSourceElement(node.type);
  63471. registerForUnusedIdentifiersCheck(node);
  63472. }
  63473. function computeEnumMemberValues(node) {
  63474. var nodeLinks = getNodeLinks(node);
  63475. if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
  63476. nodeLinks.flags |= 16384 /* EnumValuesComputed */;
  63477. var autoValue = 0;
  63478. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  63479. var member = _a[_i];
  63480. var value = computeMemberValue(member, autoValue);
  63481. getNodeLinks(member).enumMemberValue = value;
  63482. autoValue = typeof value === "number" ? value + 1 : undefined;
  63483. }
  63484. }
  63485. }
  63486. function computeMemberValue(member, autoValue) {
  63487. if (isComputedNonLiteralName(member.name)) {
  63488. error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
  63489. }
  63490. else {
  63491. var text = ts.getTextOfPropertyName(member.name);
  63492. if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
  63493. error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
  63494. }
  63495. }
  63496. if (member.initializer) {
  63497. return computeConstantValue(member);
  63498. }
  63499. // In ambient non-const numeric enum declarations, enum members without initializers are
  63500. // considered computed members (as opposed to having auto-incremented values).
  63501. if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
  63502. return undefined;
  63503. }
  63504. // If the member declaration specifies no value, the member is considered a constant enum member.
  63505. // If the member is the first member in the enum declaration, it is assigned the value zero.
  63506. // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
  63507. // occurs if the immediately preceding member is not a constant enum member.
  63508. if (autoValue !== undefined) {
  63509. return autoValue;
  63510. }
  63511. error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
  63512. return undefined;
  63513. }
  63514. function computeConstantValue(member) {
  63515. var enumKind = getEnumKind(getSymbolOfNode(member.parent));
  63516. var isConstEnum = ts.isEnumConst(member.parent);
  63517. var initializer = member.initializer;
  63518. var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
  63519. if (value !== undefined) {
  63520. if (isConstEnum && typeof value === "number" && !isFinite(value)) {
  63521. error(initializer, isNaN(value) ?
  63522. ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
  63523. ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
  63524. }
  63525. }
  63526. else if (enumKind === 1 /* Literal */) {
  63527. error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
  63528. return 0;
  63529. }
  63530. else if (isConstEnum) {
  63531. error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
  63532. }
  63533. else if (member.parent.flags & 8388608 /* Ambient */) {
  63534. error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
  63535. }
  63536. else {
  63537. // Only here do we need to check that the initializer is assignable to the enum type.
  63538. checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
  63539. }
  63540. return value;
  63541. function evaluate(expr) {
  63542. switch (expr.kind) {
  63543. case 207 /* PrefixUnaryExpression */:
  63544. var value_2 = evaluate(expr.operand);
  63545. if (typeof value_2 === "number") {
  63546. switch (expr.operator) {
  63547. case 39 /* PlusToken */: return value_2;
  63548. case 40 /* MinusToken */: return -value_2;
  63549. case 54 /* TildeToken */: return ~value_2;
  63550. }
  63551. }
  63552. break;
  63553. case 209 /* BinaryExpression */:
  63554. var left = evaluate(expr.left);
  63555. var right = evaluate(expr.right);
  63556. if (typeof left === "number" && typeof right === "number") {
  63557. switch (expr.operatorToken.kind) {
  63558. case 51 /* BarToken */: return left | right;
  63559. case 50 /* AmpersandToken */: return left & right;
  63560. case 48 /* GreaterThanGreaterThanToken */: return left >> right;
  63561. case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
  63562. case 47 /* LessThanLessThanToken */: return left << right;
  63563. case 52 /* CaretToken */: return left ^ right;
  63564. case 41 /* AsteriskToken */: return left * right;
  63565. case 43 /* SlashToken */: return left / right;
  63566. case 39 /* PlusToken */: return left + right;
  63567. case 40 /* MinusToken */: return left - right;
  63568. case 44 /* PercentToken */: return left % right;
  63569. case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
  63570. }
  63571. }
  63572. else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
  63573. return left + right;
  63574. }
  63575. break;
  63576. case 10 /* StringLiteral */:
  63577. case 14 /* NoSubstitutionTemplateLiteral */:
  63578. return expr.text;
  63579. case 8 /* NumericLiteral */:
  63580. checkGrammarNumericLiteral(expr);
  63581. return +expr.text;
  63582. case 200 /* ParenthesizedExpression */:
  63583. return evaluate(expr.expression);
  63584. case 75 /* Identifier */:
  63585. var identifier = expr;
  63586. if (isInfinityOrNaNString(identifier.escapedText)) {
  63587. return +(identifier.escapedText);
  63588. }
  63589. return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
  63590. case 195 /* ElementAccessExpression */:
  63591. case 194 /* PropertyAccessExpression */:
  63592. var ex = expr;
  63593. if (isConstantMemberAccess(ex)) {
  63594. var type = getTypeOfExpression(ex.expression);
  63595. if (type.symbol && type.symbol.flags & 384 /* Enum */) {
  63596. var name = void 0;
  63597. if (ex.kind === 194 /* PropertyAccessExpression */) {
  63598. name = ex.name.escapedText;
  63599. }
  63600. else {
  63601. name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
  63602. }
  63603. return evaluateEnumMember(expr, type.symbol, name);
  63604. }
  63605. }
  63606. break;
  63607. }
  63608. return undefined;
  63609. }
  63610. function evaluateEnumMember(expr, enumSymbol, name) {
  63611. var memberSymbol = enumSymbol.exports.get(name);
  63612. if (memberSymbol) {
  63613. var declaration = memberSymbol.valueDeclaration;
  63614. if (declaration !== member) {
  63615. if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
  63616. return getEnumMemberValue(declaration);
  63617. }
  63618. error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
  63619. return 0;
  63620. }
  63621. }
  63622. return undefined;
  63623. }
  63624. }
  63625. function isConstantMemberAccess(node) {
  63626. return node.kind === 75 /* Identifier */ ||
  63627. node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
  63628. node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
  63629. ts.isStringLiteralLike(node.argumentExpression);
  63630. }
  63631. function checkEnumDeclaration(node) {
  63632. if (!produceDiagnostics) {
  63633. return;
  63634. }
  63635. // Grammar checking
  63636. checkGrammarDecoratorsAndModifiers(node);
  63637. checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
  63638. checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
  63639. checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
  63640. checkExportsOnMergedDeclarations(node);
  63641. node.members.forEach(checkEnumMember);
  63642. computeEnumMemberValues(node);
  63643. // Spec 2014 - Section 9.3:
  63644. // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
  63645. // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
  63646. // for the first member.
  63647. //
  63648. // Only perform this check once per symbol
  63649. var enumSymbol = getSymbolOfNode(node);
  63650. var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
  63651. if (node === firstDeclaration) {
  63652. if (enumSymbol.declarations.length > 1) {
  63653. var enumIsConst_1 = ts.isEnumConst(node);
  63654. // check that const is placed\omitted on all enum declarations
  63655. ts.forEach(enumSymbol.declarations, function (decl) {
  63656. if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
  63657. error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
  63658. }
  63659. });
  63660. }
  63661. var seenEnumMissingInitialInitializer_1 = false;
  63662. ts.forEach(enumSymbol.declarations, function (declaration) {
  63663. // return true if we hit a violation of the rule, false otherwise
  63664. if (declaration.kind !== 248 /* EnumDeclaration */) {
  63665. return false;
  63666. }
  63667. var enumDeclaration = declaration;
  63668. if (!enumDeclaration.members.length) {
  63669. return false;
  63670. }
  63671. var firstEnumMember = enumDeclaration.members[0];
  63672. if (!firstEnumMember.initializer) {
  63673. if (seenEnumMissingInitialInitializer_1) {
  63674. error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
  63675. }
  63676. else {
  63677. seenEnumMissingInitialInitializer_1 = true;
  63678. }
  63679. }
  63680. });
  63681. }
  63682. }
  63683. function checkEnumMember(node) {
  63684. if (ts.isPrivateIdentifier(node.name)) {
  63685. error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
  63686. }
  63687. }
  63688. function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
  63689. var declarations = symbol.declarations;
  63690. for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
  63691. var declaration = declarations_8[_i];
  63692. if ((declaration.kind === 245 /* ClassDeclaration */ ||
  63693. (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
  63694. !(declaration.flags & 8388608 /* Ambient */)) {
  63695. return declaration;
  63696. }
  63697. }
  63698. return undefined;
  63699. }
  63700. function inSameLexicalScope(node1, node2) {
  63701. var container1 = ts.getEnclosingBlockScopeContainer(node1);
  63702. var container2 = ts.getEnclosingBlockScopeContainer(node2);
  63703. if (isGlobalSourceFile(container1)) {
  63704. return isGlobalSourceFile(container2);
  63705. }
  63706. else if (isGlobalSourceFile(container2)) {
  63707. return false;
  63708. }
  63709. else {
  63710. return container1 === container2;
  63711. }
  63712. }
  63713. function checkModuleDeclaration(node) {
  63714. if (produceDiagnostics) {
  63715. // Grammar checking
  63716. var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
  63717. var inAmbientContext = node.flags & 8388608 /* Ambient */;
  63718. if (isGlobalAugmentation && !inAmbientContext) {
  63719. error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
  63720. }
  63721. var isAmbientExternalModule = ts.isAmbientModule(node);
  63722. var contextErrorMessage = isAmbientExternalModule
  63723. ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
  63724. : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
  63725. if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
  63726. // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
  63727. return;
  63728. }
  63729. if (!checkGrammarDecoratorsAndModifiers(node)) {
  63730. if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
  63731. grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
  63732. }
  63733. }
  63734. if (ts.isIdentifier(node.name)) {
  63735. checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
  63736. checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
  63737. }
  63738. checkExportsOnMergedDeclarations(node);
  63739. var symbol = getSymbolOfNode(node);
  63740. // The following checks only apply on a non-ambient instantiated module declaration.
  63741. if (symbol.flags & 512 /* ValueModule */
  63742. && !inAmbientContext
  63743. && symbol.declarations.length > 1
  63744. && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
  63745. var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
  63746. if (firstNonAmbientClassOrFunc) {
  63747. if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
  63748. error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
  63749. }
  63750. else if (node.pos < firstNonAmbientClassOrFunc.pos) {
  63751. error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
  63752. }
  63753. }
  63754. // if the module merges with a class declaration in the same lexical scope,
  63755. // we need to track this to ensure the correct emit.
  63756. var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
  63757. if (mergedClass &&
  63758. inSameLexicalScope(node, mergedClass)) {
  63759. getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
  63760. }
  63761. }
  63762. if (isAmbientExternalModule) {
  63763. if (ts.isExternalModuleAugmentation(node)) {
  63764. // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
  63765. // otherwise we'll be swamped in cascading errors.
  63766. // We can detect if augmentation was applied using following rules:
  63767. // - augmentation for a global scope is always applied
  63768. // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
  63769. var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
  63770. if (checkBody && node.body) {
  63771. for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
  63772. var statement = _a[_i];
  63773. checkModuleAugmentationElement(statement, isGlobalAugmentation);
  63774. }
  63775. }
  63776. }
  63777. else if (isGlobalSourceFile(node.parent)) {
  63778. if (isGlobalAugmentation) {
  63779. error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
  63780. }
  63781. else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
  63782. error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
  63783. }
  63784. }
  63785. else {
  63786. if (isGlobalAugmentation) {
  63787. error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
  63788. }
  63789. else {
  63790. // Node is not an augmentation and is not located on the script level.
  63791. // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
  63792. error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
  63793. }
  63794. }
  63795. }
  63796. }
  63797. if (node.body) {
  63798. checkSourceElement(node.body);
  63799. if (!ts.isGlobalScopeAugmentation(node)) {
  63800. registerForUnusedIdentifiersCheck(node);
  63801. }
  63802. }
  63803. }
  63804. function checkModuleAugmentationElement(node, isGlobalAugmentation) {
  63805. switch (node.kind) {
  63806. case 225 /* VariableStatement */:
  63807. // error each individual name in variable statement instead of marking the entire variable statement
  63808. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  63809. var decl = _a[_i];
  63810. checkModuleAugmentationElement(decl, isGlobalAugmentation);
  63811. }
  63812. break;
  63813. case 259 /* ExportAssignment */:
  63814. case 260 /* ExportDeclaration */:
  63815. grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
  63816. break;
  63817. case 253 /* ImportEqualsDeclaration */:
  63818. case 254 /* ImportDeclaration */:
  63819. grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
  63820. break;
  63821. case 191 /* BindingElement */:
  63822. case 242 /* VariableDeclaration */:
  63823. var name = node.name;
  63824. if (ts.isBindingPattern(name)) {
  63825. for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
  63826. var el = _c[_b];
  63827. // mark individual names in binding pattern
  63828. checkModuleAugmentationElement(el, isGlobalAugmentation);
  63829. }
  63830. break;
  63831. }
  63832. // falls through
  63833. case 245 /* ClassDeclaration */:
  63834. case 248 /* EnumDeclaration */:
  63835. case 244 /* FunctionDeclaration */:
  63836. case 246 /* InterfaceDeclaration */:
  63837. case 249 /* ModuleDeclaration */:
  63838. case 247 /* TypeAliasDeclaration */:
  63839. if (isGlobalAugmentation) {
  63840. return;
  63841. }
  63842. var symbol = getSymbolOfNode(node);
  63843. if (symbol) {
  63844. // module augmentations cannot introduce new names on the top level scope of the module
  63845. // this is done it two steps
  63846. // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
  63847. // 2. main check - report error if value declaration of the parent symbol is module augmentation)
  63848. var reportError = !(symbol.flags & 33554432 /* Transient */);
  63849. if (!reportError) {
  63850. // symbol should not originate in augmentation
  63851. reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
  63852. }
  63853. }
  63854. break;
  63855. }
  63856. }
  63857. function getFirstNonModuleExportsIdentifier(node) {
  63858. switch (node.kind) {
  63859. case 75 /* Identifier */:
  63860. return node;
  63861. case 153 /* QualifiedName */:
  63862. do {
  63863. node = node.left;
  63864. } while (node.kind !== 75 /* Identifier */);
  63865. return node;
  63866. case 194 /* PropertyAccessExpression */:
  63867. do {
  63868. if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
  63869. return node.name;
  63870. }
  63871. node = node.expression;
  63872. } while (node.kind !== 75 /* Identifier */);
  63873. return node;
  63874. }
  63875. }
  63876. function checkExternalImportOrExportDeclaration(node) {
  63877. var moduleName = ts.getExternalModuleName(node);
  63878. if (!moduleName || ts.nodeIsMissing(moduleName)) {
  63879. // Should be a parse error.
  63880. return false;
  63881. }
  63882. if (!ts.isStringLiteral(moduleName)) {
  63883. error(moduleName, ts.Diagnostics.String_literal_expected);
  63884. return false;
  63885. }
  63886. var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
  63887. if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
  63888. error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
  63889. ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
  63890. ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
  63891. return false;
  63892. }
  63893. if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
  63894. // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration
  63895. // no need to do this again.
  63896. if (!isTopLevelInExternalModuleAugmentation(node)) {
  63897. // TypeScript 1.0 spec (April 2013): 12.1.6
  63898. // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
  63899. // other external modules only through top - level external module names.
  63900. // Relative external module names are not permitted.
  63901. error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
  63902. return false;
  63903. }
  63904. }
  63905. return true;
  63906. }
  63907. function checkAliasSymbol(node) {
  63908. var symbol = getSymbolOfNode(node);
  63909. var target = resolveAlias(symbol);
  63910. var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
  63911. if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
  63912. // For external modules symbol represents local symbol for an alias.
  63913. // This local symbol will merge any other local declarations (excluding other aliases)
  63914. // and symbol.flags will contains combined representation for all merged declaration.
  63915. // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
  63916. // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
  63917. // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
  63918. symbol = getMergedSymbol(symbol.exportSymbol || symbol);
  63919. var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
  63920. (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
  63921. (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
  63922. if (target.flags & excludedMeanings) {
  63923. var message = node.kind === 263 /* ExportSpecifier */ ?
  63924. ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
  63925. ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
  63926. error(node, message, symbolToString(symbol));
  63927. }
  63928. // Don't allow to re-export something with no value side when `--isolatedModules` is set.
  63929. if (compilerOptions.isolatedModules
  63930. && node.kind === 263 /* ExportSpecifier */
  63931. && !node.parent.parent.isTypeOnly
  63932. && !(target.flags & 111551 /* Value */)
  63933. && !(node.flags & 8388608 /* Ambient */)) {
  63934. error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
  63935. }
  63936. }
  63937. }
  63938. function checkImportBinding(node) {
  63939. checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
  63940. checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
  63941. checkAliasSymbol(node);
  63942. }
  63943. function checkImportDeclaration(node) {
  63944. if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
  63945. // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
  63946. return;
  63947. }
  63948. if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
  63949. grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
  63950. }
  63951. if (checkExternalImportOrExportDeclaration(node)) {
  63952. var importClause = node.importClause;
  63953. if (importClause && !checkGrammarImportClause(importClause)) {
  63954. if (importClause.name) {
  63955. checkImportBinding(importClause);
  63956. }
  63957. if (importClause.namedBindings) {
  63958. if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
  63959. checkImportBinding(importClause.namedBindings);
  63960. }
  63961. else {
  63962. var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
  63963. if (moduleExisted) {
  63964. ts.forEach(importClause.namedBindings.elements, checkImportBinding);
  63965. }
  63966. }
  63967. }
  63968. }
  63969. }
  63970. }
  63971. function checkImportEqualsDeclaration(node) {
  63972. if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
  63973. // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
  63974. return;
  63975. }
  63976. checkGrammarDecoratorsAndModifiers(node);
  63977. if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
  63978. checkImportBinding(node);
  63979. if (ts.hasModifier(node, 1 /* Export */)) {
  63980. markExportAsReferenced(node);
  63981. }
  63982. if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
  63983. var target = resolveAlias(getSymbolOfNode(node));
  63984. if (target !== unknownSymbol) {
  63985. if (target.flags & 111551 /* Value */) {
  63986. // Target is a value symbol, check that it is not hidden by a local declaration with the same name
  63987. var moduleName = ts.getFirstIdentifier(node.moduleReference);
  63988. if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
  63989. error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
  63990. }
  63991. }
  63992. if (target.flags & 788968 /* Type */) {
  63993. checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
  63994. }
  63995. }
  63996. }
  63997. else {
  63998. if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
  63999. // Import equals declaration is deprecated in es6 or above
  64000. grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
  64001. }
  64002. }
  64003. }
  64004. }
  64005. function checkExportDeclaration(node) {
  64006. if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
  64007. // If we hit an export in an illegal context, just bail out to avoid cascading errors.
  64008. return;
  64009. }
  64010. if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
  64011. grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
  64012. }
  64013. checkGrammarExportDeclaration(node);
  64014. if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
  64015. if (node.exportClause) {
  64016. // export { x, y }
  64017. // export { x, y } from "foo"
  64018. if (ts.isNamedExports(node.exportClause)) {
  64019. ts.forEach(node.exportClause.elements, checkExportSpecifier);
  64020. }
  64021. else if (!ts.isNamespaceExport(node.exportClause)) {
  64022. checkImportBinding(node.exportClause);
  64023. }
  64024. var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
  64025. var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
  64026. !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
  64027. if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
  64028. error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
  64029. }
  64030. }
  64031. else {
  64032. // export * from "foo"
  64033. var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
  64034. if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
  64035. error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
  64036. }
  64037. if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
  64038. checkExternalEmitHelpers(node, 65536 /* ExportStar */);
  64039. }
  64040. }
  64041. }
  64042. }
  64043. function checkGrammarExportDeclaration(node) {
  64044. var _a;
  64045. var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
  64046. if (isTypeOnlyExportStar) {
  64047. grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
  64048. }
  64049. return !isTypeOnlyExportStar;
  64050. }
  64051. function checkGrammarModuleElementContext(node, errorMessage) {
  64052. var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
  64053. if (!isInAppropriateContext) {
  64054. grammarErrorOnFirstToken(node, errorMessage);
  64055. }
  64056. return !isInAppropriateContext;
  64057. }
  64058. function importClauseContainsReferencedImport(importClause) {
  64059. return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
  64060. return !!getSymbolOfNode(declaration).isReferenced;
  64061. });
  64062. }
  64063. function importClauseContainsConstEnumUsedAsValue(importClause) {
  64064. return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
  64065. return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
  64066. });
  64067. }
  64068. function checkImportsForTypeOnlyConversion(sourceFile) {
  64069. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  64070. var statement = _a[_i];
  64071. if (ts.isImportDeclaration(statement) &&
  64072. statement.importClause &&
  64073. !statement.importClause.isTypeOnly &&
  64074. importClauseContainsReferencedImport(statement.importClause) &&
  64075. !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
  64076. !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
  64077. error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
  64078. }
  64079. }
  64080. }
  64081. function checkExportSpecifier(node) {
  64082. checkAliasSymbol(node);
  64083. if (ts.getEmitDeclarations(compilerOptions)) {
  64084. collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
  64085. }
  64086. if (!node.parent.parent.moduleSpecifier) {
  64087. var exportedName = node.propertyName || node.name;
  64088. // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
  64089. var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
  64090. /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
  64091. if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
  64092. error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
  64093. }
  64094. else {
  64095. markExportAsReferenced(node);
  64096. var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
  64097. if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
  64098. checkExpressionCached(node.propertyName || node.name);
  64099. }
  64100. }
  64101. }
  64102. }
  64103. function checkExportAssignment(node) {
  64104. if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
  64105. // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
  64106. return;
  64107. }
  64108. var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
  64109. if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
  64110. if (node.isExportEquals) {
  64111. error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
  64112. }
  64113. else {
  64114. error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
  64115. }
  64116. return;
  64117. }
  64118. // Grammar checking
  64119. if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
  64120. grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
  64121. }
  64122. if (node.expression.kind === 75 /* Identifier */) {
  64123. var id = node.expression;
  64124. var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
  64125. if (sym) {
  64126. markAliasReferenced(sym, id);
  64127. // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
  64128. var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
  64129. if (target === unknownSymbol || target.flags & 111551 /* Value */) {
  64130. // However if it is a value, we need to check it's being used correctly
  64131. checkExpressionCached(node.expression);
  64132. }
  64133. }
  64134. if (ts.getEmitDeclarations(compilerOptions)) {
  64135. collectLinkedAliases(node.expression, /*setVisibility*/ true);
  64136. }
  64137. }
  64138. else {
  64139. checkExpressionCached(node.expression);
  64140. }
  64141. checkExternalModuleExports(container);
  64142. if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
  64143. grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
  64144. }
  64145. if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
  64146. if (moduleKind >= ts.ModuleKind.ES2015) {
  64147. // export assignment is not supported in es6 modules
  64148. grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
  64149. }
  64150. else if (moduleKind === ts.ModuleKind.System) {
  64151. // system modules does not support export assignment
  64152. grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
  64153. }
  64154. }
  64155. }
  64156. function hasExportedMembers(moduleSymbol) {
  64157. return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
  64158. }
  64159. function checkExternalModuleExports(node) {
  64160. var moduleSymbol = getSymbolOfNode(node);
  64161. var links = getSymbolLinks(moduleSymbol);
  64162. if (!links.exportsChecked) {
  64163. var exportEqualsSymbol = moduleSymbol.exports.get("export=");
  64164. if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
  64165. var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
  64166. if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
  64167. error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
  64168. }
  64169. }
  64170. // Checks for export * conflicts
  64171. var exports_2 = getExportsOfModule(moduleSymbol);
  64172. if (exports_2) {
  64173. exports_2.forEach(function (_a, id) {
  64174. var declarations = _a.declarations, flags = _a.flags;
  64175. if (id === "__export") {
  64176. return;
  64177. }
  64178. // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
  64179. // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
  64180. if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
  64181. return;
  64182. }
  64183. var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
  64184. if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
  64185. // it is legal to merge type alias with other values
  64186. // so count should be either 1 (just type alias) or 2 (type alias + merged value)
  64187. return;
  64188. }
  64189. if (exportedDeclarationsCount > 1) {
  64190. for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
  64191. var declaration = declarations_9[_i];
  64192. if (isNotOverload(declaration)) {
  64193. diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
  64194. }
  64195. }
  64196. }
  64197. });
  64198. }
  64199. links.exportsChecked = true;
  64200. }
  64201. }
  64202. function checkSourceElement(node) {
  64203. if (node) {
  64204. var saveCurrentNode = currentNode;
  64205. currentNode = node;
  64206. instantiationCount = 0;
  64207. checkSourceElementWorker(node);
  64208. currentNode = saveCurrentNode;
  64209. }
  64210. }
  64211. function checkSourceElementWorker(node) {
  64212. if (ts.isInJSFile(node)) {
  64213. ts.forEach(node.jsDoc, function (_a) {
  64214. var tags = _a.tags;
  64215. return ts.forEach(tags, checkSourceElement);
  64216. });
  64217. }
  64218. var kind = node.kind;
  64219. if (cancellationToken) {
  64220. // Only bother checking on a few construct kinds. We don't want to be excessively
  64221. // hitting the cancellation token on every node we check.
  64222. switch (kind) {
  64223. case 249 /* ModuleDeclaration */:
  64224. case 245 /* ClassDeclaration */:
  64225. case 246 /* InterfaceDeclaration */:
  64226. case 244 /* FunctionDeclaration */:
  64227. cancellationToken.throwIfCancellationRequested();
  64228. }
  64229. }
  64230. if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
  64231. errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
  64232. }
  64233. switch (kind) {
  64234. case 155 /* TypeParameter */:
  64235. return checkTypeParameter(node);
  64236. case 156 /* Parameter */:
  64237. return checkParameter(node);
  64238. case 159 /* PropertyDeclaration */:
  64239. return checkPropertyDeclaration(node);
  64240. case 158 /* PropertySignature */:
  64241. return checkPropertySignature(node);
  64242. case 170 /* FunctionType */:
  64243. case 171 /* ConstructorType */:
  64244. case 165 /* CallSignature */:
  64245. case 166 /* ConstructSignature */:
  64246. case 167 /* IndexSignature */:
  64247. return checkSignatureDeclaration(node);
  64248. case 161 /* MethodDeclaration */:
  64249. case 160 /* MethodSignature */:
  64250. return checkMethodDeclaration(node);
  64251. case 162 /* Constructor */:
  64252. return checkConstructorDeclaration(node);
  64253. case 163 /* GetAccessor */:
  64254. case 164 /* SetAccessor */:
  64255. return checkAccessorDeclaration(node);
  64256. case 169 /* TypeReference */:
  64257. return checkTypeReferenceNode(node);
  64258. case 168 /* TypePredicate */:
  64259. return checkTypePredicate(node);
  64260. case 172 /* TypeQuery */:
  64261. return checkTypeQuery(node);
  64262. case 173 /* TypeLiteral */:
  64263. return checkTypeLiteral(node);
  64264. case 174 /* ArrayType */:
  64265. return checkArrayType(node);
  64266. case 175 /* TupleType */:
  64267. return checkTupleType(node);
  64268. case 178 /* UnionType */:
  64269. case 179 /* IntersectionType */:
  64270. return checkUnionOrIntersectionType(node);
  64271. case 182 /* ParenthesizedType */:
  64272. case 176 /* OptionalType */:
  64273. case 177 /* RestType */:
  64274. return checkSourceElement(node.type);
  64275. case 183 /* ThisType */:
  64276. return checkThisType(node);
  64277. case 184 /* TypeOperator */:
  64278. return checkTypeOperator(node);
  64279. case 180 /* ConditionalType */:
  64280. return checkConditionalType(node);
  64281. case 181 /* InferType */:
  64282. return checkInferType(node);
  64283. case 188 /* ImportType */:
  64284. return checkImportType(node);
  64285. case 307 /* JSDocAugmentsTag */:
  64286. return checkJSDocAugmentsTag(node);
  64287. case 321 /* JSDocTypedefTag */:
  64288. case 314 /* JSDocCallbackTag */:
  64289. case 315 /* JSDocEnumTag */:
  64290. return checkJSDocTypeAliasTag(node);
  64291. case 320 /* JSDocTemplateTag */:
  64292. return checkJSDocTemplateTag(node);
  64293. case 319 /* JSDocTypeTag */:
  64294. return checkJSDocTypeTag(node);
  64295. case 316 /* JSDocParameterTag */:
  64296. return checkJSDocParameterTag(node);
  64297. case 300 /* JSDocFunctionType */:
  64298. checkJSDocFunctionType(node);
  64299. // falls through
  64300. case 298 /* JSDocNonNullableType */:
  64301. case 297 /* JSDocNullableType */:
  64302. case 295 /* JSDocAllType */:
  64303. case 296 /* JSDocUnknownType */:
  64304. case 304 /* JSDocTypeLiteral */:
  64305. checkJSDocTypeIsInJsFile(node);
  64306. ts.forEachChild(node, checkSourceElement);
  64307. return;
  64308. case 301 /* JSDocVariadicType */:
  64309. checkJSDocVariadicType(node);
  64310. return;
  64311. case 294 /* JSDocTypeExpression */:
  64312. return checkSourceElement(node.type);
  64313. case 185 /* IndexedAccessType */:
  64314. return checkIndexedAccessType(node);
  64315. case 186 /* MappedType */:
  64316. return checkMappedType(node);
  64317. case 244 /* FunctionDeclaration */:
  64318. return checkFunctionDeclaration(node);
  64319. case 223 /* Block */:
  64320. case 250 /* ModuleBlock */:
  64321. return checkBlock(node);
  64322. case 225 /* VariableStatement */:
  64323. return checkVariableStatement(node);
  64324. case 226 /* ExpressionStatement */:
  64325. return checkExpressionStatement(node);
  64326. case 227 /* IfStatement */:
  64327. return checkIfStatement(node);
  64328. case 228 /* DoStatement */:
  64329. return checkDoStatement(node);
  64330. case 229 /* WhileStatement */:
  64331. return checkWhileStatement(node);
  64332. case 230 /* ForStatement */:
  64333. return checkForStatement(node);
  64334. case 231 /* ForInStatement */:
  64335. return checkForInStatement(node);
  64336. case 232 /* ForOfStatement */:
  64337. return checkForOfStatement(node);
  64338. case 233 /* ContinueStatement */:
  64339. case 234 /* BreakStatement */:
  64340. return checkBreakOrContinueStatement(node);
  64341. case 235 /* ReturnStatement */:
  64342. return checkReturnStatement(node);
  64343. case 236 /* WithStatement */:
  64344. return checkWithStatement(node);
  64345. case 237 /* SwitchStatement */:
  64346. return checkSwitchStatement(node);
  64347. case 238 /* LabeledStatement */:
  64348. return checkLabeledStatement(node);
  64349. case 239 /* ThrowStatement */:
  64350. return checkThrowStatement(node);
  64351. case 240 /* TryStatement */:
  64352. return checkTryStatement(node);
  64353. case 242 /* VariableDeclaration */:
  64354. return checkVariableDeclaration(node);
  64355. case 191 /* BindingElement */:
  64356. return checkBindingElement(node);
  64357. case 245 /* ClassDeclaration */:
  64358. return checkClassDeclaration(node);
  64359. case 246 /* InterfaceDeclaration */:
  64360. return checkInterfaceDeclaration(node);
  64361. case 247 /* TypeAliasDeclaration */:
  64362. return checkTypeAliasDeclaration(node);
  64363. case 248 /* EnumDeclaration */:
  64364. return checkEnumDeclaration(node);
  64365. case 249 /* ModuleDeclaration */:
  64366. return checkModuleDeclaration(node);
  64367. case 254 /* ImportDeclaration */:
  64368. return checkImportDeclaration(node);
  64369. case 253 /* ImportEqualsDeclaration */:
  64370. return checkImportEqualsDeclaration(node);
  64371. case 260 /* ExportDeclaration */:
  64372. return checkExportDeclaration(node);
  64373. case 259 /* ExportAssignment */:
  64374. return checkExportAssignment(node);
  64375. case 224 /* EmptyStatement */:
  64376. case 241 /* DebuggerStatement */:
  64377. checkGrammarStatementInAmbientContext(node);
  64378. return;
  64379. case 264 /* MissingDeclaration */:
  64380. return checkMissingDeclaration(node);
  64381. }
  64382. }
  64383. function checkJSDocTypeIsInJsFile(node) {
  64384. if (!ts.isInJSFile(node)) {
  64385. grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
  64386. }
  64387. }
  64388. function checkJSDocVariadicType(node) {
  64389. checkJSDocTypeIsInJsFile(node);
  64390. checkSourceElement(node.type);
  64391. // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
  64392. var parent = node.parent;
  64393. if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
  64394. if (ts.last(parent.parent.parameters) !== parent) {
  64395. error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
  64396. }
  64397. return;
  64398. }
  64399. if (!ts.isJSDocTypeExpression(parent)) {
  64400. error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
  64401. }
  64402. var paramTag = node.parent.parent;
  64403. if (!ts.isJSDocParameterTag(paramTag)) {
  64404. error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
  64405. return;
  64406. }
  64407. var param = ts.getParameterSymbolFromJSDoc(paramTag);
  64408. if (!param) {
  64409. // We will error in `checkJSDocParameterTag`.
  64410. return;
  64411. }
  64412. var host = ts.getHostSignatureFromJSDoc(paramTag);
  64413. if (!host || ts.last(host.parameters).symbol !== param) {
  64414. error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
  64415. }
  64416. }
  64417. function getTypeFromJSDocVariadicType(node) {
  64418. var type = getTypeFromTypeNode(node.type);
  64419. var parent = node.parent;
  64420. var paramTag = node.parent.parent;
  64421. if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
  64422. // Else we will add a diagnostic, see `checkJSDocVariadicType`.
  64423. var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
  64424. if (host_1) {
  64425. /*
  64426. Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
  64427. So in the following situation we will not create an array type:
  64428. /** @param {...number} a * /
  64429. function f(a) {}
  64430. Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
  64431. */
  64432. var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
  64433. var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
  64434. if (!lastParamDeclaration ||
  64435. symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
  64436. return createArrayType(type);
  64437. }
  64438. }
  64439. }
  64440. if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
  64441. return createArrayType(type);
  64442. }
  64443. return addOptionality(type);
  64444. }
  64445. // Function and class expression bodies are checked after all statements in the enclosing body. This is
  64446. // to ensure constructs like the following are permitted:
  64447. // const foo = function () {
  64448. // const s = foo();
  64449. // return "hello";
  64450. // }
  64451. // Here, performing a full type check of the body of the function expression whilst in the process of
  64452. // determining the type of foo would cause foo to be given type any because of the recursive reference.
  64453. // Delaying the type check of the body ensures foo has been assigned a type.
  64454. function checkNodeDeferred(node) {
  64455. var enclosingFile = ts.getSourceFileOfNode(node);
  64456. var links = getNodeLinks(enclosingFile);
  64457. if (!(links.flags & 1 /* TypeChecked */)) {
  64458. links.deferredNodes = links.deferredNodes || ts.createMap();
  64459. var id = "" + getNodeId(node);
  64460. links.deferredNodes.set(id, node);
  64461. }
  64462. }
  64463. function checkDeferredNodes(context) {
  64464. var links = getNodeLinks(context);
  64465. if (links.deferredNodes) {
  64466. links.deferredNodes.forEach(checkDeferredNode);
  64467. }
  64468. }
  64469. function checkDeferredNode(node) {
  64470. var saveCurrentNode = currentNode;
  64471. currentNode = node;
  64472. instantiationCount = 0;
  64473. switch (node.kind) {
  64474. case 201 /* FunctionExpression */:
  64475. case 202 /* ArrowFunction */:
  64476. case 161 /* MethodDeclaration */:
  64477. case 160 /* MethodSignature */:
  64478. checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
  64479. break;
  64480. case 163 /* GetAccessor */:
  64481. case 164 /* SetAccessor */:
  64482. checkAccessorDeclaration(node);
  64483. break;
  64484. case 214 /* ClassExpression */:
  64485. checkClassExpressionDeferred(node);
  64486. break;
  64487. case 267 /* JsxSelfClosingElement */:
  64488. checkJsxSelfClosingElementDeferred(node);
  64489. break;
  64490. case 266 /* JsxElement */:
  64491. checkJsxElementDeferred(node);
  64492. break;
  64493. }
  64494. currentNode = saveCurrentNode;
  64495. }
  64496. function checkSourceFile(node) {
  64497. ts.performance.mark("beforeCheck");
  64498. checkSourceFileWorker(node);
  64499. ts.performance.mark("afterCheck");
  64500. ts.performance.measure("Check", "beforeCheck", "afterCheck");
  64501. }
  64502. function unusedIsError(kind, isAmbient) {
  64503. if (isAmbient) {
  64504. return false;
  64505. }
  64506. switch (kind) {
  64507. case 0 /* Local */:
  64508. return !!compilerOptions.noUnusedLocals;
  64509. case 1 /* Parameter */:
  64510. return !!compilerOptions.noUnusedParameters;
  64511. default:
  64512. return ts.Debug.assertNever(kind);
  64513. }
  64514. }
  64515. function getPotentiallyUnusedIdentifiers(sourceFile) {
  64516. return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
  64517. }
  64518. // Fully type check a source file and collect the relevant diagnostics.
  64519. function checkSourceFileWorker(node) {
  64520. var links = getNodeLinks(node);
  64521. if (!(links.flags & 1 /* TypeChecked */)) {
  64522. if (ts.skipTypeChecking(node, compilerOptions, host)) {
  64523. return;
  64524. }
  64525. // Grammar checking
  64526. checkGrammarSourceFile(node);
  64527. ts.clear(potentialThisCollisions);
  64528. ts.clear(potentialNewTargetCollisions);
  64529. ts.clear(potentialWeakMapCollisions);
  64530. ts.forEach(node.statements, checkSourceElement);
  64531. checkSourceElement(node.endOfFileToken);
  64532. checkDeferredNodes(node);
  64533. if (ts.isExternalOrCommonJsModule(node)) {
  64534. registerForUnusedIdentifiersCheck(node);
  64535. }
  64536. if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
  64537. checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
  64538. if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
  64539. diagnostics.add(diag);
  64540. }
  64541. });
  64542. }
  64543. if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
  64544. !node.isDeclarationFile &&
  64545. ts.isExternalModule(node)) {
  64546. checkImportsForTypeOnlyConversion(node);
  64547. }
  64548. if (ts.isExternalOrCommonJsModule(node)) {
  64549. checkExternalModuleExports(node);
  64550. }
  64551. if (potentialThisCollisions.length) {
  64552. ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
  64553. ts.clear(potentialThisCollisions);
  64554. }
  64555. if (potentialNewTargetCollisions.length) {
  64556. ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
  64557. ts.clear(potentialNewTargetCollisions);
  64558. }
  64559. if (potentialWeakMapCollisions.length) {
  64560. ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
  64561. ts.clear(potentialWeakMapCollisions);
  64562. }
  64563. links.flags |= 1 /* TypeChecked */;
  64564. }
  64565. }
  64566. function getDiagnostics(sourceFile, ct) {
  64567. try {
  64568. // Record the cancellation token so it can be checked later on during checkSourceElement.
  64569. // Do this in a finally block so we can ensure that it gets reset back to nothing after
  64570. // this call is done.
  64571. cancellationToken = ct;
  64572. return getDiagnosticsWorker(sourceFile);
  64573. }
  64574. finally {
  64575. cancellationToken = undefined;
  64576. }
  64577. }
  64578. function getDiagnosticsWorker(sourceFile) {
  64579. throwIfNonDiagnosticsProducing();
  64580. if (sourceFile) {
  64581. // Some global diagnostics are deferred until they are needed and
  64582. // may not be reported in the first call to getGlobalDiagnostics.
  64583. // We should catch these changes and report them.
  64584. var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
  64585. var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
  64586. checkSourceFile(sourceFile);
  64587. var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
  64588. var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
  64589. if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
  64590. // If the arrays are not the same reference, new diagnostics were added.
  64591. var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
  64592. return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
  64593. }
  64594. else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
  64595. // If the arrays are the same reference, but the length has changed, a single
  64596. // new diagnostic was added as DiagnosticCollection attempts to reuse the
  64597. // same array.
  64598. return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
  64599. }
  64600. return semanticDiagnostics;
  64601. }
  64602. // Global diagnostics are always added when a file is not provided to
  64603. // getDiagnostics
  64604. ts.forEach(host.getSourceFiles(), checkSourceFile);
  64605. return diagnostics.getDiagnostics();
  64606. }
  64607. function getGlobalDiagnostics() {
  64608. throwIfNonDiagnosticsProducing();
  64609. return diagnostics.getGlobalDiagnostics();
  64610. }
  64611. function throwIfNonDiagnosticsProducing() {
  64612. if (!produceDiagnostics) {
  64613. throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
  64614. }
  64615. }
  64616. // Language service support
  64617. function getSymbolsInScope(location, meaning) {
  64618. if (location.flags & 16777216 /* InWithStatement */) {
  64619. // We cannot answer semantic questions within a with block, do not proceed any further
  64620. return [];
  64621. }
  64622. var symbols = ts.createSymbolTable();
  64623. var isStatic = false;
  64624. populateSymbols();
  64625. symbols.delete("this" /* This */); // Not a symbol, a keyword
  64626. return symbolsToArray(symbols);
  64627. function populateSymbols() {
  64628. while (location) {
  64629. if (location.locals && !isGlobalSourceFile(location)) {
  64630. copySymbols(location.locals, meaning);
  64631. }
  64632. switch (location.kind) {
  64633. case 290 /* SourceFile */:
  64634. if (!ts.isExternalOrCommonJsModule(location))
  64635. break;
  64636. // falls through
  64637. case 249 /* ModuleDeclaration */:
  64638. copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
  64639. break;
  64640. case 248 /* EnumDeclaration */:
  64641. copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
  64642. break;
  64643. case 214 /* ClassExpression */:
  64644. var className = location.name;
  64645. if (className) {
  64646. copySymbol(location.symbol, meaning);
  64647. }
  64648. // this fall-through is necessary because we would like to handle
  64649. // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
  64650. // falls through
  64651. case 245 /* ClassDeclaration */:
  64652. case 246 /* InterfaceDeclaration */:
  64653. // If we didn't come from static member of class or interface,
  64654. // add the type parameters into the symbol table
  64655. // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
  64656. // Note: that the memberFlags come from previous iteration.
  64657. if (!isStatic) {
  64658. copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
  64659. }
  64660. break;
  64661. case 201 /* FunctionExpression */:
  64662. var funcName = location.name;
  64663. if (funcName) {
  64664. copySymbol(location.symbol, meaning);
  64665. }
  64666. break;
  64667. }
  64668. if (ts.introducesArgumentsExoticObject(location)) {
  64669. copySymbol(argumentsSymbol, meaning);
  64670. }
  64671. isStatic = ts.hasModifier(location, 32 /* Static */);
  64672. location = location.parent;
  64673. }
  64674. copySymbols(globals, meaning);
  64675. }
  64676. /**
  64677. * Copy the given symbol into symbol tables if the symbol has the given meaning
  64678. * and it doesn't already existed in the symbol table
  64679. * @param key a key for storing in symbol table; if undefined, use symbol.name
  64680. * @param symbol the symbol to be added into symbol table
  64681. * @param meaning meaning of symbol to filter by before adding to symbol table
  64682. */
  64683. function copySymbol(symbol, meaning) {
  64684. if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
  64685. var id = symbol.escapedName;
  64686. // We will copy all symbol regardless of its reserved name because
  64687. // symbolsToArray will check whether the key is a reserved name and
  64688. // it will not copy symbol with reserved name to the array
  64689. if (!symbols.has(id)) {
  64690. symbols.set(id, symbol);
  64691. }
  64692. }
  64693. }
  64694. function copySymbols(source, meaning) {
  64695. if (meaning) {
  64696. source.forEach(function (symbol) {
  64697. copySymbol(symbol, meaning);
  64698. });
  64699. }
  64700. }
  64701. }
  64702. function isTypeDeclarationName(name) {
  64703. return name.kind === 75 /* Identifier */ &&
  64704. isTypeDeclaration(name.parent) &&
  64705. name.parent.name === name;
  64706. }
  64707. function isTypeDeclaration(node) {
  64708. switch (node.kind) {
  64709. case 155 /* TypeParameter */:
  64710. case 245 /* ClassDeclaration */:
  64711. case 246 /* InterfaceDeclaration */:
  64712. case 247 /* TypeAliasDeclaration */:
  64713. case 248 /* EnumDeclaration */:
  64714. return true;
  64715. case 255 /* ImportClause */:
  64716. return node.isTypeOnly;
  64717. case 258 /* ImportSpecifier */:
  64718. case 263 /* ExportSpecifier */:
  64719. return node.parent.parent.isTypeOnly;
  64720. default:
  64721. return false;
  64722. }
  64723. }
  64724. // True if the given identifier is part of a type reference
  64725. function isTypeReferenceIdentifier(node) {
  64726. while (node.parent.kind === 153 /* QualifiedName */) {
  64727. node = node.parent;
  64728. }
  64729. return node.parent.kind === 169 /* TypeReference */;
  64730. }
  64731. function isHeritageClauseElementIdentifier(node) {
  64732. while (node.parent.kind === 194 /* PropertyAccessExpression */) {
  64733. node = node.parent;
  64734. }
  64735. return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
  64736. }
  64737. function forEachEnclosingClass(node, callback) {
  64738. var result;
  64739. while (true) {
  64740. node = ts.getContainingClass(node);
  64741. if (!node)
  64742. break;
  64743. if (result = callback(node))
  64744. break;
  64745. }
  64746. return result;
  64747. }
  64748. function isNodeUsedDuringClassInitialization(node) {
  64749. return !!ts.findAncestor(node, function (element) {
  64750. if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
  64751. return true;
  64752. }
  64753. else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
  64754. return "quit";
  64755. }
  64756. return false;
  64757. });
  64758. }
  64759. function isNodeWithinClass(node, classDeclaration) {
  64760. return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
  64761. }
  64762. function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
  64763. while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
  64764. nodeOnRightSide = nodeOnRightSide.parent;
  64765. }
  64766. if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
  64767. return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
  64768. }
  64769. if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
  64770. return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
  64771. }
  64772. return undefined;
  64773. }
  64774. function isInRightSideOfImportOrExportAssignment(node) {
  64775. return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
  64776. }
  64777. function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
  64778. var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
  64779. switch (specialPropertyAssignmentKind) {
  64780. case 1 /* ExportsProperty */:
  64781. case 3 /* PrototypeProperty */:
  64782. return getSymbolOfNode(entityName.parent);
  64783. case 4 /* ThisProperty */:
  64784. case 2 /* ModuleExports */:
  64785. case 5 /* Property */:
  64786. return getSymbolOfNode(entityName.parent.parent);
  64787. }
  64788. }
  64789. function isImportTypeQualifierPart(node) {
  64790. var parent = node.parent;
  64791. while (ts.isQualifiedName(parent)) {
  64792. node = parent;
  64793. parent = parent.parent;
  64794. }
  64795. if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
  64796. return parent;
  64797. }
  64798. return undefined;
  64799. }
  64800. function getSymbolOfNameOrPropertyAccessExpression(name) {
  64801. if (ts.isDeclarationName(name)) {
  64802. return getSymbolOfNode(name.parent);
  64803. }
  64804. if (ts.isInJSFile(name) &&
  64805. name.parent.kind === 194 /* PropertyAccessExpression */ &&
  64806. name.parent === name.parent.parent.left) {
  64807. // Check if this is a special property assignment
  64808. if (!ts.isPrivateIdentifier(name)) {
  64809. var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
  64810. if (specialPropertyAssignmentSymbol) {
  64811. return specialPropertyAssignmentSymbol;
  64812. }
  64813. }
  64814. }
  64815. if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
  64816. // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
  64817. var success = resolveEntityName(name,
  64818. /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
  64819. if (success && success !== unknownSymbol) {
  64820. return success;
  64821. }
  64822. }
  64823. else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
  64824. // Since we already checked for ExportAssignment, this really could only be an Import
  64825. var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
  64826. ts.Debug.assert(importEqualsDeclaration !== undefined);
  64827. return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
  64828. }
  64829. if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
  64830. var possibleImportNode = isImportTypeQualifierPart(name);
  64831. if (possibleImportNode) {
  64832. getTypeFromTypeNode(possibleImportNode);
  64833. var sym = getNodeLinks(name).resolvedSymbol;
  64834. return sym === unknownSymbol ? undefined : sym;
  64835. }
  64836. }
  64837. while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
  64838. name = name.parent;
  64839. }
  64840. if (isHeritageClauseElementIdentifier(name)) {
  64841. var meaning = 0 /* None */;
  64842. // In an interface or class, we're definitely interested in a type.
  64843. if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
  64844. meaning = 788968 /* Type */;
  64845. // In a class 'extends' clause we are also looking for a value.
  64846. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
  64847. meaning |= 111551 /* Value */;
  64848. }
  64849. }
  64850. else {
  64851. meaning = 1920 /* Namespace */;
  64852. }
  64853. meaning |= 2097152 /* Alias */;
  64854. var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
  64855. if (entityNameSymbol) {
  64856. return entityNameSymbol;
  64857. }
  64858. }
  64859. if (name.parent.kind === 316 /* JSDocParameterTag */) {
  64860. return ts.getParameterSymbolFromJSDoc(name.parent);
  64861. }
  64862. if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 320 /* JSDocTemplateTag */) {
  64863. ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
  64864. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
  64865. return typeParameter && typeParameter.symbol;
  64866. }
  64867. if (ts.isExpressionNode(name)) {
  64868. if (ts.nodeIsMissing(name)) {
  64869. // Missing entity name.
  64870. return undefined;
  64871. }
  64872. if (name.kind === 75 /* Identifier */) {
  64873. if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
  64874. var symbol = getIntrinsicTagSymbol(name.parent);
  64875. return symbol === unknownSymbol ? undefined : symbol;
  64876. }
  64877. return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
  64878. }
  64879. else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
  64880. var links = getNodeLinks(name);
  64881. if (links.resolvedSymbol) {
  64882. return links.resolvedSymbol;
  64883. }
  64884. if (name.kind === 194 /* PropertyAccessExpression */) {
  64885. checkPropertyAccessExpression(name);
  64886. }
  64887. else {
  64888. checkQualifiedName(name);
  64889. }
  64890. return links.resolvedSymbol;
  64891. }
  64892. }
  64893. else if (isTypeReferenceIdentifier(name)) {
  64894. var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
  64895. return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
  64896. }
  64897. if (name.parent.kind === 168 /* TypePredicate */) {
  64898. return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
  64899. }
  64900. // Do we want to return undefined here?
  64901. return undefined;
  64902. }
  64903. function getSymbolAtLocation(node) {
  64904. if (node.kind === 290 /* SourceFile */) {
  64905. return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
  64906. }
  64907. var parent = node.parent;
  64908. var grandParent = parent.parent;
  64909. if (node.flags & 16777216 /* InWithStatement */) {
  64910. // We cannot answer semantic questions within a with block, do not proceed any further
  64911. return undefined;
  64912. }
  64913. if (isDeclarationNameOrImportPropertyName(node)) {
  64914. // This is a declaration, call getSymbolOfNode
  64915. var parentSymbol = getSymbolOfNode(parent);
  64916. return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
  64917. ? getImmediateAliasedSymbol(parentSymbol)
  64918. : parentSymbol;
  64919. }
  64920. else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
  64921. return getSymbolOfNode(parent.parent);
  64922. }
  64923. if (node.kind === 75 /* Identifier */) {
  64924. if (isInRightSideOfImportOrExportAssignment(node)) {
  64925. return getSymbolOfNameOrPropertyAccessExpression(node);
  64926. }
  64927. else if (parent.kind === 191 /* BindingElement */ &&
  64928. grandParent.kind === 189 /* ObjectBindingPattern */ &&
  64929. node === parent.propertyName) {
  64930. var typeOfPattern = getTypeOfNode(grandParent);
  64931. var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
  64932. if (propertyDeclaration) {
  64933. return propertyDeclaration;
  64934. }
  64935. }
  64936. }
  64937. switch (node.kind) {
  64938. case 75 /* Identifier */:
  64939. case 76 /* PrivateIdentifier */:
  64940. case 194 /* PropertyAccessExpression */:
  64941. case 153 /* QualifiedName */:
  64942. return getSymbolOfNameOrPropertyAccessExpression(node);
  64943. case 104 /* ThisKeyword */:
  64944. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
  64945. if (ts.isFunctionLike(container)) {
  64946. var sig = getSignatureFromDeclaration(container);
  64947. if (sig.thisParameter) {
  64948. return sig.thisParameter;
  64949. }
  64950. }
  64951. if (ts.isInExpressionContext(node)) {
  64952. return checkExpression(node).symbol;
  64953. }
  64954. // falls through
  64955. case 183 /* ThisType */:
  64956. return getTypeFromThisTypeNode(node).symbol;
  64957. case 102 /* SuperKeyword */:
  64958. return checkExpression(node).symbol;
  64959. case 129 /* ConstructorKeyword */:
  64960. // constructor keyword for an overload, should take us to the definition if it exist
  64961. var constructorDeclaration = node.parent;
  64962. if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
  64963. return constructorDeclaration.parent.symbol;
  64964. }
  64965. return undefined;
  64966. case 10 /* StringLiteral */:
  64967. case 14 /* NoSubstitutionTemplateLiteral */:
  64968. // 1). import x = require("./mo/*gotToDefinitionHere*/d")
  64969. // 2). External module name in an import declaration
  64970. // 3). Dynamic import call or require in javascript
  64971. // 4). type A = import("./f/*gotToDefinitionHere*/oo")
  64972. if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
  64973. ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
  64974. ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
  64975. (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
  64976. return resolveExternalModuleName(node, node);
  64977. }
  64978. if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
  64979. return getSymbolOfNode(parent);
  64980. }
  64981. // falls through
  64982. case 8 /* NumericLiteral */:
  64983. // index access
  64984. var objectType = ts.isElementAccessExpression(parent)
  64985. ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
  64986. : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
  64987. ? getTypeFromTypeNode(grandParent.objectType)
  64988. : undefined;
  64989. return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
  64990. case 84 /* DefaultKeyword */:
  64991. case 94 /* FunctionKeyword */:
  64992. case 38 /* EqualsGreaterThanToken */:
  64993. case 80 /* ClassKeyword */:
  64994. return getSymbolOfNode(node.parent);
  64995. case 188 /* ImportType */:
  64996. return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined;
  64997. case 89 /* ExportKeyword */:
  64998. return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined;
  64999. default:
  65000. return undefined;
  65001. }
  65002. }
  65003. function getShorthandAssignmentValueSymbol(location) {
  65004. if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
  65005. return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
  65006. }
  65007. return undefined;
  65008. }
  65009. /** Returns the target of an export specifier without following aliases */
  65010. function getExportSpecifierLocalTargetSymbol(node) {
  65011. return node.parent.parent.moduleSpecifier ?
  65012. getExternalModuleMember(node.parent.parent, node) :
  65013. resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
  65014. }
  65015. function getTypeOfNode(node) {
  65016. if (node.flags & 16777216 /* InWithStatement */) {
  65017. // We cannot answer semantic questions within a with block, do not proceed any further
  65018. return errorType;
  65019. }
  65020. var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
  65021. var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
  65022. if (ts.isPartOfTypeNode(node)) {
  65023. var typeFromTypeNode = getTypeFromTypeNode(node);
  65024. return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
  65025. }
  65026. if (ts.isExpressionNode(node)) {
  65027. return getRegularTypeOfExpression(node);
  65028. }
  65029. if (classType && !classDecl.isImplements) {
  65030. // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
  65031. // extends clause of a class. We handle that case here.
  65032. var baseType = ts.firstOrUndefined(getBaseTypes(classType));
  65033. return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
  65034. }
  65035. if (isTypeDeclaration(node)) {
  65036. // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
  65037. var symbol = getSymbolOfNode(node);
  65038. return getDeclaredTypeOfSymbol(symbol);
  65039. }
  65040. if (isTypeDeclarationName(node)) {
  65041. var symbol = getSymbolAtLocation(node);
  65042. return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
  65043. }
  65044. if (ts.isDeclaration(node)) {
  65045. // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
  65046. var symbol = getSymbolOfNode(node);
  65047. return getTypeOfSymbol(symbol);
  65048. }
  65049. if (isDeclarationNameOrImportPropertyName(node)) {
  65050. var symbol = getSymbolAtLocation(node);
  65051. if (symbol) {
  65052. return getTypeOfSymbol(symbol);
  65053. }
  65054. return errorType;
  65055. }
  65056. if (ts.isBindingPattern(node)) {
  65057. return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
  65058. }
  65059. if (isInRightSideOfImportOrExportAssignment(node)) {
  65060. var symbol = getSymbolAtLocation(node);
  65061. if (symbol) {
  65062. var declaredType = getDeclaredTypeOfSymbol(symbol);
  65063. return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
  65064. }
  65065. }
  65066. return errorType;
  65067. }
  65068. // Gets the type of object literal or array literal of destructuring assignment.
  65069. // { a } from
  65070. // for ( { a } of elems) {
  65071. // }
  65072. // [ a ] from
  65073. // [a] = [ some array ...]
  65074. function getTypeOfAssignmentPattern(expr) {
  65075. ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
  65076. // If this is from "for of"
  65077. // for ( { a } of elems) {
  65078. // }
  65079. if (expr.parent.kind === 232 /* ForOfStatement */) {
  65080. var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier);
  65081. return checkDestructuringAssignment(expr, iteratedType || errorType);
  65082. }
  65083. // If this is from "for" initializer
  65084. // for ({a } = elems[0];.....) { }
  65085. if (expr.parent.kind === 209 /* BinaryExpression */) {
  65086. var iteratedType = getTypeOfExpression(expr.parent.right);
  65087. return checkDestructuringAssignment(expr, iteratedType || errorType);
  65088. }
  65089. // If this is from nested object binding pattern
  65090. // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
  65091. if (expr.parent.kind === 281 /* PropertyAssignment */) {
  65092. var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
  65093. var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
  65094. var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
  65095. return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
  65096. }
  65097. // Array literal assignment - array destructuring pattern
  65098. var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
  65099. // [{ property1: p1, property2 }] = elems;
  65100. var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
  65101. var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
  65102. return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
  65103. }
  65104. // Gets the property symbol corresponding to the property in destructuring assignment
  65105. // 'property1' from
  65106. // for ( { property1: a } of elems) {
  65107. // }
  65108. // 'property1' at location 'a' from:
  65109. // [a] = [ property1, property2 ]
  65110. function getPropertySymbolOfDestructuringAssignment(location) {
  65111. // Get the type of the object or array literal and then look for property of given name in the type
  65112. var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
  65113. return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
  65114. }
  65115. function getRegularTypeOfExpression(expr) {
  65116. if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
  65117. expr = expr.parent;
  65118. }
  65119. return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
  65120. }
  65121. /**
  65122. * Gets either the static or instance type of a class element, based on
  65123. * whether the element is declared as "static".
  65124. */
  65125. function getParentTypeOfClassElement(node) {
  65126. var classSymbol = getSymbolOfNode(node.parent);
  65127. return ts.hasModifier(node, 32 /* Static */)
  65128. ? getTypeOfSymbol(classSymbol)
  65129. : getDeclaredTypeOfSymbol(classSymbol);
  65130. }
  65131. function getClassElementPropertyKeyType(element) {
  65132. var name = element.name;
  65133. switch (name.kind) {
  65134. case 75 /* Identifier */:
  65135. return getLiteralType(ts.idText(name));
  65136. case 8 /* NumericLiteral */:
  65137. case 10 /* StringLiteral */:
  65138. return getLiteralType(name.text);
  65139. case 154 /* ComputedPropertyName */:
  65140. var nameType = checkComputedPropertyName(name);
  65141. return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
  65142. default:
  65143. return ts.Debug.fail("Unsupported property name.");
  65144. }
  65145. }
  65146. // Return the list of properties of the given type, augmented with properties from Function
  65147. // if the type has call or construct signatures
  65148. function getAugmentedPropertiesOfType(type) {
  65149. type = getApparentType(type);
  65150. var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
  65151. var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
  65152. getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
  65153. undefined;
  65154. if (functionType) {
  65155. ts.forEach(getPropertiesOfType(functionType), function (p) {
  65156. if (!propsByName.has(p.escapedName)) {
  65157. propsByName.set(p.escapedName, p);
  65158. }
  65159. });
  65160. }
  65161. return getNamedMembers(propsByName);
  65162. }
  65163. function typeHasCallOrConstructSignatures(type) {
  65164. return ts.typeHasCallOrConstructSignatures(type, checker);
  65165. }
  65166. function getRootSymbols(symbol) {
  65167. var roots = getImmediateRootSymbols(symbol);
  65168. return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
  65169. }
  65170. function getImmediateRootSymbols(symbol) {
  65171. if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
  65172. return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
  65173. }
  65174. else if (symbol.flags & 33554432 /* Transient */) {
  65175. var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
  65176. return leftSpread ? [leftSpread, rightSpread]
  65177. : syntheticOrigin ? [syntheticOrigin]
  65178. : ts.singleElementArray(tryGetAliasTarget(symbol));
  65179. }
  65180. return undefined;
  65181. }
  65182. function tryGetAliasTarget(symbol) {
  65183. var target;
  65184. var next = symbol;
  65185. while (next = getSymbolLinks(next).target) {
  65186. target = next;
  65187. }
  65188. return target;
  65189. }
  65190. // Emitter support
  65191. function isArgumentsLocalBinding(nodeIn) {
  65192. if (!ts.isGeneratedIdentifier(nodeIn)) {
  65193. var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
  65194. if (node) {
  65195. var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
  65196. return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
  65197. }
  65198. }
  65199. return false;
  65200. }
  65201. function moduleExportsSomeValue(moduleReferenceExpression) {
  65202. var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
  65203. if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
  65204. // If the module is not found or is shorthand, assume that it may export a value.
  65205. return true;
  65206. }
  65207. var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
  65208. // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
  65209. // otherwise it will return moduleSymbol itself
  65210. moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
  65211. var symbolLinks = getSymbolLinks(moduleSymbol);
  65212. if (symbolLinks.exportsSomeValue === undefined) {
  65213. // for export assignments - check if resolved symbol for RHS is itself a value
  65214. // otherwise - check if at least one export is value
  65215. symbolLinks.exportsSomeValue = hasExportAssignment
  65216. ? !!(moduleSymbol.flags & 111551 /* Value */)
  65217. : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
  65218. }
  65219. return symbolLinks.exportsSomeValue;
  65220. function isValue(s) {
  65221. s = resolveSymbol(s);
  65222. return s && !!(s.flags & 111551 /* Value */);
  65223. }
  65224. }
  65225. function isNameOfModuleOrEnumDeclaration(node) {
  65226. return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
  65227. }
  65228. // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
  65229. // node of the exported entity's container. Otherwise, return undefined.
  65230. function getReferencedExportContainer(nodeIn, prefixLocals) {
  65231. var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
  65232. if (node) {
  65233. // When resolving the export container for the name of a module or enum
  65234. // declaration, we need to start resolution at the declaration's container.
  65235. // Otherwise, we could incorrectly resolve the export container as the
  65236. // declaration if it contains an exported member with the same name.
  65237. var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
  65238. if (symbol) {
  65239. if (symbol.flags & 1048576 /* ExportValue */) {
  65240. // If we reference an exported entity within the same module declaration, then whether
  65241. // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
  65242. // kinds that we do NOT prefix.
  65243. var exportSymbol = getMergedSymbol(symbol.exportSymbol);
  65244. if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
  65245. return undefined;
  65246. }
  65247. symbol = exportSymbol;
  65248. }
  65249. var parentSymbol_1 = getParentOfSymbol(symbol);
  65250. if (parentSymbol_1) {
  65251. if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
  65252. var symbolFile = parentSymbol_1.valueDeclaration;
  65253. var referenceFile = ts.getSourceFileOfNode(node);
  65254. // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
  65255. var symbolIsUmdExport = symbolFile !== referenceFile;
  65256. return symbolIsUmdExport ? undefined : symbolFile;
  65257. }
  65258. return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
  65259. }
  65260. }
  65261. }
  65262. }
  65263. // When resolved as an expression identifier, if the given node references an import, return the declaration of
  65264. // that import. Otherwise, return undefined.
  65265. function getReferencedImportDeclaration(nodeIn) {
  65266. var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
  65267. if (node) {
  65268. var symbol = getReferencedValueSymbol(node);
  65269. // We should only get the declaration of an alias if there isn't a local value
  65270. // declaration for the symbol
  65271. if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
  65272. return getDeclarationOfAliasSymbol(symbol);
  65273. }
  65274. }
  65275. return undefined;
  65276. }
  65277. function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
  65278. return ts.isBindingElement(symbol.valueDeclaration)
  65279. && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
  65280. }
  65281. function isSymbolOfDeclarationWithCollidingName(symbol) {
  65282. if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
  65283. var links = getSymbolLinks(symbol);
  65284. if (links.isDeclarationWithCollidingName === undefined) {
  65285. var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
  65286. if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
  65287. var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
  65288. if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
  65289. // redeclaration - always should be renamed
  65290. links.isDeclarationWithCollidingName = true;
  65291. }
  65292. else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
  65293. // binding is captured in the function
  65294. // should be renamed if:
  65295. // - binding is not top level - top level bindings never collide with anything
  65296. // AND
  65297. // - binding is not declared in loop, should be renamed to avoid name reuse across siblings
  65298. // let a, b
  65299. // { let x = 1; a = () => x; }
  65300. // { let x = 100; b = () => x; }
  65301. // console.log(a()); // should print '1'
  65302. // console.log(b()); // should print '100'
  65303. // OR
  65304. // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
  65305. // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
  65306. // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
  65307. // they will not collide with anything
  65308. var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
  65309. var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
  65310. var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
  65311. links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
  65312. }
  65313. else {
  65314. links.isDeclarationWithCollidingName = false;
  65315. }
  65316. }
  65317. }
  65318. return links.isDeclarationWithCollidingName;
  65319. }
  65320. return false;
  65321. }
  65322. // When resolved as an expression identifier, if the given node references a nested block scoped entity with
  65323. // a name that either hides an existing name or might hide it when compiled downlevel,
  65324. // return the declaration of that entity. Otherwise, return undefined.
  65325. function getReferencedDeclarationWithCollidingName(nodeIn) {
  65326. if (!ts.isGeneratedIdentifier(nodeIn)) {
  65327. var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
  65328. if (node) {
  65329. var symbol = getReferencedValueSymbol(node);
  65330. if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
  65331. return symbol.valueDeclaration;
  65332. }
  65333. }
  65334. }
  65335. return undefined;
  65336. }
  65337. // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
  65338. // existing name or might hide a name when compiled downlevel
  65339. function isDeclarationWithCollidingName(nodeIn) {
  65340. var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
  65341. if (node) {
  65342. var symbol = getSymbolOfNode(node);
  65343. if (symbol) {
  65344. return isSymbolOfDeclarationWithCollidingName(symbol);
  65345. }
  65346. }
  65347. return false;
  65348. }
  65349. function isValueAliasDeclaration(node) {
  65350. switch (node.kind) {
  65351. case 253 /* ImportEqualsDeclaration */:
  65352. return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
  65353. case 255 /* ImportClause */:
  65354. case 256 /* NamespaceImport */:
  65355. case 258 /* ImportSpecifier */:
  65356. case 263 /* ExportSpecifier */:
  65357. var symbol = getSymbolOfNode(node) || unknownSymbol;
  65358. return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
  65359. case 260 /* ExportDeclaration */:
  65360. var exportClause = node.exportClause;
  65361. return !!exportClause && (ts.isNamespaceExport(exportClause) ||
  65362. ts.some(exportClause.elements, isValueAliasDeclaration));
  65363. case 259 /* ExportAssignment */:
  65364. return node.expression && node.expression.kind === 75 /* Identifier */ ?
  65365. isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
  65366. true;
  65367. }
  65368. return false;
  65369. }
  65370. function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
  65371. var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
  65372. if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
  65373. // parent is not source file or it is not reference to internal module
  65374. return false;
  65375. }
  65376. var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
  65377. return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
  65378. }
  65379. function isAliasResolvedToValue(symbol) {
  65380. var target = resolveAlias(symbol);
  65381. if (target === unknownSymbol) {
  65382. return true;
  65383. }
  65384. // const enums and modules that contain only const enums are not considered values from the emit perspective
  65385. // unless 'preserveConstEnums' option is set to true
  65386. return !!(target.flags & 111551 /* Value */) &&
  65387. (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
  65388. }
  65389. function isConstEnumOrConstEnumOnlyModule(s) {
  65390. return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
  65391. }
  65392. function isReferencedAliasDeclaration(node, checkChildren) {
  65393. if (isAliasSymbolDeclaration(node)) {
  65394. var symbol = getSymbolOfNode(node);
  65395. if (symbol && getSymbolLinks(symbol).referenced) {
  65396. return true;
  65397. }
  65398. var target = getSymbolLinks(symbol).target; // TODO: GH#18217
  65399. if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
  65400. target.flags & 111551 /* Value */ &&
  65401. (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
  65402. // An `export import ... =` of a value symbol is always considered referenced
  65403. return true;
  65404. }
  65405. }
  65406. if (checkChildren) {
  65407. return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
  65408. }
  65409. return false;
  65410. }
  65411. function isImplementationOfOverload(node) {
  65412. if (ts.nodeIsPresent(node.body)) {
  65413. if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
  65414. return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
  65415. var symbol = getSymbolOfNode(node);
  65416. var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
  65417. // If this function body corresponds to function with multiple signature, it is implementation of overload
  65418. // e.g.: function foo(a: string): string;
  65419. // function foo(a: number): number;
  65420. // function foo(a: any) { // This is implementation of the overloads
  65421. // return a;
  65422. // }
  65423. return signaturesOfSymbol.length > 1 ||
  65424. // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
  65425. // e.g.: function foo(a: string): string;
  65426. // function foo(a: any) { // This is implementation of the overloads
  65427. // return a;
  65428. // }
  65429. (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
  65430. }
  65431. return false;
  65432. }
  65433. function isRequiredInitializedParameter(parameter) {
  65434. return !!strictNullChecks &&
  65435. !isOptionalParameter(parameter) &&
  65436. !ts.isJSDocParameterTag(parameter) &&
  65437. !!parameter.initializer &&
  65438. !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
  65439. }
  65440. function isOptionalUninitializedParameterProperty(parameter) {
  65441. return strictNullChecks &&
  65442. isOptionalParameter(parameter) &&
  65443. !parameter.initializer &&
  65444. ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
  65445. }
  65446. function isExpandoFunctionDeclaration(node) {
  65447. var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
  65448. if (!declaration) {
  65449. return false;
  65450. }
  65451. var symbol = getSymbolOfNode(declaration);
  65452. if (!symbol || !(symbol.flags & 16 /* Function */)) {
  65453. return false;
  65454. }
  65455. return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
  65456. }
  65457. function getPropertiesOfContainerFunction(node) {
  65458. var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
  65459. if (!declaration) {
  65460. return ts.emptyArray;
  65461. }
  65462. var symbol = getSymbolOfNode(declaration);
  65463. return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
  65464. }
  65465. function getNodeCheckFlags(node) {
  65466. return getNodeLinks(node).flags || 0;
  65467. }
  65468. function getEnumMemberValue(node) {
  65469. computeEnumMemberValues(node.parent);
  65470. return getNodeLinks(node).enumMemberValue;
  65471. }
  65472. function canHaveConstantValue(node) {
  65473. switch (node.kind) {
  65474. case 284 /* EnumMember */:
  65475. case 194 /* PropertyAccessExpression */:
  65476. case 195 /* ElementAccessExpression */:
  65477. return true;
  65478. }
  65479. return false;
  65480. }
  65481. function getConstantValue(node) {
  65482. if (node.kind === 284 /* EnumMember */) {
  65483. return getEnumMemberValue(node);
  65484. }
  65485. var symbol = getNodeLinks(node).resolvedSymbol;
  65486. if (symbol && (symbol.flags & 8 /* EnumMember */)) {
  65487. // inline property\index accesses only for const enums
  65488. var member = symbol.valueDeclaration;
  65489. if (ts.isEnumConst(member.parent)) {
  65490. return getEnumMemberValue(member);
  65491. }
  65492. }
  65493. return undefined;
  65494. }
  65495. function isFunctionType(type) {
  65496. return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
  65497. }
  65498. function getTypeReferenceSerializationKind(typeNameIn, location) {
  65499. // ensure both `typeName` and `location` are parse tree nodes.
  65500. var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
  65501. if (!typeName)
  65502. return ts.TypeReferenceSerializationKind.Unknown;
  65503. if (location) {
  65504. location = ts.getParseTreeNode(location);
  65505. if (!location)
  65506. return ts.TypeReferenceSerializationKind.Unknown;
  65507. }
  65508. // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
  65509. var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
  65510. // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
  65511. var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
  65512. if (valueSymbol && valueSymbol === typeSymbol) {
  65513. var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
  65514. if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
  65515. return ts.TypeReferenceSerializationKind.Promise;
  65516. }
  65517. var constructorType = getTypeOfSymbol(valueSymbol);
  65518. if (constructorType && isConstructorType(constructorType)) {
  65519. return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
  65520. }
  65521. }
  65522. // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
  65523. if (!typeSymbol) {
  65524. return ts.TypeReferenceSerializationKind.Unknown;
  65525. }
  65526. var type = getDeclaredTypeOfSymbol(typeSymbol);
  65527. if (type === errorType) {
  65528. return ts.TypeReferenceSerializationKind.Unknown;
  65529. }
  65530. else if (type.flags & 3 /* AnyOrUnknown */) {
  65531. return ts.TypeReferenceSerializationKind.ObjectType;
  65532. }
  65533. else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
  65534. return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
  65535. }
  65536. else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
  65537. return ts.TypeReferenceSerializationKind.BooleanType;
  65538. }
  65539. else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
  65540. return ts.TypeReferenceSerializationKind.NumberLikeType;
  65541. }
  65542. else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
  65543. return ts.TypeReferenceSerializationKind.BigIntLikeType;
  65544. }
  65545. else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
  65546. return ts.TypeReferenceSerializationKind.StringLikeType;
  65547. }
  65548. else if (isTupleType(type)) {
  65549. return ts.TypeReferenceSerializationKind.ArrayLikeType;
  65550. }
  65551. else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
  65552. return ts.TypeReferenceSerializationKind.ESSymbolType;
  65553. }
  65554. else if (isFunctionType(type)) {
  65555. return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
  65556. }
  65557. else if (isArrayType(type)) {
  65558. return ts.TypeReferenceSerializationKind.ArrayLikeType;
  65559. }
  65560. else {
  65561. return ts.TypeReferenceSerializationKind.ObjectType;
  65562. }
  65563. }
  65564. function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
  65565. var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
  65566. if (!declaration) {
  65567. return ts.createToken(125 /* AnyKeyword */);
  65568. }
  65569. // Get type of the symbol if this is the valid symbol otherwise get type at location
  65570. var symbol = getSymbolOfNode(declaration);
  65571. var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
  65572. ? getWidenedLiteralType(getTypeOfSymbol(symbol))
  65573. : errorType;
  65574. if (type.flags & 8192 /* UniqueESSymbol */ &&
  65575. type.symbol === symbol) {
  65576. flags |= 1048576 /* AllowUniqueESSymbolType */;
  65577. }
  65578. if (addUndefined) {
  65579. type = getOptionalType(type);
  65580. }
  65581. return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
  65582. }
  65583. function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
  65584. var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
  65585. if (!signatureDeclaration) {
  65586. return ts.createToken(125 /* AnyKeyword */);
  65587. }
  65588. var signature = getSignatureFromDeclaration(signatureDeclaration);
  65589. return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
  65590. }
  65591. function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
  65592. var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
  65593. if (!expr) {
  65594. return ts.createToken(125 /* AnyKeyword */);
  65595. }
  65596. var type = getWidenedType(getRegularTypeOfExpression(expr));
  65597. return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
  65598. }
  65599. function hasGlobalName(name) {
  65600. return globals.has(ts.escapeLeadingUnderscores(name));
  65601. }
  65602. function getReferencedValueSymbol(reference, startInDeclarationContainer) {
  65603. var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
  65604. if (resolvedSymbol) {
  65605. return resolvedSymbol;
  65606. }
  65607. var location = reference;
  65608. if (startInDeclarationContainer) {
  65609. // When resolving the name of a declaration as a value, we need to start resolution
  65610. // at a point outside of the declaration.
  65611. var parent = reference.parent;
  65612. if (ts.isDeclaration(parent) && reference === parent.name) {
  65613. location = getDeclarationContainer(parent);
  65614. }
  65615. }
  65616. return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
  65617. }
  65618. function getReferencedValueDeclaration(referenceIn) {
  65619. if (!ts.isGeneratedIdentifier(referenceIn)) {
  65620. var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
  65621. if (reference) {
  65622. var symbol = getReferencedValueSymbol(reference);
  65623. if (symbol) {
  65624. return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
  65625. }
  65626. }
  65627. }
  65628. return undefined;
  65629. }
  65630. function isLiteralConstDeclaration(node) {
  65631. if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
  65632. return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
  65633. }
  65634. return false;
  65635. }
  65636. function literalTypeToNode(type, enclosing, tracker) {
  65637. var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
  65638. : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
  65639. return enumResult || ts.createLiteral(type.value);
  65640. }
  65641. function createLiteralConstValue(node, tracker) {
  65642. var type = getTypeOfSymbol(getSymbolOfNode(node));
  65643. return literalTypeToNode(type, node, tracker);
  65644. }
  65645. function createResolver() {
  65646. // this variable and functions that use it are deliberately moved here from the outer scope
  65647. // to avoid scope pollution
  65648. var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
  65649. var fileToDirective;
  65650. if (resolvedTypeReferenceDirectives) {
  65651. // populate reverse mapping: file path -> type reference directive that was resolved to this file
  65652. fileToDirective = ts.createMap();
  65653. resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
  65654. if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
  65655. return;
  65656. }
  65657. var file = host.getSourceFile(resolvedDirective.resolvedFileName);
  65658. // Add the transitive closure of path references loaded by this file (as long as they are not)
  65659. // part of an existing type reference.
  65660. addReferencedFilesToTypeDirective(file, key);
  65661. });
  65662. }
  65663. return {
  65664. getReferencedExportContainer: getReferencedExportContainer,
  65665. getReferencedImportDeclaration: getReferencedImportDeclaration,
  65666. getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
  65667. isDeclarationWithCollidingName: isDeclarationWithCollidingName,
  65668. isValueAliasDeclaration: function (node) {
  65669. node = ts.getParseTreeNode(node);
  65670. // Synthesized nodes are always treated like values.
  65671. return node ? isValueAliasDeclaration(node) : true;
  65672. },
  65673. hasGlobalName: hasGlobalName,
  65674. isReferencedAliasDeclaration: function (node, checkChildren) {
  65675. node = ts.getParseTreeNode(node);
  65676. // Synthesized nodes are always treated as referenced.
  65677. return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
  65678. },
  65679. getNodeCheckFlags: function (node) {
  65680. node = ts.getParseTreeNode(node);
  65681. return node ? getNodeCheckFlags(node) : 0;
  65682. },
  65683. isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
  65684. isDeclarationVisible: isDeclarationVisible,
  65685. isImplementationOfOverload: isImplementationOfOverload,
  65686. isRequiredInitializedParameter: isRequiredInitializedParameter,
  65687. isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
  65688. isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
  65689. getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
  65690. createTypeOfDeclaration: createTypeOfDeclaration,
  65691. createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
  65692. createTypeOfExpression: createTypeOfExpression,
  65693. createLiteralConstValue: createLiteralConstValue,
  65694. isSymbolAccessible: isSymbolAccessible,
  65695. isEntityNameVisible: isEntityNameVisible,
  65696. getConstantValue: function (nodeIn) {
  65697. var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
  65698. return node ? getConstantValue(node) : undefined;
  65699. },
  65700. collectLinkedAliases: collectLinkedAliases,
  65701. getReferencedValueDeclaration: getReferencedValueDeclaration,
  65702. getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
  65703. isOptionalParameter: isOptionalParameter,
  65704. moduleExportsSomeValue: moduleExportsSomeValue,
  65705. isArgumentsLocalBinding: isArgumentsLocalBinding,
  65706. getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
  65707. getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
  65708. getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
  65709. isLiteralConstDeclaration: isLiteralConstDeclaration,
  65710. isLateBound: function (nodeIn) {
  65711. var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
  65712. var symbol = node && getSymbolOfNode(node);
  65713. return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
  65714. },
  65715. getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
  65716. getAllAccessorDeclarations: function (accessor) {
  65717. accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
  65718. var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
  65719. var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
  65720. var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
  65721. var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
  65722. var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
  65723. var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
  65724. return {
  65725. firstAccessor: firstAccessor,
  65726. secondAccessor: secondAccessor,
  65727. setAccessor: setAccessor,
  65728. getAccessor: getAccessor
  65729. };
  65730. },
  65731. getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
  65732. isBindingCapturedByNode: function (node, decl) {
  65733. var parseNode = ts.getParseTreeNode(node);
  65734. var parseDecl = ts.getParseTreeNode(decl);
  65735. return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
  65736. },
  65737. getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
  65738. var n = ts.getParseTreeNode(node);
  65739. ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
  65740. var sym = getSymbolOfNode(node);
  65741. if (!sym) {
  65742. return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
  65743. }
  65744. return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
  65745. }
  65746. };
  65747. function isInHeritageClause(node) {
  65748. return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
  65749. }
  65750. // defined here to avoid outer scope pollution
  65751. function getTypeReferenceDirectivesForEntityName(node) {
  65752. // program does not have any files with type reference directives - bail out
  65753. if (!fileToDirective) {
  65754. return undefined;
  65755. }
  65756. // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
  65757. // qualified names can only be used as types\namespaces
  65758. // identifiers are treated as values only if they appear in type queries
  65759. var meaning = 788968 /* Type */ | 1920 /* Namespace */;
  65760. if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
  65761. meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
  65762. }
  65763. var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
  65764. return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
  65765. }
  65766. // defined here to avoid outer scope pollution
  65767. function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
  65768. // program does not have any files with type reference directives - bail out
  65769. if (!fileToDirective) {
  65770. return undefined;
  65771. }
  65772. if (!isSymbolFromTypeDeclarationFile(symbol)) {
  65773. return undefined;
  65774. }
  65775. // check what declarations in the symbol can contribute to the target meaning
  65776. var typeReferenceDirectives;
  65777. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  65778. var decl = _a[_i];
  65779. // check meaning of the local symbol to see if declaration needs to be analyzed further
  65780. if (decl.symbol && decl.symbol.flags & meaning) {
  65781. var file = ts.getSourceFileOfNode(decl);
  65782. var typeReferenceDirective = fileToDirective.get(file.path);
  65783. if (typeReferenceDirective) {
  65784. (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
  65785. }
  65786. else {
  65787. // found at least one entry that does not originate from type reference directive
  65788. return undefined;
  65789. }
  65790. }
  65791. }
  65792. return typeReferenceDirectives;
  65793. }
  65794. function isSymbolFromTypeDeclarationFile(symbol) {
  65795. // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
  65796. if (!symbol.declarations) {
  65797. return false;
  65798. }
  65799. // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
  65800. // external modules cannot define or contribute to type declaration files
  65801. var current = symbol;
  65802. while (true) {
  65803. var parent = getParentOfSymbol(current);
  65804. if (parent) {
  65805. current = parent;
  65806. }
  65807. else {
  65808. break;
  65809. }
  65810. }
  65811. if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
  65812. return false;
  65813. }
  65814. // check that at least one declaration of top level symbol originates from type declaration file
  65815. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  65816. var decl = _a[_i];
  65817. var file = ts.getSourceFileOfNode(decl);
  65818. if (fileToDirective.has(file.path)) {
  65819. return true;
  65820. }
  65821. }
  65822. return false;
  65823. }
  65824. function addReferencedFilesToTypeDirective(file, key) {
  65825. if (fileToDirective.has(file.path))
  65826. return;
  65827. fileToDirective.set(file.path, key);
  65828. for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
  65829. var fileName = _a[_i].fileName;
  65830. var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
  65831. var referencedFile = host.getSourceFile(resolvedFile);
  65832. if (referencedFile) {
  65833. addReferencedFilesToTypeDirective(referencedFile, key);
  65834. }
  65835. }
  65836. }
  65837. }
  65838. function getExternalModuleFileFromDeclaration(declaration) {
  65839. var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
  65840. var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
  65841. if (!moduleSymbol) {
  65842. return undefined;
  65843. }
  65844. return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
  65845. }
  65846. function initializeTypeChecker() {
  65847. // Bind all source files and propagate errors
  65848. for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
  65849. var file = _a[_i];
  65850. ts.bindSourceFile(file, compilerOptions);
  65851. }
  65852. amalgamatedDuplicates = ts.createMap();
  65853. // Initialize global symbol table
  65854. var augmentations;
  65855. for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
  65856. var file = _c[_b];
  65857. if (file.redirectInfo) {
  65858. continue;
  65859. }
  65860. if (!ts.isExternalOrCommonJsModule(file)) {
  65861. // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
  65862. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
  65863. var fileGlobalThisSymbol = file.locals.get("globalThis");
  65864. if (fileGlobalThisSymbol) {
  65865. for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
  65866. var declaration = _e[_d];
  65867. diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
  65868. }
  65869. }
  65870. mergeSymbolTable(globals, file.locals);
  65871. }
  65872. if (file.jsGlobalAugmentations) {
  65873. mergeSymbolTable(globals, file.jsGlobalAugmentations);
  65874. }
  65875. if (file.patternAmbientModules && file.patternAmbientModules.length) {
  65876. patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
  65877. }
  65878. if (file.moduleAugmentations.length) {
  65879. (augmentations || (augmentations = [])).push(file.moduleAugmentations);
  65880. }
  65881. if (file.symbol && file.symbol.globalExports) {
  65882. // Merge in UMD exports with first-in-wins semantics (see #9771)
  65883. var source = file.symbol.globalExports;
  65884. source.forEach(function (sourceSymbol, id) {
  65885. if (!globals.has(id)) {
  65886. globals.set(id, sourceSymbol);
  65887. }
  65888. });
  65889. }
  65890. }
  65891. // We do global augmentations separately from module augmentations (and before creating global types) because they
  65892. // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
  65893. // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
  65894. // checking for an export or property on the module (if export=) which, in turn, can fall back to the
  65895. // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
  65896. // did module augmentations prior to finalizing the global types.
  65897. if (augmentations) {
  65898. // merge _global_ module augmentations.
  65899. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
  65900. for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
  65901. var list = augmentations_1[_f];
  65902. for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
  65903. var augmentation = list_1[_g];
  65904. if (!ts.isGlobalScopeAugmentation(augmentation.parent))
  65905. continue;
  65906. mergeModuleAugmentation(augmentation);
  65907. }
  65908. }
  65909. }
  65910. // Setup global builtins
  65911. addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
  65912. getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
  65913. getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
  65914. getSymbolLinks(unknownSymbol).type = errorType;
  65915. getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
  65916. // Initialize special types
  65917. globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
  65918. globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
  65919. globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
  65920. globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
  65921. globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
  65922. globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
  65923. globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
  65924. globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
  65925. globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
  65926. anyArrayType = createArrayType(anyType);
  65927. autoArrayType = createArrayType(autoType);
  65928. if (autoArrayType === emptyObjectType) {
  65929. // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
  65930. autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
  65931. }
  65932. globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
  65933. anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
  65934. globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
  65935. if (augmentations) {
  65936. // merge _nonglobal_ module augmentations.
  65937. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
  65938. for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
  65939. var list = augmentations_2[_h];
  65940. for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
  65941. var augmentation = list_2[_j];
  65942. if (ts.isGlobalScopeAugmentation(augmentation.parent))
  65943. continue;
  65944. mergeModuleAugmentation(augmentation);
  65945. }
  65946. }
  65947. }
  65948. amalgamatedDuplicates.forEach(function (_a) {
  65949. var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
  65950. // If not many things conflict, issue individual errors
  65951. if (conflictingSymbols.size < 8) {
  65952. conflictingSymbols.forEach(function (_a, symbolName) {
  65953. var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
  65954. var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
  65955. for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
  65956. var node = firstFileLocations_1[_i];
  65957. addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
  65958. }
  65959. for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
  65960. var node = secondFileLocations_1[_b];
  65961. addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
  65962. }
  65963. });
  65964. }
  65965. else {
  65966. // Otherwise issue top-level error since the files appear very identical in terms of what they contain
  65967. var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
  65968. diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file)));
  65969. diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file)));
  65970. }
  65971. });
  65972. amalgamatedDuplicates = undefined;
  65973. }
  65974. function checkExternalEmitHelpers(location, helpers) {
  65975. if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
  65976. var sourceFile = ts.getSourceFileOfNode(location);
  65977. if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
  65978. var helpersModule = resolveHelpersModule(sourceFile, location);
  65979. if (helpersModule !== unknownSymbol) {
  65980. var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
  65981. for (var helper = 1 /* FirstEmitHelper */; helper <= 524288 /* LastEmitHelper */; helper <<= 1) {
  65982. if (uncheckedHelpers & helper) {
  65983. var name = getHelperName(helper);
  65984. var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
  65985. if (!symbol) {
  65986. error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name);
  65987. }
  65988. }
  65989. }
  65990. }
  65991. requestedExternalEmitHelpers |= helpers;
  65992. }
  65993. }
  65994. }
  65995. function getHelperName(helper) {
  65996. switch (helper) {
  65997. case 1 /* Extends */: return "__extends";
  65998. case 2 /* Assign */: return "__assign";
  65999. case 4 /* Rest */: return "__rest";
  66000. case 8 /* Decorate */: return "__decorate";
  66001. case 16 /* Metadata */: return "__metadata";
  66002. case 32 /* Param */: return "__param";
  66003. case 64 /* Awaiter */: return "__awaiter";
  66004. case 128 /* Generator */: return "__generator";
  66005. case 256 /* Values */: return "__values";
  66006. case 512 /* Read */: return "__read";
  66007. case 1024 /* Spread */: return "__spread";
  66008. case 2048 /* SpreadArrays */: return "__spreadArrays";
  66009. case 4096 /* Await */: return "__await";
  66010. case 8192 /* AsyncGenerator */: return "__asyncGenerator";
  66011. case 16384 /* AsyncDelegator */: return "__asyncDelegator";
  66012. case 32768 /* AsyncValues */: return "__asyncValues";
  66013. case 65536 /* ExportStar */: return "__exportStar";
  66014. case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
  66015. case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
  66016. case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
  66017. default: return ts.Debug.fail("Unrecognized helper");
  66018. }
  66019. }
  66020. function resolveHelpersModule(node, errorNode) {
  66021. if (!externalHelpersModule) {
  66022. externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
  66023. }
  66024. return externalHelpersModule;
  66025. }
  66026. // GRAMMAR CHECKING
  66027. function checkGrammarDecoratorsAndModifiers(node) {
  66028. return checkGrammarDecorators(node) || checkGrammarModifiers(node);
  66029. }
  66030. function checkGrammarDecorators(node) {
  66031. if (!node.decorators) {
  66032. return false;
  66033. }
  66034. if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
  66035. if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
  66036. return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
  66037. }
  66038. else {
  66039. return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
  66040. }
  66041. }
  66042. else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
  66043. var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
  66044. if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
  66045. return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
  66046. }
  66047. }
  66048. return false;
  66049. }
  66050. function checkGrammarModifiers(node) {
  66051. var quickResult = reportObviousModifierErrors(node);
  66052. if (quickResult !== undefined) {
  66053. return quickResult;
  66054. }
  66055. var lastStatic, lastDeclare, lastAsync, lastReadonly;
  66056. var flags = 0 /* None */;
  66057. for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
  66058. var modifier = _a[_i];
  66059. if (modifier.kind !== 138 /* ReadonlyKeyword */) {
  66060. if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
  66061. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
  66062. }
  66063. if (node.kind === 167 /* IndexSignature */) {
  66064. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
  66065. }
  66066. }
  66067. switch (modifier.kind) {
  66068. case 81 /* ConstKeyword */:
  66069. if (node.kind !== 248 /* EnumDeclaration */) {
  66070. return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
  66071. }
  66072. break;
  66073. case 119 /* PublicKeyword */:
  66074. case 118 /* ProtectedKeyword */:
  66075. case 117 /* PrivateKeyword */:
  66076. var text = visibilityToString(ts.modifierToFlag(modifier.kind));
  66077. if (flags & 28 /* AccessibilityModifier */) {
  66078. return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
  66079. }
  66080. else if (flags & 32 /* Static */) {
  66081. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
  66082. }
  66083. else if (flags & 64 /* Readonly */) {
  66084. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
  66085. }
  66086. else if (flags & 256 /* Async */) {
  66087. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
  66088. }
  66089. else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
  66090. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
  66091. }
  66092. else if (flags & 128 /* Abstract */) {
  66093. if (modifier.kind === 117 /* PrivateKeyword */) {
  66094. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
  66095. }
  66096. else {
  66097. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
  66098. }
  66099. }
  66100. else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
  66101. return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
  66102. }
  66103. flags |= ts.modifierToFlag(modifier.kind);
  66104. break;
  66105. case 120 /* StaticKeyword */:
  66106. if (flags & 32 /* Static */) {
  66107. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
  66108. }
  66109. else if (flags & 64 /* Readonly */) {
  66110. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
  66111. }
  66112. else if (flags & 256 /* Async */) {
  66113. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
  66114. }
  66115. else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
  66116. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
  66117. }
  66118. else if (node.kind === 156 /* Parameter */) {
  66119. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
  66120. }
  66121. else if (flags & 128 /* Abstract */) {
  66122. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
  66123. }
  66124. else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
  66125. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
  66126. }
  66127. flags |= 32 /* Static */;
  66128. lastStatic = modifier;
  66129. break;
  66130. case 138 /* ReadonlyKeyword */:
  66131. if (flags & 64 /* Readonly */) {
  66132. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
  66133. }
  66134. else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
  66135. // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
  66136. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
  66137. }
  66138. flags |= 64 /* Readonly */;
  66139. lastReadonly = modifier;
  66140. break;
  66141. case 89 /* ExportKeyword */:
  66142. if (flags & 1 /* Export */) {
  66143. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
  66144. }
  66145. else if (flags & 2 /* Ambient */) {
  66146. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
  66147. }
  66148. else if (flags & 128 /* Abstract */) {
  66149. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
  66150. }
  66151. else if (flags & 256 /* Async */) {
  66152. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
  66153. }
  66154. else if (ts.isClassLike(node.parent)) {
  66155. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
  66156. }
  66157. else if (node.kind === 156 /* Parameter */) {
  66158. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
  66159. }
  66160. flags |= 1 /* Export */;
  66161. break;
  66162. case 84 /* DefaultKeyword */:
  66163. var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
  66164. if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
  66165. return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
  66166. }
  66167. flags |= 512 /* Default */;
  66168. break;
  66169. case 130 /* DeclareKeyword */:
  66170. if (flags & 2 /* Ambient */) {
  66171. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
  66172. }
  66173. else if (flags & 256 /* Async */) {
  66174. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
  66175. }
  66176. else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
  66177. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
  66178. }
  66179. else if (node.kind === 156 /* Parameter */) {
  66180. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
  66181. }
  66182. else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
  66183. return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
  66184. }
  66185. else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
  66186. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
  66187. }
  66188. flags |= 2 /* Ambient */;
  66189. lastDeclare = modifier;
  66190. break;
  66191. case 122 /* AbstractKeyword */:
  66192. if (flags & 128 /* Abstract */) {
  66193. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
  66194. }
  66195. if (node.kind !== 245 /* ClassDeclaration */) {
  66196. if (node.kind !== 161 /* MethodDeclaration */ &&
  66197. node.kind !== 159 /* PropertyDeclaration */ &&
  66198. node.kind !== 163 /* GetAccessor */ &&
  66199. node.kind !== 164 /* SetAccessor */) {
  66200. return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
  66201. }
  66202. if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
  66203. return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
  66204. }
  66205. if (flags & 32 /* Static */) {
  66206. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
  66207. }
  66208. if (flags & 8 /* Private */) {
  66209. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
  66210. }
  66211. }
  66212. if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
  66213. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
  66214. }
  66215. flags |= 128 /* Abstract */;
  66216. break;
  66217. case 126 /* AsyncKeyword */:
  66218. if (flags & 256 /* Async */) {
  66219. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
  66220. }
  66221. else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
  66222. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
  66223. }
  66224. else if (node.kind === 156 /* Parameter */) {
  66225. return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
  66226. }
  66227. flags |= 256 /* Async */;
  66228. lastAsync = modifier;
  66229. break;
  66230. }
  66231. }
  66232. if (node.kind === 162 /* Constructor */) {
  66233. if (flags & 32 /* Static */) {
  66234. return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
  66235. }
  66236. if (flags & 128 /* Abstract */) {
  66237. return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
  66238. }
  66239. else if (flags & 256 /* Async */) {
  66240. return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
  66241. }
  66242. else if (flags & 64 /* Readonly */) {
  66243. return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
  66244. }
  66245. return false;
  66246. }
  66247. else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
  66248. return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
  66249. }
  66250. else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
  66251. return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
  66252. }
  66253. else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
  66254. return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
  66255. }
  66256. if (flags & 256 /* Async */) {
  66257. return checkGrammarAsyncModifier(node, lastAsync);
  66258. }
  66259. return false;
  66260. }
  66261. /**
  66262. * true | false: Early return this value from checkGrammarModifiers.
  66263. * undefined: Need to do full checking on the modifiers.
  66264. */
  66265. function reportObviousModifierErrors(node) {
  66266. return !node.modifiers
  66267. ? false
  66268. : shouldReportBadModifier(node)
  66269. ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
  66270. : undefined;
  66271. }
  66272. function shouldReportBadModifier(node) {
  66273. switch (node.kind) {
  66274. case 163 /* GetAccessor */:
  66275. case 164 /* SetAccessor */:
  66276. case 162 /* Constructor */:
  66277. case 159 /* PropertyDeclaration */:
  66278. case 158 /* PropertySignature */:
  66279. case 161 /* MethodDeclaration */:
  66280. case 160 /* MethodSignature */:
  66281. case 167 /* IndexSignature */:
  66282. case 249 /* ModuleDeclaration */:
  66283. case 254 /* ImportDeclaration */:
  66284. case 253 /* ImportEqualsDeclaration */:
  66285. case 260 /* ExportDeclaration */:
  66286. case 259 /* ExportAssignment */:
  66287. case 201 /* FunctionExpression */:
  66288. case 202 /* ArrowFunction */:
  66289. case 156 /* Parameter */:
  66290. return false;
  66291. default:
  66292. if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
  66293. return false;
  66294. }
  66295. switch (node.kind) {
  66296. case 244 /* FunctionDeclaration */:
  66297. return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
  66298. case 245 /* ClassDeclaration */:
  66299. return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
  66300. case 246 /* InterfaceDeclaration */:
  66301. case 225 /* VariableStatement */:
  66302. case 247 /* TypeAliasDeclaration */:
  66303. return true;
  66304. case 248 /* EnumDeclaration */:
  66305. return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
  66306. default:
  66307. ts.Debug.fail();
  66308. return false;
  66309. }
  66310. }
  66311. }
  66312. function nodeHasAnyModifiersExcept(node, allowedModifier) {
  66313. return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
  66314. }
  66315. function checkGrammarAsyncModifier(node, asyncModifier) {
  66316. switch (node.kind) {
  66317. case 161 /* MethodDeclaration */:
  66318. case 244 /* FunctionDeclaration */:
  66319. case 201 /* FunctionExpression */:
  66320. case 202 /* ArrowFunction */:
  66321. return false;
  66322. }
  66323. return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
  66324. }
  66325. function checkGrammarForDisallowedTrailingComma(list, diag) {
  66326. if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
  66327. if (list && list.hasTrailingComma) {
  66328. return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
  66329. }
  66330. return false;
  66331. }
  66332. function checkGrammarTypeParameterList(typeParameters, file) {
  66333. if (typeParameters && typeParameters.length === 0) {
  66334. var start = typeParameters.pos - "<".length;
  66335. var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
  66336. return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
  66337. }
  66338. return false;
  66339. }
  66340. function checkGrammarParameterList(parameters) {
  66341. var seenOptionalParameter = false;
  66342. var parameterCount = parameters.length;
  66343. for (var i = 0; i < parameterCount; i++) {
  66344. var parameter = parameters[i];
  66345. if (parameter.dotDotDotToken) {
  66346. if (i !== (parameterCount - 1)) {
  66347. return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
  66348. }
  66349. if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
  66350. checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
  66351. }
  66352. if (parameter.questionToken) {
  66353. return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
  66354. }
  66355. if (parameter.initializer) {
  66356. return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
  66357. }
  66358. }
  66359. else if (parameter.questionToken) {
  66360. seenOptionalParameter = true;
  66361. if (parameter.initializer) {
  66362. return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
  66363. }
  66364. }
  66365. else if (seenOptionalParameter && !parameter.initializer) {
  66366. return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
  66367. }
  66368. }
  66369. }
  66370. function getNonSimpleParameters(parameters) {
  66371. return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
  66372. }
  66373. function checkGrammarForUseStrictSimpleParameterList(node) {
  66374. if (languageVersion >= 3 /* ES2016 */) {
  66375. var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
  66376. if (useStrictDirective_1) {
  66377. var nonSimpleParameters = getNonSimpleParameters(node.parameters);
  66378. if (ts.length(nonSimpleParameters)) {
  66379. ts.forEach(nonSimpleParameters, function (parameter) {
  66380. ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
  66381. });
  66382. var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
  66383. ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
  66384. return true;
  66385. }
  66386. }
  66387. }
  66388. return false;
  66389. }
  66390. function checkGrammarFunctionLikeDeclaration(node) {
  66391. // Prevent cascading error by short-circuit
  66392. var file = ts.getSourceFileOfNode(node);
  66393. return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
  66394. checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
  66395. (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
  66396. }
  66397. function checkGrammarClassLikeDeclaration(node) {
  66398. var file = ts.getSourceFileOfNode(node);
  66399. return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
  66400. }
  66401. function checkGrammarArrowFunction(node, file) {
  66402. if (!ts.isArrowFunction(node)) {
  66403. return false;
  66404. }
  66405. var equalsGreaterThanToken = node.equalsGreaterThanToken;
  66406. var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
  66407. var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
  66408. return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
  66409. }
  66410. function checkGrammarIndexSignatureParameters(node) {
  66411. var parameter = node.parameters[0];
  66412. if (node.parameters.length !== 1) {
  66413. if (parameter) {
  66414. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
  66415. }
  66416. else {
  66417. return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
  66418. }
  66419. }
  66420. if (parameter.dotDotDotToken) {
  66421. return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
  66422. }
  66423. if (ts.hasModifiers(parameter)) {
  66424. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
  66425. }
  66426. if (parameter.questionToken) {
  66427. return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
  66428. }
  66429. if (parameter.initializer) {
  66430. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
  66431. }
  66432. if (!parameter.type) {
  66433. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
  66434. }
  66435. if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
  66436. var type = getTypeFromTypeNode(parameter.type);
  66437. if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
  66438. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType));
  66439. }
  66440. if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
  66441. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
  66442. }
  66443. return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
  66444. }
  66445. if (!node.type) {
  66446. return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
  66447. }
  66448. return false;
  66449. }
  66450. function checkGrammarIndexSignature(node) {
  66451. // Prevent cascading error by short-circuit
  66452. return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
  66453. }
  66454. function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
  66455. if (typeArguments && typeArguments.length === 0) {
  66456. var sourceFile = ts.getSourceFileOfNode(node);
  66457. var start = typeArguments.pos - "<".length;
  66458. var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
  66459. return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
  66460. }
  66461. return false;
  66462. }
  66463. function checkGrammarTypeArguments(node, typeArguments) {
  66464. return checkGrammarForDisallowedTrailingComma(typeArguments) ||
  66465. checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
  66466. }
  66467. function checkGrammarTaggedTemplateChain(node) {
  66468. if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
  66469. return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
  66470. }
  66471. return false;
  66472. }
  66473. function checkGrammarForOmittedArgument(args) {
  66474. if (args) {
  66475. for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
  66476. var arg = args_4[_i];
  66477. if (arg.kind === 215 /* OmittedExpression */) {
  66478. return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
  66479. }
  66480. }
  66481. }
  66482. return false;
  66483. }
  66484. function checkGrammarArguments(args) {
  66485. return checkGrammarForOmittedArgument(args);
  66486. }
  66487. function checkGrammarHeritageClause(node) {
  66488. var types = node.types;
  66489. if (checkGrammarForDisallowedTrailingComma(types)) {
  66490. return true;
  66491. }
  66492. if (types && types.length === 0) {
  66493. var listType = ts.tokenToString(node.token);
  66494. return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
  66495. }
  66496. return ts.some(types, checkGrammarExpressionWithTypeArguments);
  66497. }
  66498. function checkGrammarExpressionWithTypeArguments(node) {
  66499. return checkGrammarTypeArguments(node, node.typeArguments);
  66500. }
  66501. function checkGrammarClassDeclarationHeritageClauses(node) {
  66502. var seenExtendsClause = false;
  66503. var seenImplementsClause = false;
  66504. if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
  66505. for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
  66506. var heritageClause = _a[_i];
  66507. if (heritageClause.token === 90 /* ExtendsKeyword */) {
  66508. if (seenExtendsClause) {
  66509. return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
  66510. }
  66511. if (seenImplementsClause) {
  66512. return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
  66513. }
  66514. if (heritageClause.types.length > 1) {
  66515. return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
  66516. }
  66517. seenExtendsClause = true;
  66518. }
  66519. else {
  66520. ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
  66521. if (seenImplementsClause) {
  66522. return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
  66523. }
  66524. seenImplementsClause = true;
  66525. }
  66526. // Grammar checking heritageClause inside class declaration
  66527. checkGrammarHeritageClause(heritageClause);
  66528. }
  66529. }
  66530. }
  66531. function checkGrammarInterfaceDeclaration(node) {
  66532. var seenExtendsClause = false;
  66533. if (node.heritageClauses) {
  66534. for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
  66535. var heritageClause = _a[_i];
  66536. if (heritageClause.token === 90 /* ExtendsKeyword */) {
  66537. if (seenExtendsClause) {
  66538. return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
  66539. }
  66540. seenExtendsClause = true;
  66541. }
  66542. else {
  66543. ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
  66544. return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
  66545. }
  66546. // Grammar checking heritageClause inside class declaration
  66547. checkGrammarHeritageClause(heritageClause);
  66548. }
  66549. }
  66550. return false;
  66551. }
  66552. function checkGrammarComputedPropertyName(node) {
  66553. // If node is not a computedPropertyName, just skip the grammar checking
  66554. if (node.kind !== 154 /* ComputedPropertyName */) {
  66555. return false;
  66556. }
  66557. var computedPropertyName = node;
  66558. if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
  66559. return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
  66560. }
  66561. return false;
  66562. }
  66563. function checkGrammarForGenerator(node) {
  66564. if (node.asteriskToken) {
  66565. ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
  66566. node.kind === 201 /* FunctionExpression */ ||
  66567. node.kind === 161 /* MethodDeclaration */);
  66568. if (node.flags & 8388608 /* Ambient */) {
  66569. return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
  66570. }
  66571. if (!node.body) {
  66572. return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
  66573. }
  66574. }
  66575. }
  66576. function checkGrammarForInvalidQuestionMark(questionToken, message) {
  66577. return !!questionToken && grammarErrorOnNode(questionToken, message);
  66578. }
  66579. function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
  66580. return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
  66581. }
  66582. function checkGrammarObjectLiteralExpression(node, inDestructuring) {
  66583. var seen = ts.createUnderscoreEscapedMap();
  66584. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  66585. var prop = _a[_i];
  66586. if (prop.kind === 283 /* SpreadAssignment */) {
  66587. if (inDestructuring) {
  66588. // a rest property cannot be destructured any further
  66589. var expression = ts.skipParentheses(prop.expression);
  66590. if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
  66591. return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
  66592. }
  66593. }
  66594. continue;
  66595. }
  66596. var name = prop.name;
  66597. if (name.kind === 154 /* ComputedPropertyName */) {
  66598. // If the name is not a ComputedPropertyName, the grammar checking will skip it
  66599. checkGrammarComputedPropertyName(name);
  66600. }
  66601. if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
  66602. // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
  66603. // outside of destructuring it is a syntax error
  66604. return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
  66605. }
  66606. if (name.kind === 76 /* PrivateIdentifier */) {
  66607. return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
  66608. }
  66609. // Modifiers are never allowed on properties except for 'async' on a method declaration
  66610. if (prop.modifiers) {
  66611. // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
  66612. for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
  66613. var mod = _c[_b];
  66614. if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
  66615. grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
  66616. }
  66617. }
  66618. }
  66619. // ECMA-262 11.1.5 Object Initializer
  66620. // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
  66621. // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
  66622. // IsDataDescriptor(propId.descriptor) is true.
  66623. // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
  66624. // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
  66625. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
  66626. // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
  66627. var currentKind = void 0;
  66628. switch (prop.kind) {
  66629. case 282 /* ShorthandPropertyAssignment */:
  66630. checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
  66631. // falls through
  66632. case 281 /* PropertyAssignment */:
  66633. // Grammar checking for computedPropertyName and shorthandPropertyAssignment
  66634. checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
  66635. if (name.kind === 8 /* NumericLiteral */) {
  66636. checkGrammarNumericLiteral(name);
  66637. }
  66638. currentKind = 4 /* PropertyAssignment */;
  66639. break;
  66640. case 161 /* MethodDeclaration */:
  66641. currentKind = 8 /* Method */;
  66642. break;
  66643. case 163 /* GetAccessor */:
  66644. currentKind = 1 /* GetAccessor */;
  66645. break;
  66646. case 164 /* SetAccessor */:
  66647. currentKind = 2 /* SetAccessor */;
  66648. break;
  66649. default:
  66650. throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
  66651. }
  66652. if (!inDestructuring) {
  66653. var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
  66654. if (effectiveName === undefined) {
  66655. continue;
  66656. }
  66657. var existingKind = seen.get(effectiveName);
  66658. if (!existingKind) {
  66659. seen.set(effectiveName, currentKind);
  66660. }
  66661. else {
  66662. if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
  66663. grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
  66664. }
  66665. else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
  66666. if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
  66667. seen.set(effectiveName, currentKind | existingKind);
  66668. }
  66669. else {
  66670. return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
  66671. }
  66672. }
  66673. else {
  66674. return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
  66675. }
  66676. }
  66677. }
  66678. }
  66679. }
  66680. function checkGrammarJsxElement(node) {
  66681. checkGrammarTypeArguments(node, node.typeArguments);
  66682. var seen = ts.createUnderscoreEscapedMap();
  66683. for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
  66684. var attr = _a[_i];
  66685. if (attr.kind === 275 /* JsxSpreadAttribute */) {
  66686. continue;
  66687. }
  66688. var name = attr.name, initializer = attr.initializer;
  66689. if (!seen.get(name.escapedText)) {
  66690. seen.set(name.escapedText, true);
  66691. }
  66692. else {
  66693. return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
  66694. }
  66695. if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
  66696. return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
  66697. }
  66698. }
  66699. }
  66700. function checkGrammarJsxExpression(node) {
  66701. if (node.expression && ts.isCommaSequence(node.expression)) {
  66702. return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
  66703. }
  66704. }
  66705. function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
  66706. if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
  66707. return true;
  66708. }
  66709. if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
  66710. if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
  66711. // use of 'for-await-of' in non-async function
  66712. var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
  66713. if (!hasParseDiagnostics(sourceFile)) {
  66714. var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
  66715. var func = ts.getContainingFunction(forInOrOfStatement);
  66716. if (func && func.kind !== 162 /* Constructor */) {
  66717. ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
  66718. var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
  66719. ts.addRelatedInfo(diagnostic, relatedInfo);
  66720. }
  66721. diagnostics.add(diagnostic);
  66722. return true;
  66723. }
  66724. return false;
  66725. }
  66726. }
  66727. if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
  66728. var variableList = forInOrOfStatement.initializer;
  66729. if (!checkGrammarVariableDeclarationList(variableList)) {
  66730. var declarations = variableList.declarations;
  66731. // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
  66732. // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
  66733. // For example:
  66734. // var let = 10;
  66735. // for (let of [1,2,3]) {} // this is invalid ES6 syntax
  66736. // for (let in [1,2,3]) {} // this is invalid ES6 syntax
  66737. // We will then want to skip on grammar checking on variableList declaration
  66738. if (!declarations.length) {
  66739. return false;
  66740. }
  66741. if (declarations.length > 1) {
  66742. var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
  66743. ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
  66744. : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
  66745. return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
  66746. }
  66747. var firstDeclaration = declarations[0];
  66748. if (firstDeclaration.initializer) {
  66749. var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
  66750. ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
  66751. : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
  66752. return grammarErrorOnNode(firstDeclaration.name, diagnostic);
  66753. }
  66754. if (firstDeclaration.type) {
  66755. var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
  66756. ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
  66757. : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
  66758. return grammarErrorOnNode(firstDeclaration, diagnostic);
  66759. }
  66760. }
  66761. }
  66762. return false;
  66763. }
  66764. function checkGrammarAccessor(accessor) {
  66765. if (!(accessor.flags & 8388608 /* Ambient */)) {
  66766. if (languageVersion < 1 /* ES5 */) {
  66767. return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
  66768. }
  66769. if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
  66770. return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
  66771. }
  66772. }
  66773. if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
  66774. return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
  66775. }
  66776. if (accessor.typeParameters) {
  66777. return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
  66778. }
  66779. if (!doesAccessorHaveCorrectParameterCount(accessor)) {
  66780. return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
  66781. ts.Diagnostics.A_get_accessor_cannot_have_parameters :
  66782. ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
  66783. }
  66784. if (accessor.kind === 164 /* SetAccessor */) {
  66785. if (accessor.type) {
  66786. return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
  66787. }
  66788. var parameter = ts.Debug.assertDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
  66789. if (parameter.dotDotDotToken) {
  66790. return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
  66791. }
  66792. if (parameter.questionToken) {
  66793. return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
  66794. }
  66795. if (parameter.initializer) {
  66796. return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
  66797. }
  66798. }
  66799. return false;
  66800. }
  66801. /** Does the accessor have the right number of parameters?
  66802. * A get accessor has no parameters or a single `this` parameter.
  66803. * A set accessor has one parameter or a `this` parameter and one more parameter.
  66804. */
  66805. function doesAccessorHaveCorrectParameterCount(accessor) {
  66806. return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
  66807. }
  66808. function getAccessorThisParameter(accessor) {
  66809. if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
  66810. return ts.getThisParameter(accessor);
  66811. }
  66812. }
  66813. function checkGrammarTypeOperatorNode(node) {
  66814. if (node.operator === 147 /* UniqueKeyword */) {
  66815. if (node.type.kind !== 144 /* SymbolKeyword */) {
  66816. return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
  66817. }
  66818. var parent = ts.walkUpParenthesizedTypes(node.parent);
  66819. switch (parent.kind) {
  66820. case 242 /* VariableDeclaration */:
  66821. var decl = parent;
  66822. if (decl.name.kind !== 75 /* Identifier */) {
  66823. return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
  66824. }
  66825. if (!ts.isVariableDeclarationInVariableStatement(decl)) {
  66826. return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
  66827. }
  66828. if (!(decl.parent.flags & 2 /* Const */)) {
  66829. return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
  66830. }
  66831. break;
  66832. case 159 /* PropertyDeclaration */:
  66833. if (!ts.hasModifier(parent, 32 /* Static */) ||
  66834. !ts.hasModifier(parent, 64 /* Readonly */)) {
  66835. return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
  66836. }
  66837. break;
  66838. case 158 /* PropertySignature */:
  66839. if (!ts.hasModifier(parent, 64 /* Readonly */)) {
  66840. return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
  66841. }
  66842. break;
  66843. default:
  66844. return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
  66845. }
  66846. }
  66847. else if (node.operator === 138 /* ReadonlyKeyword */) {
  66848. if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
  66849. return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
  66850. }
  66851. }
  66852. }
  66853. function checkGrammarForInvalidDynamicName(node, message) {
  66854. if (isNonBindableDynamicName(node)) {
  66855. return grammarErrorOnNode(node, message);
  66856. }
  66857. }
  66858. function checkGrammarMethod(node) {
  66859. if (checkGrammarFunctionLikeDeclaration(node)) {
  66860. return true;
  66861. }
  66862. if (node.kind === 161 /* MethodDeclaration */) {
  66863. if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
  66864. // We only disallow modifier on a method declaration if it is a property of object-literal-expression
  66865. if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
  66866. return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
  66867. }
  66868. else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
  66869. return true;
  66870. }
  66871. else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
  66872. return true;
  66873. }
  66874. else if (node.body === undefined) {
  66875. return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
  66876. }
  66877. }
  66878. if (checkGrammarForGenerator(node)) {
  66879. return true;
  66880. }
  66881. }
  66882. if (ts.isClassLike(node.parent)) {
  66883. // Technically, computed properties in ambient contexts is disallowed
  66884. // for property declarations and accessors too, not just methods.
  66885. // However, property declarations disallow computed names in general,
  66886. // and accessors are not allowed in ambient contexts in general,
  66887. // so this error only really matters for methods.
  66888. if (node.flags & 8388608 /* Ambient */) {
  66889. return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
  66890. }
  66891. else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
  66892. return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
  66893. }
  66894. }
  66895. else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
  66896. return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
  66897. }
  66898. else if (node.parent.kind === 173 /* TypeLiteral */) {
  66899. return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
  66900. }
  66901. }
  66902. function checkGrammarBreakOrContinueStatement(node) {
  66903. var current = node;
  66904. while (current) {
  66905. if (ts.isFunctionLike(current)) {
  66906. return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
  66907. }
  66908. switch (current.kind) {
  66909. case 238 /* LabeledStatement */:
  66910. if (node.label && current.label.escapedText === node.label.escapedText) {
  66911. // found matching label - verify that label usage is correct
  66912. // continue can only target labels that are on iteration statements
  66913. var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
  66914. && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
  66915. if (isMisplacedContinueLabel) {
  66916. return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
  66917. }
  66918. return false;
  66919. }
  66920. break;
  66921. case 237 /* SwitchStatement */:
  66922. if (node.kind === 234 /* BreakStatement */ && !node.label) {
  66923. // unlabeled break within switch statement - ok
  66924. return false;
  66925. }
  66926. break;
  66927. default:
  66928. if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
  66929. // unlabeled break or continue within iteration statement - ok
  66930. return false;
  66931. }
  66932. break;
  66933. }
  66934. current = current.parent;
  66935. }
  66936. if (node.label) {
  66937. var message = node.kind === 234 /* BreakStatement */
  66938. ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
  66939. : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
  66940. return grammarErrorOnNode(node, message);
  66941. }
  66942. else {
  66943. var message = node.kind === 234 /* BreakStatement */
  66944. ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
  66945. : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
  66946. return grammarErrorOnNode(node, message);
  66947. }
  66948. }
  66949. function checkGrammarBindingElement(node) {
  66950. if (node.dotDotDotToken) {
  66951. var elements = node.parent.elements;
  66952. if (node !== ts.last(elements)) {
  66953. return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
  66954. }
  66955. checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
  66956. if (node.propertyName) {
  66957. return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
  66958. }
  66959. if (node.initializer) {
  66960. // Error on equals token which immediately precedes the initializer
  66961. return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
  66962. }
  66963. }
  66964. }
  66965. function isStringOrNumberLiteralExpression(expr) {
  66966. return ts.isStringOrNumericLiteralLike(expr) ||
  66967. expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
  66968. expr.operand.kind === 8 /* NumericLiteral */;
  66969. }
  66970. function isBigIntLiteralExpression(expr) {
  66971. return expr.kind === 9 /* BigIntLiteral */ ||
  66972. expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
  66973. expr.operand.kind === 9 /* BigIntLiteral */;
  66974. }
  66975. function isSimpleLiteralEnumReference(expr) {
  66976. if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
  66977. ts.isEntityNameExpression(expr.expression)) {
  66978. return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
  66979. }
  66980. }
  66981. function checkAmbientInitializer(node) {
  66982. var initializer = node.initializer;
  66983. if (initializer) {
  66984. var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
  66985. isSimpleLiteralEnumReference(initializer) ||
  66986. initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
  66987. isBigIntLiteralExpression(initializer));
  66988. var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
  66989. if (isConstOrReadonly && !node.type) {
  66990. if (isInvalidInitializer) {
  66991. return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
  66992. }
  66993. }
  66994. else {
  66995. return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
  66996. }
  66997. if (!isConstOrReadonly || isInvalidInitializer) {
  66998. return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
  66999. }
  67000. }
  67001. }
  67002. function checkGrammarVariableDeclaration(node) {
  67003. if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
  67004. if (node.flags & 8388608 /* Ambient */) {
  67005. checkAmbientInitializer(node);
  67006. }
  67007. else if (!node.initializer) {
  67008. if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
  67009. return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
  67010. }
  67011. if (ts.isVarConst(node)) {
  67012. return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
  67013. }
  67014. }
  67015. }
  67016. if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
  67017. return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
  67018. }
  67019. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  67020. if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
  67021. !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
  67022. checkESModuleMarker(node.name);
  67023. }
  67024. var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
  67025. // 1. LexicalDeclaration : LetOrConst BindingList ;
  67026. // It is a Syntax Error if the BoundNames of BindingList contains "let".
  67027. // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
  67028. // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
  67029. // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
  67030. // and its Identifier is eval or arguments
  67031. return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
  67032. }
  67033. function checkESModuleMarker(name) {
  67034. if (name.kind === 75 /* Identifier */) {
  67035. if (ts.idText(name) === "__esModule") {
  67036. return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
  67037. }
  67038. }
  67039. else {
  67040. var elements = name.elements;
  67041. for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
  67042. var element = elements_1[_i];
  67043. if (!ts.isOmittedExpression(element)) {
  67044. return checkESModuleMarker(element.name);
  67045. }
  67046. }
  67047. }
  67048. return false;
  67049. }
  67050. function checkGrammarNameInLetOrConstDeclarations(name) {
  67051. if (name.kind === 75 /* Identifier */) {
  67052. if (name.originalKeywordKind === 115 /* LetKeyword */) {
  67053. return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
  67054. }
  67055. }
  67056. else {
  67057. var elements = name.elements;
  67058. for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
  67059. var element = elements_2[_i];
  67060. if (!ts.isOmittedExpression(element)) {
  67061. checkGrammarNameInLetOrConstDeclarations(element.name);
  67062. }
  67063. }
  67064. }
  67065. return false;
  67066. }
  67067. function checkGrammarVariableDeclarationList(declarationList) {
  67068. var declarations = declarationList.declarations;
  67069. if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
  67070. return true;
  67071. }
  67072. if (!declarationList.declarations.length) {
  67073. return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
  67074. }
  67075. return false;
  67076. }
  67077. function allowLetAndConstDeclarations(parent) {
  67078. switch (parent.kind) {
  67079. case 227 /* IfStatement */:
  67080. case 228 /* DoStatement */:
  67081. case 229 /* WhileStatement */:
  67082. case 236 /* WithStatement */:
  67083. case 230 /* ForStatement */:
  67084. case 231 /* ForInStatement */:
  67085. case 232 /* ForOfStatement */:
  67086. return false;
  67087. case 238 /* LabeledStatement */:
  67088. return allowLetAndConstDeclarations(parent.parent);
  67089. }
  67090. return true;
  67091. }
  67092. function checkGrammarForDisallowedLetOrConstStatement(node) {
  67093. if (!allowLetAndConstDeclarations(node.parent)) {
  67094. if (ts.isLet(node.declarationList)) {
  67095. return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
  67096. }
  67097. else if (ts.isVarConst(node.declarationList)) {
  67098. return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
  67099. }
  67100. }
  67101. }
  67102. function checkGrammarMetaProperty(node) {
  67103. var escapedText = node.name.escapedText;
  67104. switch (node.keywordToken) {
  67105. case 99 /* NewKeyword */:
  67106. if (escapedText !== "target") {
  67107. return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target");
  67108. }
  67109. break;
  67110. case 96 /* ImportKeyword */:
  67111. if (escapedText !== "meta") {
  67112. return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta");
  67113. }
  67114. break;
  67115. }
  67116. }
  67117. function hasParseDiagnostics(sourceFile) {
  67118. return sourceFile.parseDiagnostics.length > 0;
  67119. }
  67120. function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
  67121. var sourceFile = ts.getSourceFileOfNode(node);
  67122. if (!hasParseDiagnostics(sourceFile)) {
  67123. var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
  67124. diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
  67125. return true;
  67126. }
  67127. return false;
  67128. }
  67129. function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
  67130. var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
  67131. if (!hasParseDiagnostics(sourceFile)) {
  67132. diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
  67133. return true;
  67134. }
  67135. return false;
  67136. }
  67137. function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
  67138. var sourceFile = ts.getSourceFileOfNode(node);
  67139. if (!hasParseDiagnostics(sourceFile)) {
  67140. diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
  67141. return true;
  67142. }
  67143. return false;
  67144. }
  67145. function checkGrammarConstructorTypeParameters(node) {
  67146. var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
  67147. var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
  67148. if (range) {
  67149. var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
  67150. return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
  67151. }
  67152. }
  67153. function checkGrammarConstructorTypeAnnotation(node) {
  67154. var type = ts.getEffectiveReturnTypeNode(node);
  67155. if (type) {
  67156. return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
  67157. }
  67158. }
  67159. function checkGrammarProperty(node) {
  67160. if (ts.isClassLike(node.parent)) {
  67161. if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
  67162. return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
  67163. }
  67164. if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
  67165. return true;
  67166. }
  67167. if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
  67168. return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
  67169. }
  67170. }
  67171. else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
  67172. if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
  67173. return true;
  67174. }
  67175. if (node.initializer) {
  67176. return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
  67177. }
  67178. }
  67179. else if (node.parent.kind === 173 /* TypeLiteral */) {
  67180. if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
  67181. return true;
  67182. }
  67183. if (node.initializer) {
  67184. return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
  67185. }
  67186. }
  67187. if (node.flags & 8388608 /* Ambient */) {
  67188. checkAmbientInitializer(node);
  67189. }
  67190. if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
  67191. node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
  67192. return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
  67193. }
  67194. }
  67195. function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
  67196. // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
  67197. // interfaces and imports categories:
  67198. //
  67199. // DeclarationElement:
  67200. // ExportAssignment
  67201. // export_opt InterfaceDeclaration
  67202. // export_opt TypeAliasDeclaration
  67203. // export_opt ImportDeclaration
  67204. // export_opt ExternalImportDeclaration
  67205. // export_opt AmbientDeclaration
  67206. //
  67207. // TODO: The spec needs to be amended to reflect this grammar.
  67208. if (node.kind === 246 /* InterfaceDeclaration */ ||
  67209. node.kind === 247 /* TypeAliasDeclaration */ ||
  67210. node.kind === 254 /* ImportDeclaration */ ||
  67211. node.kind === 253 /* ImportEqualsDeclaration */ ||
  67212. node.kind === 260 /* ExportDeclaration */ ||
  67213. node.kind === 259 /* ExportAssignment */ ||
  67214. node.kind === 252 /* NamespaceExportDeclaration */ ||
  67215. ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
  67216. return false;
  67217. }
  67218. return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
  67219. }
  67220. function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
  67221. for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
  67222. var decl = _a[_i];
  67223. if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
  67224. if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
  67225. return true;
  67226. }
  67227. }
  67228. }
  67229. return false;
  67230. }
  67231. function checkGrammarSourceFile(node) {
  67232. return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
  67233. }
  67234. function checkGrammarStatementInAmbientContext(node) {
  67235. if (node.flags & 8388608 /* Ambient */) {
  67236. // Find containing block which is either Block, ModuleBlock, SourceFile
  67237. var links = getNodeLinks(node);
  67238. if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
  67239. return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
  67240. }
  67241. // We are either parented by another statement, or some sort of block.
  67242. // If we're in a block, we only want to really report an error once
  67243. // to prevent noisiness. So use a bit on the block to indicate if
  67244. // this has already been reported, and don't report if it has.
  67245. //
  67246. if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
  67247. var links_2 = getNodeLinks(node.parent);
  67248. // Check if the containing block ever report this error
  67249. if (!links_2.hasReportedStatementInAmbientContext) {
  67250. return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
  67251. }
  67252. }
  67253. else {
  67254. // We must be parented by a statement. If so, there's no need
  67255. // to report the error as our parent will have already done it.
  67256. // Debug.assert(isStatement(node.parent));
  67257. }
  67258. }
  67259. return false;
  67260. }
  67261. function checkGrammarNumericLiteral(node) {
  67262. // Grammar checking
  67263. if (node.numericLiteralFlags & 32 /* Octal */) {
  67264. var diagnosticMessage = void 0;
  67265. if (languageVersion >= 1 /* ES5 */) {
  67266. diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
  67267. }
  67268. else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
  67269. diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
  67270. }
  67271. else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
  67272. diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
  67273. }
  67274. if (diagnosticMessage) {
  67275. var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
  67276. var literal = (withMinus ? "-" : "") + "0o" + node.text;
  67277. return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
  67278. }
  67279. }
  67280. // Realism (size) checking
  67281. checkNumericLiteralValueSize(node);
  67282. return false;
  67283. }
  67284. function checkNumericLiteralValueSize(node) {
  67285. // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
  67286. // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
  67287. // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
  67288. if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
  67289. return;
  67290. }
  67291. // We can't rely on the runtime to accurately store and compare extremely large numeric values
  67292. // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
  67293. // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
  67294. // it's likely addition operations on it will fail too
  67295. var apparentValue = +ts.getTextOfNode(node);
  67296. if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
  67297. return;
  67298. }
  67299. addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers));
  67300. }
  67301. function checkGrammarBigIntLiteral(node) {
  67302. var literalType = ts.isLiteralTypeNode(node.parent) ||
  67303. ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
  67304. if (!literalType) {
  67305. if (languageVersion < 7 /* ES2020 */) {
  67306. if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
  67307. return true;
  67308. }
  67309. }
  67310. }
  67311. return false;
  67312. }
  67313. function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
  67314. var sourceFile = ts.getSourceFileOfNode(node);
  67315. if (!hasParseDiagnostics(sourceFile)) {
  67316. var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
  67317. diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
  67318. return true;
  67319. }
  67320. return false;
  67321. }
  67322. function getAmbientModules() {
  67323. if (!ambientModulesCache) {
  67324. ambientModulesCache = [];
  67325. globals.forEach(function (global, sym) {
  67326. // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
  67327. if (ambientModuleSymbolRegex.test(sym)) {
  67328. ambientModulesCache.push(global);
  67329. }
  67330. });
  67331. }
  67332. return ambientModulesCache;
  67333. }
  67334. function checkGrammarImportClause(node) {
  67335. if (node.isTypeOnly && node.name && node.namedBindings) {
  67336. return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
  67337. }
  67338. return false;
  67339. }
  67340. function checkGrammarImportCallExpression(node) {
  67341. if (moduleKind === ts.ModuleKind.ES2015) {
  67342. return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
  67343. }
  67344. if (node.typeArguments) {
  67345. return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
  67346. }
  67347. var nodeArguments = node.arguments;
  67348. if (nodeArguments.length !== 1) {
  67349. return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
  67350. }
  67351. checkGrammarForDisallowedTrailingComma(nodeArguments);
  67352. // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
  67353. // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
  67354. if (ts.isSpreadElement(nodeArguments[0])) {
  67355. return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
  67356. }
  67357. return false;
  67358. }
  67359. function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
  67360. var sourceObjectFlags = ts.getObjectFlags(source);
  67361. if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
  67362. return ts.find(unionTarget.types, function (target) {
  67363. if (target.flags & 524288 /* Object */) {
  67364. var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
  67365. if (overlapObjFlags & 4 /* Reference */) {
  67366. return source.target === target.target;
  67367. }
  67368. if (overlapObjFlags & 16 /* Anonymous */) {
  67369. return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
  67370. }
  67371. }
  67372. return false;
  67373. });
  67374. }
  67375. }
  67376. function findBestTypeForObjectLiteral(source, unionTarget) {
  67377. if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
  67378. return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
  67379. }
  67380. }
  67381. function findBestTypeForInvokable(source, unionTarget) {
  67382. var signatureKind = 0 /* Call */;
  67383. var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
  67384. (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
  67385. if (hasSignatures) {
  67386. return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
  67387. }
  67388. }
  67389. function findMostOverlappyType(source, unionTarget) {
  67390. var bestMatch;
  67391. var matchingCount = 0;
  67392. for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
  67393. var target = _a[_i];
  67394. var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
  67395. if (overlap.flags & 4194304 /* Index */) {
  67396. // perfect overlap of keys
  67397. bestMatch = target;
  67398. matchingCount = Infinity;
  67399. }
  67400. else if (overlap.flags & 1048576 /* Union */) {
  67401. // We only want to account for literal types otherwise.
  67402. // If we have a union of index types, it seems likely that we
  67403. // needed to elaborate between two generic mapped types anyway.
  67404. var len = ts.length(ts.filter(overlap.types, isUnitType));
  67405. if (len >= matchingCount) {
  67406. bestMatch = target;
  67407. matchingCount = len;
  67408. }
  67409. }
  67410. else if (isUnitType(overlap) && 1 >= matchingCount) {
  67411. bestMatch = target;
  67412. matchingCount = 1;
  67413. }
  67414. }
  67415. return bestMatch;
  67416. }
  67417. function filterPrimitivesIfContainsNonPrimitive(type) {
  67418. if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
  67419. var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
  67420. if (!(result.flags & 131072 /* Never */)) {
  67421. return result;
  67422. }
  67423. }
  67424. return type;
  67425. }
  67426. // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
  67427. function findMatchingDiscriminantType(source, target, isRelatedTo) {
  67428. if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
  67429. var sourceProperties = getPropertiesOfType(source);
  67430. if (sourceProperties) {
  67431. var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
  67432. if (sourcePropertiesFiltered) {
  67433. return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo);
  67434. }
  67435. }
  67436. }
  67437. return undefined;
  67438. }
  67439. }
  67440. ts.createTypeChecker = createTypeChecker;
  67441. function isNotAccessor(declaration) {
  67442. // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
  67443. return !ts.isAccessor(declaration);
  67444. }
  67445. function isNotOverload(declaration) {
  67446. return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
  67447. !!declaration.body;
  67448. }
  67449. /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
  67450. function isDeclarationNameOrImportPropertyName(name) {
  67451. switch (name.parent.kind) {
  67452. case 258 /* ImportSpecifier */:
  67453. case 263 /* ExportSpecifier */:
  67454. return ts.isIdentifier(name);
  67455. default:
  67456. return ts.isDeclarationName(name);
  67457. }
  67458. }
  67459. function isSomeImportDeclaration(decl) {
  67460. switch (decl.kind) {
  67461. case 255 /* ImportClause */: // For default import
  67462. case 253 /* ImportEqualsDeclaration */:
  67463. case 256 /* NamespaceImport */:
  67464. case 258 /* ImportSpecifier */: // For rename import `x as y`
  67465. return true;
  67466. case 75 /* Identifier */:
  67467. // For regular import, `decl` is an Identifier under the ImportSpecifier.
  67468. return decl.parent.kind === 258 /* ImportSpecifier */;
  67469. default:
  67470. return false;
  67471. }
  67472. }
  67473. var JsxNames;
  67474. (function (JsxNames) {
  67475. JsxNames.JSX = "JSX";
  67476. JsxNames.IntrinsicElements = "IntrinsicElements";
  67477. JsxNames.ElementClass = "ElementClass";
  67478. JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
  67479. JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
  67480. JsxNames.Element = "Element";
  67481. JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
  67482. JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
  67483. JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
  67484. })(JsxNames || (JsxNames = {}));
  67485. function getIterationTypesKeyFromIterationTypeKind(typeKind) {
  67486. switch (typeKind) {
  67487. case 0 /* Yield */: return "yieldType";
  67488. case 1 /* Return */: return "returnType";
  67489. case 2 /* Next */: return "nextType";
  67490. }
  67491. }
  67492. function signatureHasRestParameter(s) {
  67493. return !!(s.flags & 1 /* HasRestParameter */);
  67494. }
  67495. ts.signatureHasRestParameter = signatureHasRestParameter;
  67496. function signatureHasLiteralTypes(s) {
  67497. return !!(s.flags & 2 /* HasLiteralTypes */);
  67498. }
  67499. ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
  67500. })(ts || (ts = {}));
  67501. var ts;
  67502. (function (ts) {
  67503. function createSynthesizedNode(kind) {
  67504. var node = ts.createNode(kind, -1, -1);
  67505. node.flags |= 8 /* Synthesized */;
  67506. return node;
  67507. }
  67508. /* @internal */
  67509. function updateNode(updated, original) {
  67510. if (updated !== original) {
  67511. setOriginalNode(updated, original);
  67512. setTextRange(updated, original);
  67513. ts.aggregateTransformFlags(updated);
  67514. }
  67515. return updated;
  67516. }
  67517. ts.updateNode = updateNode;
  67518. /**
  67519. * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
  67520. */
  67521. function createNodeArray(elements, hasTrailingComma) {
  67522. if (!elements || elements === ts.emptyArray) {
  67523. elements = [];
  67524. }
  67525. else if (ts.isNodeArray(elements)) {
  67526. return elements;
  67527. }
  67528. var array = elements;
  67529. array.pos = -1;
  67530. array.end = -1;
  67531. array.hasTrailingComma = hasTrailingComma;
  67532. return array;
  67533. }
  67534. ts.createNodeArray = createNodeArray;
  67535. /**
  67536. * Creates a shallow, memberwise clone of a node with no source map location.
  67537. */
  67538. /* @internal */
  67539. function getSynthesizedClone(node) {
  67540. // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
  67541. // the original node. We also need to exclude specific properties and only include own-
  67542. // properties (to skip members already defined on the shared prototype).
  67543. if (node === undefined) {
  67544. return node;
  67545. }
  67546. var clone = createSynthesizedNode(node.kind);
  67547. clone.flags |= node.flags;
  67548. setOriginalNode(clone, node);
  67549. for (var key in node) {
  67550. if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
  67551. continue;
  67552. }
  67553. clone[key] = node[key];
  67554. }
  67555. return clone;
  67556. }
  67557. ts.getSynthesizedClone = getSynthesizedClone;
  67558. function createLiteral(value, isSingleQuote) {
  67559. if (typeof value === "number") {
  67560. return createNumericLiteral(value + "");
  67561. }
  67562. // eslint-disable-next-line no-in-operator
  67563. if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
  67564. return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
  67565. }
  67566. if (typeof value === "boolean") {
  67567. return value ? createTrue() : createFalse();
  67568. }
  67569. if (ts.isString(value)) {
  67570. var res = createStringLiteral(value);
  67571. if (isSingleQuote)
  67572. res.singleQuote = true;
  67573. return res;
  67574. }
  67575. return createLiteralFromNode(value);
  67576. }
  67577. ts.createLiteral = createLiteral;
  67578. function createNumericLiteral(value, numericLiteralFlags) {
  67579. if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
  67580. var node = createSynthesizedNode(8 /* NumericLiteral */);
  67581. node.text = value;
  67582. node.numericLiteralFlags = numericLiteralFlags;
  67583. return node;
  67584. }
  67585. ts.createNumericLiteral = createNumericLiteral;
  67586. function createBigIntLiteral(value) {
  67587. var node = createSynthesizedNode(9 /* BigIntLiteral */);
  67588. node.text = value;
  67589. return node;
  67590. }
  67591. ts.createBigIntLiteral = createBigIntLiteral;
  67592. function createStringLiteral(text) {
  67593. var node = createSynthesizedNode(10 /* StringLiteral */);
  67594. node.text = text;
  67595. return node;
  67596. }
  67597. ts.createStringLiteral = createStringLiteral;
  67598. function createRegularExpressionLiteral(text) {
  67599. var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
  67600. node.text = text;
  67601. return node;
  67602. }
  67603. ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
  67604. function createLiteralFromNode(sourceNode) {
  67605. var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
  67606. node.textSourceNode = sourceNode;
  67607. return node;
  67608. }
  67609. function createIdentifier(text, typeArguments) {
  67610. var node = createSynthesizedNode(75 /* Identifier */);
  67611. node.escapedText = ts.escapeLeadingUnderscores(text);
  67612. node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
  67613. node.autoGenerateFlags = 0 /* None */;
  67614. node.autoGenerateId = 0;
  67615. if (typeArguments) {
  67616. node.typeArguments = createNodeArray(typeArguments);
  67617. }
  67618. return node;
  67619. }
  67620. ts.createIdentifier = createIdentifier;
  67621. function updateIdentifier(node, typeArguments) {
  67622. return node.typeArguments !== typeArguments
  67623. ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
  67624. : node;
  67625. }
  67626. ts.updateIdentifier = updateIdentifier;
  67627. var nextAutoGenerateId = 0;
  67628. function createTempVariable(recordTempVariable, reservedInNestedScopes) {
  67629. var name = createIdentifier("");
  67630. name.autoGenerateFlags = 1 /* Auto */;
  67631. name.autoGenerateId = nextAutoGenerateId;
  67632. nextAutoGenerateId++;
  67633. if (recordTempVariable) {
  67634. recordTempVariable(name);
  67635. }
  67636. if (reservedInNestedScopes) {
  67637. name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
  67638. }
  67639. return name;
  67640. }
  67641. ts.createTempVariable = createTempVariable;
  67642. /** Create a unique temporary variable for use in a loop. */
  67643. function createLoopVariable() {
  67644. var name = createIdentifier("");
  67645. name.autoGenerateFlags = 2 /* Loop */;
  67646. name.autoGenerateId = nextAutoGenerateId;
  67647. nextAutoGenerateId++;
  67648. return name;
  67649. }
  67650. ts.createLoopVariable = createLoopVariable;
  67651. /** Create a unique name based on the supplied text. */
  67652. function createUniqueName(text) {
  67653. var name = createIdentifier(text);
  67654. name.autoGenerateFlags = 3 /* Unique */;
  67655. name.autoGenerateId = nextAutoGenerateId;
  67656. nextAutoGenerateId++;
  67657. return name;
  67658. }
  67659. ts.createUniqueName = createUniqueName;
  67660. function createOptimisticUniqueName(text) {
  67661. var name = createIdentifier(text);
  67662. name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
  67663. name.autoGenerateId = nextAutoGenerateId;
  67664. nextAutoGenerateId++;
  67665. return name;
  67666. }
  67667. ts.createOptimisticUniqueName = createOptimisticUniqueName;
  67668. /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
  67669. function createFileLevelUniqueName(text) {
  67670. var name = createOptimisticUniqueName(text);
  67671. name.autoGenerateFlags |= 32 /* FileLevel */;
  67672. return name;
  67673. }
  67674. ts.createFileLevelUniqueName = createFileLevelUniqueName;
  67675. function getGeneratedNameForNode(node, flags) {
  67676. var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
  67677. name.autoGenerateFlags = 4 /* Node */ | flags;
  67678. name.autoGenerateId = nextAutoGenerateId;
  67679. name.original = node;
  67680. nextAutoGenerateId++;
  67681. return name;
  67682. }
  67683. ts.getGeneratedNameForNode = getGeneratedNameForNode;
  67684. // Private Identifiers
  67685. function createPrivateIdentifier(text) {
  67686. if (text[0] !== "#") {
  67687. ts.Debug.fail("First character of private identifier must be #: " + text);
  67688. }
  67689. var node = createSynthesizedNode(76 /* PrivateIdentifier */);
  67690. node.escapedText = ts.escapeLeadingUnderscores(text);
  67691. return node;
  67692. }
  67693. ts.createPrivateIdentifier = createPrivateIdentifier;
  67694. // Punctuation
  67695. function createToken(token) {
  67696. return createSynthesizedNode(token);
  67697. }
  67698. ts.createToken = createToken;
  67699. // Reserved words
  67700. function createSuper() {
  67701. return createSynthesizedNode(102 /* SuperKeyword */);
  67702. }
  67703. ts.createSuper = createSuper;
  67704. function createThis() {
  67705. return createSynthesizedNode(104 /* ThisKeyword */);
  67706. }
  67707. ts.createThis = createThis;
  67708. function createNull() {
  67709. return createSynthesizedNode(100 /* NullKeyword */);
  67710. }
  67711. ts.createNull = createNull;
  67712. function createTrue() {
  67713. return createSynthesizedNode(106 /* TrueKeyword */);
  67714. }
  67715. ts.createTrue = createTrue;
  67716. function createFalse() {
  67717. return createSynthesizedNode(91 /* FalseKeyword */);
  67718. }
  67719. ts.createFalse = createFalse;
  67720. // Modifiers
  67721. function createModifier(kind) {
  67722. return createToken(kind);
  67723. }
  67724. ts.createModifier = createModifier;
  67725. function createModifiersFromModifierFlags(flags) {
  67726. var result = [];
  67727. if (flags & 1 /* Export */) {
  67728. result.push(createModifier(89 /* ExportKeyword */));
  67729. }
  67730. if (flags & 2 /* Ambient */) {
  67731. result.push(createModifier(130 /* DeclareKeyword */));
  67732. }
  67733. if (flags & 512 /* Default */) {
  67734. result.push(createModifier(84 /* DefaultKeyword */));
  67735. }
  67736. if (flags & 2048 /* Const */) {
  67737. result.push(createModifier(81 /* ConstKeyword */));
  67738. }
  67739. if (flags & 4 /* Public */) {
  67740. result.push(createModifier(119 /* PublicKeyword */));
  67741. }
  67742. if (flags & 8 /* Private */) {
  67743. result.push(createModifier(117 /* PrivateKeyword */));
  67744. }
  67745. if (flags & 16 /* Protected */) {
  67746. result.push(createModifier(118 /* ProtectedKeyword */));
  67747. }
  67748. if (flags & 128 /* Abstract */) {
  67749. result.push(createModifier(122 /* AbstractKeyword */));
  67750. }
  67751. if (flags & 32 /* Static */) {
  67752. result.push(createModifier(120 /* StaticKeyword */));
  67753. }
  67754. if (flags & 64 /* Readonly */) {
  67755. result.push(createModifier(138 /* ReadonlyKeyword */));
  67756. }
  67757. if (flags & 256 /* Async */) {
  67758. result.push(createModifier(126 /* AsyncKeyword */));
  67759. }
  67760. return result;
  67761. }
  67762. ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
  67763. // Names
  67764. function createQualifiedName(left, right) {
  67765. var node = createSynthesizedNode(153 /* QualifiedName */);
  67766. node.left = left;
  67767. node.right = asName(right);
  67768. return node;
  67769. }
  67770. ts.createQualifiedName = createQualifiedName;
  67771. function updateQualifiedName(node, left, right) {
  67772. return node.left !== left
  67773. || node.right !== right
  67774. ? updateNode(createQualifiedName(left, right), node)
  67775. : node;
  67776. }
  67777. ts.updateQualifiedName = updateQualifiedName;
  67778. function parenthesizeForComputedName(expression) {
  67779. return ts.isCommaSequence(expression)
  67780. ? createParen(expression)
  67781. : expression;
  67782. }
  67783. function createComputedPropertyName(expression) {
  67784. var node = createSynthesizedNode(154 /* ComputedPropertyName */);
  67785. node.expression = parenthesizeForComputedName(expression);
  67786. return node;
  67787. }
  67788. ts.createComputedPropertyName = createComputedPropertyName;
  67789. function updateComputedPropertyName(node, expression) {
  67790. return node.expression !== expression
  67791. ? updateNode(createComputedPropertyName(expression), node)
  67792. : node;
  67793. }
  67794. ts.updateComputedPropertyName = updateComputedPropertyName;
  67795. // Signature elements
  67796. function createTypeParameterDeclaration(name, constraint, defaultType) {
  67797. var node = createSynthesizedNode(155 /* TypeParameter */);
  67798. node.name = asName(name);
  67799. node.constraint = constraint;
  67800. node.default = defaultType;
  67801. return node;
  67802. }
  67803. ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
  67804. function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
  67805. return node.name !== name
  67806. || node.constraint !== constraint
  67807. || node.default !== defaultType
  67808. ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
  67809. : node;
  67810. }
  67811. ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
  67812. function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
  67813. var node = createSynthesizedNode(156 /* Parameter */);
  67814. node.decorators = asNodeArray(decorators);
  67815. node.modifiers = asNodeArray(modifiers);
  67816. node.dotDotDotToken = dotDotDotToken;
  67817. node.name = asName(name);
  67818. node.questionToken = questionToken;
  67819. node.type = type;
  67820. node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
  67821. return node;
  67822. }
  67823. ts.createParameter = createParameter;
  67824. function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
  67825. return node.decorators !== decorators
  67826. || node.modifiers !== modifiers
  67827. || node.dotDotDotToken !== dotDotDotToken
  67828. || node.name !== name
  67829. || node.questionToken !== questionToken
  67830. || node.type !== type
  67831. || node.initializer !== initializer
  67832. ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
  67833. : node;
  67834. }
  67835. ts.updateParameter = updateParameter;
  67836. function createDecorator(expression) {
  67837. var node = createSynthesizedNode(157 /* Decorator */);
  67838. node.expression = ts.parenthesizeForAccess(expression);
  67839. return node;
  67840. }
  67841. ts.createDecorator = createDecorator;
  67842. function updateDecorator(node, expression) {
  67843. return node.expression !== expression
  67844. ? updateNode(createDecorator(expression), node)
  67845. : node;
  67846. }
  67847. ts.updateDecorator = updateDecorator;
  67848. // Type Elements
  67849. function createPropertySignature(modifiers, name, questionToken, type, initializer) {
  67850. var node = createSynthesizedNode(158 /* PropertySignature */);
  67851. node.modifiers = asNodeArray(modifiers);
  67852. node.name = asName(name);
  67853. node.questionToken = questionToken;
  67854. node.type = type;
  67855. node.initializer = initializer;
  67856. return node;
  67857. }
  67858. ts.createPropertySignature = createPropertySignature;
  67859. function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
  67860. return node.modifiers !== modifiers
  67861. || node.name !== name
  67862. || node.questionToken !== questionToken
  67863. || node.type !== type
  67864. || node.initializer !== initializer
  67865. ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
  67866. : node;
  67867. }
  67868. ts.updatePropertySignature = updatePropertySignature;
  67869. function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
  67870. var node = createSynthesizedNode(159 /* PropertyDeclaration */);
  67871. node.decorators = asNodeArray(decorators);
  67872. node.modifiers = asNodeArray(modifiers);
  67873. node.name = asName(name);
  67874. node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
  67875. node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
  67876. node.type = type;
  67877. node.initializer = initializer;
  67878. return node;
  67879. }
  67880. ts.createProperty = createProperty;
  67881. function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
  67882. return node.decorators !== decorators
  67883. || node.modifiers !== modifiers
  67884. || node.name !== name
  67885. || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
  67886. || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
  67887. || node.type !== type
  67888. || node.initializer !== initializer
  67889. ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
  67890. : node;
  67891. }
  67892. ts.updateProperty = updateProperty;
  67893. function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
  67894. var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
  67895. node.name = asName(name);
  67896. node.questionToken = questionToken;
  67897. return node;
  67898. }
  67899. ts.createMethodSignature = createMethodSignature;
  67900. function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
  67901. return node.typeParameters !== typeParameters
  67902. || node.parameters !== parameters
  67903. || node.type !== type
  67904. || node.name !== name
  67905. || node.questionToken !== questionToken
  67906. ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
  67907. : node;
  67908. }
  67909. ts.updateMethodSignature = updateMethodSignature;
  67910. function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
  67911. var node = createSynthesizedNode(161 /* MethodDeclaration */);
  67912. node.decorators = asNodeArray(decorators);
  67913. node.modifiers = asNodeArray(modifiers);
  67914. node.asteriskToken = asteriskToken;
  67915. node.name = asName(name);
  67916. node.questionToken = questionToken;
  67917. node.typeParameters = asNodeArray(typeParameters);
  67918. node.parameters = createNodeArray(parameters);
  67919. node.type = type;
  67920. node.body = body;
  67921. return node;
  67922. }
  67923. ts.createMethod = createMethod;
  67924. function createMethodCall(object, methodName, argumentsList) {
  67925. return createCall(createPropertyAccess(object, asName(methodName)),
  67926. /*typeArguments*/ undefined, argumentsList);
  67927. }
  67928. function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
  67929. return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
  67930. }
  67931. /* @internal */
  67932. function createObjectDefinePropertyCall(target, propertyName, attributes) {
  67933. return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
  67934. }
  67935. ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
  67936. function tryAddPropertyAssignment(properties, propertyName, expression) {
  67937. if (expression) {
  67938. properties.push(createPropertyAssignment(propertyName, expression));
  67939. return true;
  67940. }
  67941. return false;
  67942. }
  67943. /* @internal */
  67944. function createPropertyDescriptor(attributes, singleLine) {
  67945. var properties = [];
  67946. tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
  67947. tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
  67948. var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
  67949. isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
  67950. var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
  67951. isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
  67952. ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
  67953. return createObjectLiteral(properties, !singleLine);
  67954. }
  67955. ts.createPropertyDescriptor = createPropertyDescriptor;
  67956. function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
  67957. return node.decorators !== decorators
  67958. || node.modifiers !== modifiers
  67959. || node.asteriskToken !== asteriskToken
  67960. || node.name !== name
  67961. || node.questionToken !== questionToken
  67962. || node.typeParameters !== typeParameters
  67963. || node.parameters !== parameters
  67964. || node.type !== type
  67965. || node.body !== body
  67966. ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
  67967. : node;
  67968. }
  67969. ts.updateMethod = updateMethod;
  67970. function createConstructor(decorators, modifiers, parameters, body) {
  67971. var node = createSynthesizedNode(162 /* Constructor */);
  67972. node.decorators = asNodeArray(decorators);
  67973. node.modifiers = asNodeArray(modifiers);
  67974. node.typeParameters = undefined;
  67975. node.parameters = createNodeArray(parameters);
  67976. node.type = undefined;
  67977. node.body = body;
  67978. return node;
  67979. }
  67980. ts.createConstructor = createConstructor;
  67981. function updateConstructor(node, decorators, modifiers, parameters, body) {
  67982. return node.decorators !== decorators
  67983. || node.modifiers !== modifiers
  67984. || node.parameters !== parameters
  67985. || node.body !== body
  67986. ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
  67987. : node;
  67988. }
  67989. ts.updateConstructor = updateConstructor;
  67990. function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
  67991. var node = createSynthesizedNode(163 /* GetAccessor */);
  67992. node.decorators = asNodeArray(decorators);
  67993. node.modifiers = asNodeArray(modifiers);
  67994. node.name = asName(name);
  67995. node.typeParameters = undefined;
  67996. node.parameters = createNodeArray(parameters);
  67997. node.type = type;
  67998. node.body = body;
  67999. return node;
  68000. }
  68001. ts.createGetAccessor = createGetAccessor;
  68002. function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
  68003. return node.decorators !== decorators
  68004. || node.modifiers !== modifiers
  68005. || node.name !== name
  68006. || node.parameters !== parameters
  68007. || node.type !== type
  68008. || node.body !== body
  68009. ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
  68010. : node;
  68011. }
  68012. ts.updateGetAccessor = updateGetAccessor;
  68013. function createSetAccessor(decorators, modifiers, name, parameters, body) {
  68014. var node = createSynthesizedNode(164 /* SetAccessor */);
  68015. node.decorators = asNodeArray(decorators);
  68016. node.modifiers = asNodeArray(modifiers);
  68017. node.name = asName(name);
  68018. node.typeParameters = undefined;
  68019. node.parameters = createNodeArray(parameters);
  68020. node.body = body;
  68021. return node;
  68022. }
  68023. ts.createSetAccessor = createSetAccessor;
  68024. function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
  68025. return node.decorators !== decorators
  68026. || node.modifiers !== modifiers
  68027. || node.name !== name
  68028. || node.parameters !== parameters
  68029. || node.body !== body
  68030. ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
  68031. : node;
  68032. }
  68033. ts.updateSetAccessor = updateSetAccessor;
  68034. function createCallSignature(typeParameters, parameters, type) {
  68035. return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
  68036. }
  68037. ts.createCallSignature = createCallSignature;
  68038. function updateCallSignature(node, typeParameters, parameters, type) {
  68039. return updateSignatureDeclaration(node, typeParameters, parameters, type);
  68040. }
  68041. ts.updateCallSignature = updateCallSignature;
  68042. function createConstructSignature(typeParameters, parameters, type) {
  68043. return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
  68044. }
  68045. ts.createConstructSignature = createConstructSignature;
  68046. function updateConstructSignature(node, typeParameters, parameters, type) {
  68047. return updateSignatureDeclaration(node, typeParameters, parameters, type);
  68048. }
  68049. ts.updateConstructSignature = updateConstructSignature;
  68050. function createIndexSignature(decorators, modifiers, parameters, type) {
  68051. var node = createSynthesizedNode(167 /* IndexSignature */);
  68052. node.decorators = asNodeArray(decorators);
  68053. node.modifiers = asNodeArray(modifiers);
  68054. node.parameters = createNodeArray(parameters);
  68055. node.type = type;
  68056. return node;
  68057. }
  68058. ts.createIndexSignature = createIndexSignature;
  68059. function updateIndexSignature(node, decorators, modifiers, parameters, type) {
  68060. return node.parameters !== parameters
  68061. || node.type !== type
  68062. || node.decorators !== decorators
  68063. || node.modifiers !== modifiers
  68064. ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
  68065. : node;
  68066. }
  68067. ts.updateIndexSignature = updateIndexSignature;
  68068. /* @internal */
  68069. function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
  68070. var node = createSynthesizedNode(kind);
  68071. node.typeParameters = asNodeArray(typeParameters);
  68072. node.parameters = asNodeArray(parameters);
  68073. node.type = type;
  68074. node.typeArguments = asNodeArray(typeArguments);
  68075. return node;
  68076. }
  68077. ts.createSignatureDeclaration = createSignatureDeclaration;
  68078. function updateSignatureDeclaration(node, typeParameters, parameters, type) {
  68079. return node.typeParameters !== typeParameters
  68080. || node.parameters !== parameters
  68081. || node.type !== type
  68082. ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
  68083. : node;
  68084. }
  68085. // Types
  68086. function createKeywordTypeNode(kind) {
  68087. return createSynthesizedNode(kind);
  68088. }
  68089. ts.createKeywordTypeNode = createKeywordTypeNode;
  68090. function createTypePredicateNode(parameterName, type) {
  68091. return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
  68092. }
  68093. ts.createTypePredicateNode = createTypePredicateNode;
  68094. function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
  68095. var node = createSynthesizedNode(168 /* TypePredicate */);
  68096. node.assertsModifier = assertsModifier;
  68097. node.parameterName = asName(parameterName);
  68098. node.type = type;
  68099. return node;
  68100. }
  68101. ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
  68102. function updateTypePredicateNode(node, parameterName, type) {
  68103. return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
  68104. }
  68105. ts.updateTypePredicateNode = updateTypePredicateNode;
  68106. function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
  68107. return node.assertsModifier !== assertsModifier
  68108. || node.parameterName !== parameterName
  68109. || node.type !== type
  68110. ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
  68111. : node;
  68112. }
  68113. ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
  68114. function createTypeReferenceNode(typeName, typeArguments) {
  68115. var node = createSynthesizedNode(169 /* TypeReference */);
  68116. node.typeName = asName(typeName);
  68117. node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
  68118. return node;
  68119. }
  68120. ts.createTypeReferenceNode = createTypeReferenceNode;
  68121. function updateTypeReferenceNode(node, typeName, typeArguments) {
  68122. return node.typeName !== typeName
  68123. || node.typeArguments !== typeArguments
  68124. ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
  68125. : node;
  68126. }
  68127. ts.updateTypeReferenceNode = updateTypeReferenceNode;
  68128. function createFunctionTypeNode(typeParameters, parameters, type) {
  68129. return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
  68130. }
  68131. ts.createFunctionTypeNode = createFunctionTypeNode;
  68132. function updateFunctionTypeNode(node, typeParameters, parameters, type) {
  68133. return updateSignatureDeclaration(node, typeParameters, parameters, type);
  68134. }
  68135. ts.updateFunctionTypeNode = updateFunctionTypeNode;
  68136. function createConstructorTypeNode(typeParameters, parameters, type) {
  68137. return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
  68138. }
  68139. ts.createConstructorTypeNode = createConstructorTypeNode;
  68140. function updateConstructorTypeNode(node, typeParameters, parameters, type) {
  68141. return updateSignatureDeclaration(node, typeParameters, parameters, type);
  68142. }
  68143. ts.updateConstructorTypeNode = updateConstructorTypeNode;
  68144. function createTypeQueryNode(exprName) {
  68145. var node = createSynthesizedNode(172 /* TypeQuery */);
  68146. node.exprName = exprName;
  68147. return node;
  68148. }
  68149. ts.createTypeQueryNode = createTypeQueryNode;
  68150. function updateTypeQueryNode(node, exprName) {
  68151. return node.exprName !== exprName
  68152. ? updateNode(createTypeQueryNode(exprName), node)
  68153. : node;
  68154. }
  68155. ts.updateTypeQueryNode = updateTypeQueryNode;
  68156. function createTypeLiteralNode(members) {
  68157. var node = createSynthesizedNode(173 /* TypeLiteral */);
  68158. node.members = createNodeArray(members);
  68159. return node;
  68160. }
  68161. ts.createTypeLiteralNode = createTypeLiteralNode;
  68162. function updateTypeLiteralNode(node, members) {
  68163. return node.members !== members
  68164. ? updateNode(createTypeLiteralNode(members), node)
  68165. : node;
  68166. }
  68167. ts.updateTypeLiteralNode = updateTypeLiteralNode;
  68168. function createArrayTypeNode(elementType) {
  68169. var node = createSynthesizedNode(174 /* ArrayType */);
  68170. node.elementType = ts.parenthesizeArrayTypeMember(elementType);
  68171. return node;
  68172. }
  68173. ts.createArrayTypeNode = createArrayTypeNode;
  68174. function updateArrayTypeNode(node, elementType) {
  68175. return node.elementType !== elementType
  68176. ? updateNode(createArrayTypeNode(elementType), node)
  68177. : node;
  68178. }
  68179. ts.updateArrayTypeNode = updateArrayTypeNode;
  68180. function createTupleTypeNode(elementTypes) {
  68181. var node = createSynthesizedNode(175 /* TupleType */);
  68182. node.elementTypes = createNodeArray(elementTypes);
  68183. return node;
  68184. }
  68185. ts.createTupleTypeNode = createTupleTypeNode;
  68186. function updateTupleTypeNode(node, elementTypes) {
  68187. return node.elementTypes !== elementTypes
  68188. ? updateNode(createTupleTypeNode(elementTypes), node)
  68189. : node;
  68190. }
  68191. ts.updateTupleTypeNode = updateTupleTypeNode;
  68192. function createOptionalTypeNode(type) {
  68193. var node = createSynthesizedNode(176 /* OptionalType */);
  68194. node.type = ts.parenthesizeArrayTypeMember(type);
  68195. return node;
  68196. }
  68197. ts.createOptionalTypeNode = createOptionalTypeNode;
  68198. function updateOptionalTypeNode(node, type) {
  68199. return node.type !== type
  68200. ? updateNode(createOptionalTypeNode(type), node)
  68201. : node;
  68202. }
  68203. ts.updateOptionalTypeNode = updateOptionalTypeNode;
  68204. function createRestTypeNode(type) {
  68205. var node = createSynthesizedNode(177 /* RestType */);
  68206. node.type = type;
  68207. return node;
  68208. }
  68209. ts.createRestTypeNode = createRestTypeNode;
  68210. function updateRestTypeNode(node, type) {
  68211. return node.type !== type
  68212. ? updateNode(createRestTypeNode(type), node)
  68213. : node;
  68214. }
  68215. ts.updateRestTypeNode = updateRestTypeNode;
  68216. function createUnionTypeNode(types) {
  68217. return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
  68218. }
  68219. ts.createUnionTypeNode = createUnionTypeNode;
  68220. function updateUnionTypeNode(node, types) {
  68221. return updateUnionOrIntersectionTypeNode(node, types);
  68222. }
  68223. ts.updateUnionTypeNode = updateUnionTypeNode;
  68224. function createIntersectionTypeNode(types) {
  68225. return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
  68226. }
  68227. ts.createIntersectionTypeNode = createIntersectionTypeNode;
  68228. function updateIntersectionTypeNode(node, types) {
  68229. return updateUnionOrIntersectionTypeNode(node, types);
  68230. }
  68231. ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
  68232. function createUnionOrIntersectionTypeNode(kind, types) {
  68233. var node = createSynthesizedNode(kind);
  68234. node.types = ts.parenthesizeElementTypeMembers(types);
  68235. return node;
  68236. }
  68237. ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
  68238. function updateUnionOrIntersectionTypeNode(node, types) {
  68239. return node.types !== types
  68240. ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
  68241. : node;
  68242. }
  68243. function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
  68244. var node = createSynthesizedNode(180 /* ConditionalType */);
  68245. node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
  68246. node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
  68247. node.trueType = trueType;
  68248. node.falseType = falseType;
  68249. return node;
  68250. }
  68251. ts.createConditionalTypeNode = createConditionalTypeNode;
  68252. function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
  68253. return node.checkType !== checkType
  68254. || node.extendsType !== extendsType
  68255. || node.trueType !== trueType
  68256. || node.falseType !== falseType
  68257. ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
  68258. : node;
  68259. }
  68260. ts.updateConditionalTypeNode = updateConditionalTypeNode;
  68261. function createInferTypeNode(typeParameter) {
  68262. var node = createSynthesizedNode(181 /* InferType */);
  68263. node.typeParameter = typeParameter;
  68264. return node;
  68265. }
  68266. ts.createInferTypeNode = createInferTypeNode;
  68267. function updateInferTypeNode(node, typeParameter) {
  68268. return node.typeParameter !== typeParameter
  68269. ? updateNode(createInferTypeNode(typeParameter), node)
  68270. : node;
  68271. }
  68272. ts.updateInferTypeNode = updateInferTypeNode;
  68273. function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
  68274. var node = createSynthesizedNode(188 /* ImportType */);
  68275. node.argument = argument;
  68276. node.qualifier = qualifier;
  68277. node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
  68278. node.isTypeOf = isTypeOf;
  68279. return node;
  68280. }
  68281. ts.createImportTypeNode = createImportTypeNode;
  68282. function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
  68283. return node.argument !== argument
  68284. || node.qualifier !== qualifier
  68285. || node.typeArguments !== typeArguments
  68286. || node.isTypeOf !== isTypeOf
  68287. ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
  68288. : node;
  68289. }
  68290. ts.updateImportTypeNode = updateImportTypeNode;
  68291. function createParenthesizedType(type) {
  68292. var node = createSynthesizedNode(182 /* ParenthesizedType */);
  68293. node.type = type;
  68294. return node;
  68295. }
  68296. ts.createParenthesizedType = createParenthesizedType;
  68297. function updateParenthesizedType(node, type) {
  68298. return node.type !== type
  68299. ? updateNode(createParenthesizedType(type), node)
  68300. : node;
  68301. }
  68302. ts.updateParenthesizedType = updateParenthesizedType;
  68303. function createThisTypeNode() {
  68304. return createSynthesizedNode(183 /* ThisType */);
  68305. }
  68306. ts.createThisTypeNode = createThisTypeNode;
  68307. function createTypeOperatorNode(operatorOrType, type) {
  68308. var node = createSynthesizedNode(184 /* TypeOperator */);
  68309. node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
  68310. node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
  68311. return node;
  68312. }
  68313. ts.createTypeOperatorNode = createTypeOperatorNode;
  68314. function updateTypeOperatorNode(node, type) {
  68315. return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
  68316. }
  68317. ts.updateTypeOperatorNode = updateTypeOperatorNode;
  68318. function createIndexedAccessTypeNode(objectType, indexType) {
  68319. var node = createSynthesizedNode(185 /* IndexedAccessType */);
  68320. node.objectType = ts.parenthesizeElementTypeMember(objectType);
  68321. node.indexType = indexType;
  68322. return node;
  68323. }
  68324. ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
  68325. function updateIndexedAccessTypeNode(node, objectType, indexType) {
  68326. return node.objectType !== objectType
  68327. || node.indexType !== indexType
  68328. ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
  68329. : node;
  68330. }
  68331. ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
  68332. function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
  68333. var node = createSynthesizedNode(186 /* MappedType */);
  68334. node.readonlyToken = readonlyToken;
  68335. node.typeParameter = typeParameter;
  68336. node.questionToken = questionToken;
  68337. node.type = type;
  68338. return node;
  68339. }
  68340. ts.createMappedTypeNode = createMappedTypeNode;
  68341. function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
  68342. return node.readonlyToken !== readonlyToken
  68343. || node.typeParameter !== typeParameter
  68344. || node.questionToken !== questionToken
  68345. || node.type !== type
  68346. ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
  68347. : node;
  68348. }
  68349. ts.updateMappedTypeNode = updateMappedTypeNode;
  68350. function createLiteralTypeNode(literal) {
  68351. var node = createSynthesizedNode(187 /* LiteralType */);
  68352. node.literal = literal;
  68353. return node;
  68354. }
  68355. ts.createLiteralTypeNode = createLiteralTypeNode;
  68356. function updateLiteralTypeNode(node, literal) {
  68357. return node.literal !== literal
  68358. ? updateNode(createLiteralTypeNode(literal), node)
  68359. : node;
  68360. }
  68361. ts.updateLiteralTypeNode = updateLiteralTypeNode;
  68362. // Binding Patterns
  68363. function createObjectBindingPattern(elements) {
  68364. var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
  68365. node.elements = createNodeArray(elements);
  68366. return node;
  68367. }
  68368. ts.createObjectBindingPattern = createObjectBindingPattern;
  68369. function updateObjectBindingPattern(node, elements) {
  68370. return node.elements !== elements
  68371. ? updateNode(createObjectBindingPattern(elements), node)
  68372. : node;
  68373. }
  68374. ts.updateObjectBindingPattern = updateObjectBindingPattern;
  68375. function createArrayBindingPattern(elements) {
  68376. var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
  68377. node.elements = createNodeArray(elements);
  68378. return node;
  68379. }
  68380. ts.createArrayBindingPattern = createArrayBindingPattern;
  68381. function updateArrayBindingPattern(node, elements) {
  68382. return node.elements !== elements
  68383. ? updateNode(createArrayBindingPattern(elements), node)
  68384. : node;
  68385. }
  68386. ts.updateArrayBindingPattern = updateArrayBindingPattern;
  68387. function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
  68388. var node = createSynthesizedNode(191 /* BindingElement */);
  68389. node.dotDotDotToken = dotDotDotToken;
  68390. node.propertyName = asName(propertyName);
  68391. node.name = asName(name);
  68392. node.initializer = initializer;
  68393. return node;
  68394. }
  68395. ts.createBindingElement = createBindingElement;
  68396. function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
  68397. return node.propertyName !== propertyName
  68398. || node.dotDotDotToken !== dotDotDotToken
  68399. || node.name !== name
  68400. || node.initializer !== initializer
  68401. ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
  68402. : node;
  68403. }
  68404. ts.updateBindingElement = updateBindingElement;
  68405. // Expression
  68406. function createArrayLiteral(elements, multiLine) {
  68407. var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
  68408. node.elements = ts.parenthesizeListElements(createNodeArray(elements));
  68409. if (multiLine)
  68410. node.multiLine = true;
  68411. return node;
  68412. }
  68413. ts.createArrayLiteral = createArrayLiteral;
  68414. function updateArrayLiteral(node, elements) {
  68415. return node.elements !== elements
  68416. ? updateNode(createArrayLiteral(elements, node.multiLine), node)
  68417. : node;
  68418. }
  68419. ts.updateArrayLiteral = updateArrayLiteral;
  68420. function createObjectLiteral(properties, multiLine) {
  68421. var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
  68422. node.properties = createNodeArray(properties);
  68423. if (multiLine)
  68424. node.multiLine = true;
  68425. return node;
  68426. }
  68427. ts.createObjectLiteral = createObjectLiteral;
  68428. function updateObjectLiteral(node, properties) {
  68429. return node.properties !== properties
  68430. ? updateNode(createObjectLiteral(properties, node.multiLine), node)
  68431. : node;
  68432. }
  68433. ts.updateObjectLiteral = updateObjectLiteral;
  68434. function createPropertyAccess(expression, name) {
  68435. var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
  68436. node.expression = ts.parenthesizeForAccess(expression);
  68437. node.name = asName(name);
  68438. setEmitFlags(node, 131072 /* NoIndentation */);
  68439. return node;
  68440. }
  68441. ts.createPropertyAccess = createPropertyAccess;
  68442. function updatePropertyAccess(node, expression, name) {
  68443. if (ts.isOptionalChain(node) && ts.isIdentifier(node.name) && ts.isIdentifier(name)) {
  68444. // Not sure why this cast was necessary: the previous line should already establish that node.name is an identifier
  68445. var theNode = node;
  68446. return updatePropertyAccessChain(theNode, expression, node.questionDotToken, name);
  68447. }
  68448. // Because we are updating existed propertyAccess we want to inherit its emitFlags
  68449. // instead of using the default from createPropertyAccess
  68450. return node.expression !== expression
  68451. || node.name !== name
  68452. ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
  68453. : node;
  68454. }
  68455. ts.updatePropertyAccess = updatePropertyAccess;
  68456. function createPropertyAccessChain(expression, questionDotToken, name) {
  68457. var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
  68458. node.flags |= 32 /* OptionalChain */;
  68459. node.expression = ts.parenthesizeForAccess(expression);
  68460. node.questionDotToken = questionDotToken;
  68461. node.name = asName(name);
  68462. setEmitFlags(node, 131072 /* NoIndentation */);
  68463. return node;
  68464. }
  68465. ts.createPropertyAccessChain = createPropertyAccessChain;
  68466. function updatePropertyAccessChain(node, expression, questionDotToken, name) {
  68467. ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
  68468. // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
  68469. // instead of using the default from createPropertyAccess
  68470. return node.expression !== expression
  68471. || node.questionDotToken !== questionDotToken
  68472. || node.name !== name
  68473. ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
  68474. : node;
  68475. }
  68476. ts.updatePropertyAccessChain = updatePropertyAccessChain;
  68477. function createElementAccess(expression, index) {
  68478. var node = createSynthesizedNode(195 /* ElementAccessExpression */);
  68479. node.expression = ts.parenthesizeForAccess(expression);
  68480. node.argumentExpression = asExpression(index);
  68481. return node;
  68482. }
  68483. ts.createElementAccess = createElementAccess;
  68484. function updateElementAccess(node, expression, argumentExpression) {
  68485. if (ts.isOptionalChain(node)) {
  68486. return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
  68487. }
  68488. return node.expression !== expression
  68489. || node.argumentExpression !== argumentExpression
  68490. ? updateNode(createElementAccess(expression, argumentExpression), node)
  68491. : node;
  68492. }
  68493. ts.updateElementAccess = updateElementAccess;
  68494. function createElementAccessChain(expression, questionDotToken, index) {
  68495. var node = createSynthesizedNode(195 /* ElementAccessExpression */);
  68496. node.flags |= 32 /* OptionalChain */;
  68497. node.expression = ts.parenthesizeForAccess(expression);
  68498. node.questionDotToken = questionDotToken;
  68499. node.argumentExpression = asExpression(index);
  68500. return node;
  68501. }
  68502. ts.createElementAccessChain = createElementAccessChain;
  68503. function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
  68504. ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
  68505. return node.expression !== expression
  68506. || node.questionDotToken !== questionDotToken
  68507. || node.argumentExpression !== argumentExpression
  68508. ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
  68509. : node;
  68510. }
  68511. ts.updateElementAccessChain = updateElementAccessChain;
  68512. function createCall(expression, typeArguments, argumentsArray) {
  68513. var node = createSynthesizedNode(196 /* CallExpression */);
  68514. node.expression = ts.parenthesizeForAccess(expression);
  68515. node.typeArguments = asNodeArray(typeArguments);
  68516. node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
  68517. return node;
  68518. }
  68519. ts.createCall = createCall;
  68520. function updateCall(node, expression, typeArguments, argumentsArray) {
  68521. if (ts.isOptionalChain(node)) {
  68522. return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
  68523. }
  68524. return node.expression !== expression
  68525. || node.typeArguments !== typeArguments
  68526. || node.arguments !== argumentsArray
  68527. ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
  68528. : node;
  68529. }
  68530. ts.updateCall = updateCall;
  68531. function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
  68532. var node = createSynthesizedNode(196 /* CallExpression */);
  68533. node.flags |= 32 /* OptionalChain */;
  68534. node.expression = ts.parenthesizeForAccess(expression);
  68535. node.questionDotToken = questionDotToken;
  68536. node.typeArguments = asNodeArray(typeArguments);
  68537. node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
  68538. return node;
  68539. }
  68540. ts.createCallChain = createCallChain;
  68541. function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
  68542. ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
  68543. return node.expression !== expression
  68544. || node.questionDotToken !== questionDotToken
  68545. || node.typeArguments !== typeArguments
  68546. || node.arguments !== argumentsArray
  68547. ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
  68548. : node;
  68549. }
  68550. ts.updateCallChain = updateCallChain;
  68551. function createNew(expression, typeArguments, argumentsArray) {
  68552. var node = createSynthesizedNode(197 /* NewExpression */);
  68553. node.expression = ts.parenthesizeForNew(expression);
  68554. node.typeArguments = asNodeArray(typeArguments);
  68555. node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
  68556. return node;
  68557. }
  68558. ts.createNew = createNew;
  68559. function updateNew(node, expression, typeArguments, argumentsArray) {
  68560. return node.expression !== expression
  68561. || node.typeArguments !== typeArguments
  68562. || node.arguments !== argumentsArray
  68563. ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
  68564. : node;
  68565. }
  68566. ts.updateNew = updateNew;
  68567. function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
  68568. var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
  68569. node.tag = ts.parenthesizeForAccess(tag);
  68570. if (template) {
  68571. node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
  68572. node.template = template;
  68573. }
  68574. else {
  68575. node.typeArguments = undefined;
  68576. node.template = typeArgumentsOrTemplate;
  68577. }
  68578. return node;
  68579. }
  68580. ts.createTaggedTemplate = createTaggedTemplate;
  68581. function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
  68582. return node.tag !== tag
  68583. || (template
  68584. ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
  68585. : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
  68586. ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
  68587. : node;
  68588. }
  68589. ts.updateTaggedTemplate = updateTaggedTemplate;
  68590. function createTypeAssertion(type, expression) {
  68591. var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
  68592. node.type = type;
  68593. node.expression = ts.parenthesizePrefixOperand(expression);
  68594. return node;
  68595. }
  68596. ts.createTypeAssertion = createTypeAssertion;
  68597. function updateTypeAssertion(node, type, expression) {
  68598. return node.type !== type
  68599. || node.expression !== expression
  68600. ? updateNode(createTypeAssertion(type, expression), node)
  68601. : node;
  68602. }
  68603. ts.updateTypeAssertion = updateTypeAssertion;
  68604. function createParen(expression) {
  68605. var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
  68606. node.expression = expression;
  68607. return node;
  68608. }
  68609. ts.createParen = createParen;
  68610. function updateParen(node, expression) {
  68611. return node.expression !== expression
  68612. ? updateNode(createParen(expression), node)
  68613. : node;
  68614. }
  68615. ts.updateParen = updateParen;
  68616. function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
  68617. var node = createSynthesizedNode(201 /* FunctionExpression */);
  68618. node.modifiers = asNodeArray(modifiers);
  68619. node.asteriskToken = asteriskToken;
  68620. node.name = asName(name);
  68621. node.typeParameters = asNodeArray(typeParameters);
  68622. node.parameters = createNodeArray(parameters);
  68623. node.type = type;
  68624. node.body = body;
  68625. return node;
  68626. }
  68627. ts.createFunctionExpression = createFunctionExpression;
  68628. function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
  68629. return node.name !== name
  68630. || node.modifiers !== modifiers
  68631. || node.asteriskToken !== asteriskToken
  68632. || node.typeParameters !== typeParameters
  68633. || node.parameters !== parameters
  68634. || node.type !== type
  68635. || node.body !== body
  68636. ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
  68637. : node;
  68638. }
  68639. ts.updateFunctionExpression = updateFunctionExpression;
  68640. function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
  68641. var node = createSynthesizedNode(202 /* ArrowFunction */);
  68642. node.modifiers = asNodeArray(modifiers);
  68643. node.typeParameters = asNodeArray(typeParameters);
  68644. node.parameters = createNodeArray(parameters);
  68645. node.type = type;
  68646. node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
  68647. node.body = ts.parenthesizeConciseBody(body);
  68648. return node;
  68649. }
  68650. ts.createArrowFunction = createArrowFunction;
  68651. function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
  68652. return node.modifiers !== modifiers
  68653. || node.typeParameters !== typeParameters
  68654. || node.parameters !== parameters
  68655. || node.type !== type
  68656. || node.equalsGreaterThanToken !== equalsGreaterThanToken
  68657. || node.body !== body
  68658. ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
  68659. : node;
  68660. }
  68661. ts.updateArrowFunction = updateArrowFunction;
  68662. function createDelete(expression) {
  68663. var node = createSynthesizedNode(203 /* DeleteExpression */);
  68664. node.expression = ts.parenthesizePrefixOperand(expression);
  68665. return node;
  68666. }
  68667. ts.createDelete = createDelete;
  68668. function updateDelete(node, expression) {
  68669. return node.expression !== expression
  68670. ? updateNode(createDelete(expression), node)
  68671. : node;
  68672. }
  68673. ts.updateDelete = updateDelete;
  68674. function createTypeOf(expression) {
  68675. var node = createSynthesizedNode(204 /* TypeOfExpression */);
  68676. node.expression = ts.parenthesizePrefixOperand(expression);
  68677. return node;
  68678. }
  68679. ts.createTypeOf = createTypeOf;
  68680. function updateTypeOf(node, expression) {
  68681. return node.expression !== expression
  68682. ? updateNode(createTypeOf(expression), node)
  68683. : node;
  68684. }
  68685. ts.updateTypeOf = updateTypeOf;
  68686. function createVoid(expression) {
  68687. var node = createSynthesizedNode(205 /* VoidExpression */);
  68688. node.expression = ts.parenthesizePrefixOperand(expression);
  68689. return node;
  68690. }
  68691. ts.createVoid = createVoid;
  68692. function updateVoid(node, expression) {
  68693. return node.expression !== expression
  68694. ? updateNode(createVoid(expression), node)
  68695. : node;
  68696. }
  68697. ts.updateVoid = updateVoid;
  68698. function createAwait(expression) {
  68699. var node = createSynthesizedNode(206 /* AwaitExpression */);
  68700. node.expression = ts.parenthesizePrefixOperand(expression);
  68701. return node;
  68702. }
  68703. ts.createAwait = createAwait;
  68704. function updateAwait(node, expression) {
  68705. return node.expression !== expression
  68706. ? updateNode(createAwait(expression), node)
  68707. : node;
  68708. }
  68709. ts.updateAwait = updateAwait;
  68710. function createPrefix(operator, operand) {
  68711. var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
  68712. node.operator = operator;
  68713. node.operand = ts.parenthesizePrefixOperand(operand);
  68714. return node;
  68715. }
  68716. ts.createPrefix = createPrefix;
  68717. function updatePrefix(node, operand) {
  68718. return node.operand !== operand
  68719. ? updateNode(createPrefix(node.operator, operand), node)
  68720. : node;
  68721. }
  68722. ts.updatePrefix = updatePrefix;
  68723. function createPostfix(operand, operator) {
  68724. var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
  68725. node.operand = ts.parenthesizePostfixOperand(operand);
  68726. node.operator = operator;
  68727. return node;
  68728. }
  68729. ts.createPostfix = createPostfix;
  68730. function updatePostfix(node, operand) {
  68731. return node.operand !== operand
  68732. ? updateNode(createPostfix(operand, node.operator), node)
  68733. : node;
  68734. }
  68735. ts.updatePostfix = updatePostfix;
  68736. function createBinary(left, operator, right) {
  68737. var node = createSynthesizedNode(209 /* BinaryExpression */);
  68738. var operatorToken = asToken(operator);
  68739. var operatorKind = operatorToken.kind;
  68740. node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
  68741. node.operatorToken = operatorToken;
  68742. node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
  68743. return node;
  68744. }
  68745. ts.createBinary = createBinary;
  68746. function updateBinary(node, left, right, operator) {
  68747. return node.left !== left
  68748. || node.right !== right
  68749. ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
  68750. : node;
  68751. }
  68752. ts.updateBinary = updateBinary;
  68753. function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
  68754. var node = createSynthesizedNode(210 /* ConditionalExpression */);
  68755. node.condition = ts.parenthesizeForConditionalHead(condition);
  68756. node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
  68757. node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
  68758. node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
  68759. node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
  68760. return node;
  68761. }
  68762. ts.createConditional = createConditional;
  68763. function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
  68764. return node.condition !== condition
  68765. || node.questionToken !== questionToken
  68766. || node.whenTrue !== whenTrue
  68767. || node.colonToken !== colonToken
  68768. || node.whenFalse !== whenFalse
  68769. ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
  68770. : node;
  68771. }
  68772. ts.updateConditional = updateConditional;
  68773. function createTemplateExpression(head, templateSpans) {
  68774. var node = createSynthesizedNode(211 /* TemplateExpression */);
  68775. node.head = head;
  68776. node.templateSpans = createNodeArray(templateSpans);
  68777. return node;
  68778. }
  68779. ts.createTemplateExpression = createTemplateExpression;
  68780. function updateTemplateExpression(node, head, templateSpans) {
  68781. return node.head !== head
  68782. || node.templateSpans !== templateSpans
  68783. ? updateNode(createTemplateExpression(head, templateSpans), node)
  68784. : node;
  68785. }
  68786. ts.updateTemplateExpression = updateTemplateExpression;
  68787. var rawTextScanner;
  68788. var invalidValueSentinel = {};
  68789. function getCookedText(kind, rawText) {
  68790. if (!rawTextScanner) {
  68791. rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
  68792. }
  68793. switch (kind) {
  68794. case 14 /* NoSubstitutionTemplateLiteral */:
  68795. rawTextScanner.setText("`" + rawText + "`");
  68796. break;
  68797. case 15 /* TemplateHead */:
  68798. rawTextScanner.setText("`" + rawText + "${");
  68799. break;
  68800. case 16 /* TemplateMiddle */:
  68801. rawTextScanner.setText("}" + rawText + "${");
  68802. break;
  68803. case 17 /* TemplateTail */:
  68804. rawTextScanner.setText("}" + rawText + "`");
  68805. break;
  68806. }
  68807. var token = rawTextScanner.scan();
  68808. if (token === 23 /* CloseBracketToken */) {
  68809. token = rawTextScanner.reScanTemplateToken();
  68810. }
  68811. if (rawTextScanner.isUnterminated()) {
  68812. rawTextScanner.setText(undefined);
  68813. return invalidValueSentinel;
  68814. }
  68815. var tokenValue;
  68816. switch (token) {
  68817. case 14 /* NoSubstitutionTemplateLiteral */:
  68818. case 15 /* TemplateHead */:
  68819. case 16 /* TemplateMiddle */:
  68820. case 17 /* TemplateTail */:
  68821. tokenValue = rawTextScanner.getTokenValue();
  68822. break;
  68823. }
  68824. if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
  68825. rawTextScanner.setText(undefined);
  68826. return invalidValueSentinel;
  68827. }
  68828. rawTextScanner.setText(undefined);
  68829. return tokenValue;
  68830. }
  68831. function createTemplateLiteralLikeNode(kind, text, rawText) {
  68832. var node = createSynthesizedNode(kind);
  68833. node.text = text;
  68834. if (rawText === undefined || text === rawText) {
  68835. node.rawText = rawText;
  68836. }
  68837. else {
  68838. var cooked = getCookedText(kind, rawText);
  68839. if (typeof cooked === "object") {
  68840. return ts.Debug.fail("Invalid raw text");
  68841. }
  68842. ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
  68843. node.rawText = rawText;
  68844. }
  68845. return node;
  68846. }
  68847. function createTemplateHead(text, rawText) {
  68848. var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
  68849. node.text = text;
  68850. return node;
  68851. }
  68852. ts.createTemplateHead = createTemplateHead;
  68853. function createTemplateMiddle(text, rawText) {
  68854. var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
  68855. node.text = text;
  68856. return node;
  68857. }
  68858. ts.createTemplateMiddle = createTemplateMiddle;
  68859. function createTemplateTail(text, rawText) {
  68860. var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
  68861. node.text = text;
  68862. return node;
  68863. }
  68864. ts.createTemplateTail = createTemplateTail;
  68865. function createNoSubstitutionTemplateLiteral(text, rawText) {
  68866. var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
  68867. return node;
  68868. }
  68869. ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
  68870. function createYield(asteriskTokenOrExpression, expression) {
  68871. var node = createSynthesizedNode(212 /* YieldExpression */);
  68872. node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
  68873. node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
  68874. return node;
  68875. }
  68876. ts.createYield = createYield;
  68877. function updateYield(node, asteriskToken, expression) {
  68878. return node.expression !== expression
  68879. || node.asteriskToken !== asteriskToken
  68880. ? updateNode(createYield(asteriskToken, expression), node)
  68881. : node;
  68882. }
  68883. ts.updateYield = updateYield;
  68884. function createSpread(expression) {
  68885. var node = createSynthesizedNode(213 /* SpreadElement */);
  68886. node.expression = ts.parenthesizeExpressionForList(expression);
  68887. return node;
  68888. }
  68889. ts.createSpread = createSpread;
  68890. function updateSpread(node, expression) {
  68891. return node.expression !== expression
  68892. ? updateNode(createSpread(expression), node)
  68893. : node;
  68894. }
  68895. ts.updateSpread = updateSpread;
  68896. function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
  68897. var node = createSynthesizedNode(214 /* ClassExpression */);
  68898. node.decorators = undefined;
  68899. node.modifiers = asNodeArray(modifiers);
  68900. node.name = asName(name);
  68901. node.typeParameters = asNodeArray(typeParameters);
  68902. node.heritageClauses = asNodeArray(heritageClauses);
  68903. node.members = createNodeArray(members);
  68904. return node;
  68905. }
  68906. ts.createClassExpression = createClassExpression;
  68907. function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
  68908. return node.modifiers !== modifiers
  68909. || node.name !== name
  68910. || node.typeParameters !== typeParameters
  68911. || node.heritageClauses !== heritageClauses
  68912. || node.members !== members
  68913. ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
  68914. : node;
  68915. }
  68916. ts.updateClassExpression = updateClassExpression;
  68917. function createOmittedExpression() {
  68918. return createSynthesizedNode(215 /* OmittedExpression */);
  68919. }
  68920. ts.createOmittedExpression = createOmittedExpression;
  68921. function createExpressionWithTypeArguments(typeArguments, expression) {
  68922. var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
  68923. node.expression = ts.parenthesizeForAccess(expression);
  68924. node.typeArguments = asNodeArray(typeArguments);
  68925. return node;
  68926. }
  68927. ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
  68928. function updateExpressionWithTypeArguments(node, typeArguments, expression) {
  68929. return node.typeArguments !== typeArguments
  68930. || node.expression !== expression
  68931. ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
  68932. : node;
  68933. }
  68934. ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
  68935. function createAsExpression(expression, type) {
  68936. var node = createSynthesizedNode(217 /* AsExpression */);
  68937. node.expression = expression;
  68938. node.type = type;
  68939. return node;
  68940. }
  68941. ts.createAsExpression = createAsExpression;
  68942. function updateAsExpression(node, expression, type) {
  68943. return node.expression !== expression
  68944. || node.type !== type
  68945. ? updateNode(createAsExpression(expression, type), node)
  68946. : node;
  68947. }
  68948. ts.updateAsExpression = updateAsExpression;
  68949. function createNonNullExpression(expression) {
  68950. var node = createSynthesizedNode(218 /* NonNullExpression */);
  68951. node.expression = ts.parenthesizeForAccess(expression);
  68952. return node;
  68953. }
  68954. ts.createNonNullExpression = createNonNullExpression;
  68955. function updateNonNullExpression(node, expression) {
  68956. return node.expression !== expression
  68957. ? updateNode(createNonNullExpression(expression), node)
  68958. : node;
  68959. }
  68960. ts.updateNonNullExpression = updateNonNullExpression;
  68961. function createMetaProperty(keywordToken, name) {
  68962. var node = createSynthesizedNode(219 /* MetaProperty */);
  68963. node.keywordToken = keywordToken;
  68964. node.name = name;
  68965. return node;
  68966. }
  68967. ts.createMetaProperty = createMetaProperty;
  68968. function updateMetaProperty(node, name) {
  68969. return node.name !== name
  68970. ? updateNode(createMetaProperty(node.keywordToken, name), node)
  68971. : node;
  68972. }
  68973. ts.updateMetaProperty = updateMetaProperty;
  68974. // Misc
  68975. function createTemplateSpan(expression, literal) {
  68976. var node = createSynthesizedNode(221 /* TemplateSpan */);
  68977. node.expression = expression;
  68978. node.literal = literal;
  68979. return node;
  68980. }
  68981. ts.createTemplateSpan = createTemplateSpan;
  68982. function updateTemplateSpan(node, expression, literal) {
  68983. return node.expression !== expression
  68984. || node.literal !== literal
  68985. ? updateNode(createTemplateSpan(expression, literal), node)
  68986. : node;
  68987. }
  68988. ts.updateTemplateSpan = updateTemplateSpan;
  68989. function createSemicolonClassElement() {
  68990. return createSynthesizedNode(222 /* SemicolonClassElement */);
  68991. }
  68992. ts.createSemicolonClassElement = createSemicolonClassElement;
  68993. // Element
  68994. function createBlock(statements, multiLine) {
  68995. var block = createSynthesizedNode(223 /* Block */);
  68996. block.statements = createNodeArray(statements);
  68997. if (multiLine)
  68998. block.multiLine = multiLine;
  68999. return block;
  69000. }
  69001. ts.createBlock = createBlock;
  69002. function updateBlock(node, statements) {
  69003. return node.statements !== statements
  69004. ? updateNode(createBlock(statements, node.multiLine), node)
  69005. : node;
  69006. }
  69007. ts.updateBlock = updateBlock;
  69008. function createVariableStatement(modifiers, declarationList) {
  69009. var node = createSynthesizedNode(225 /* VariableStatement */);
  69010. node.decorators = undefined;
  69011. node.modifiers = asNodeArray(modifiers);
  69012. node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
  69013. return node;
  69014. }
  69015. ts.createVariableStatement = createVariableStatement;
  69016. function updateVariableStatement(node, modifiers, declarationList) {
  69017. return node.modifiers !== modifiers
  69018. || node.declarationList !== declarationList
  69019. ? updateNode(createVariableStatement(modifiers, declarationList), node)
  69020. : node;
  69021. }
  69022. ts.updateVariableStatement = updateVariableStatement;
  69023. function createEmptyStatement() {
  69024. return createSynthesizedNode(224 /* EmptyStatement */);
  69025. }
  69026. ts.createEmptyStatement = createEmptyStatement;
  69027. function createExpressionStatement(expression) {
  69028. var node = createSynthesizedNode(226 /* ExpressionStatement */);
  69029. node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
  69030. return node;
  69031. }
  69032. ts.createExpressionStatement = createExpressionStatement;
  69033. function updateExpressionStatement(node, expression) {
  69034. return node.expression !== expression
  69035. ? updateNode(createExpressionStatement(expression), node)
  69036. : node;
  69037. }
  69038. ts.updateExpressionStatement = updateExpressionStatement;
  69039. /** @deprecated Use `createExpressionStatement` instead. */
  69040. ts.createStatement = createExpressionStatement;
  69041. /** @deprecated Use `updateExpressionStatement` instead. */
  69042. ts.updateStatement = updateExpressionStatement;
  69043. function createIf(expression, thenStatement, elseStatement) {
  69044. var node = createSynthesizedNode(227 /* IfStatement */);
  69045. node.expression = expression;
  69046. node.thenStatement = asEmbeddedStatement(thenStatement);
  69047. node.elseStatement = asEmbeddedStatement(elseStatement);
  69048. return node;
  69049. }
  69050. ts.createIf = createIf;
  69051. function updateIf(node, expression, thenStatement, elseStatement) {
  69052. return node.expression !== expression
  69053. || node.thenStatement !== thenStatement
  69054. || node.elseStatement !== elseStatement
  69055. ? updateNode(createIf(expression, thenStatement, elseStatement), node)
  69056. : node;
  69057. }
  69058. ts.updateIf = updateIf;
  69059. function createDo(statement, expression) {
  69060. var node = createSynthesizedNode(228 /* DoStatement */);
  69061. node.statement = asEmbeddedStatement(statement);
  69062. node.expression = expression;
  69063. return node;
  69064. }
  69065. ts.createDo = createDo;
  69066. function updateDo(node, statement, expression) {
  69067. return node.statement !== statement
  69068. || node.expression !== expression
  69069. ? updateNode(createDo(statement, expression), node)
  69070. : node;
  69071. }
  69072. ts.updateDo = updateDo;
  69073. function createWhile(expression, statement) {
  69074. var node = createSynthesizedNode(229 /* WhileStatement */);
  69075. node.expression = expression;
  69076. node.statement = asEmbeddedStatement(statement);
  69077. return node;
  69078. }
  69079. ts.createWhile = createWhile;
  69080. function updateWhile(node, expression, statement) {
  69081. return node.expression !== expression
  69082. || node.statement !== statement
  69083. ? updateNode(createWhile(expression, statement), node)
  69084. : node;
  69085. }
  69086. ts.updateWhile = updateWhile;
  69087. function createFor(initializer, condition, incrementor, statement) {
  69088. var node = createSynthesizedNode(230 /* ForStatement */);
  69089. node.initializer = initializer;
  69090. node.condition = condition;
  69091. node.incrementor = incrementor;
  69092. node.statement = asEmbeddedStatement(statement);
  69093. return node;
  69094. }
  69095. ts.createFor = createFor;
  69096. function updateFor(node, initializer, condition, incrementor, statement) {
  69097. return node.initializer !== initializer
  69098. || node.condition !== condition
  69099. || node.incrementor !== incrementor
  69100. || node.statement !== statement
  69101. ? updateNode(createFor(initializer, condition, incrementor, statement), node)
  69102. : node;
  69103. }
  69104. ts.updateFor = updateFor;
  69105. function createForIn(initializer, expression, statement) {
  69106. var node = createSynthesizedNode(231 /* ForInStatement */);
  69107. node.initializer = initializer;
  69108. node.expression = expression;
  69109. node.statement = asEmbeddedStatement(statement);
  69110. return node;
  69111. }
  69112. ts.createForIn = createForIn;
  69113. function updateForIn(node, initializer, expression, statement) {
  69114. return node.initializer !== initializer
  69115. || node.expression !== expression
  69116. || node.statement !== statement
  69117. ? updateNode(createForIn(initializer, expression, statement), node)
  69118. : node;
  69119. }
  69120. ts.updateForIn = updateForIn;
  69121. function createForOf(awaitModifier, initializer, expression, statement) {
  69122. var node = createSynthesizedNode(232 /* ForOfStatement */);
  69123. node.awaitModifier = awaitModifier;
  69124. node.initializer = initializer;
  69125. node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
  69126. node.statement = asEmbeddedStatement(statement);
  69127. return node;
  69128. }
  69129. ts.createForOf = createForOf;
  69130. function updateForOf(node, awaitModifier, initializer, expression, statement) {
  69131. return node.awaitModifier !== awaitModifier
  69132. || node.initializer !== initializer
  69133. || node.expression !== expression
  69134. || node.statement !== statement
  69135. ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
  69136. : node;
  69137. }
  69138. ts.updateForOf = updateForOf;
  69139. function createContinue(label) {
  69140. var node = createSynthesizedNode(233 /* ContinueStatement */);
  69141. node.label = asName(label);
  69142. return node;
  69143. }
  69144. ts.createContinue = createContinue;
  69145. function updateContinue(node, label) {
  69146. return node.label !== label
  69147. ? updateNode(createContinue(label), node)
  69148. : node;
  69149. }
  69150. ts.updateContinue = updateContinue;
  69151. function createBreak(label) {
  69152. var node = createSynthesizedNode(234 /* BreakStatement */);
  69153. node.label = asName(label);
  69154. return node;
  69155. }
  69156. ts.createBreak = createBreak;
  69157. function updateBreak(node, label) {
  69158. return node.label !== label
  69159. ? updateNode(createBreak(label), node)
  69160. : node;
  69161. }
  69162. ts.updateBreak = updateBreak;
  69163. function createReturn(expression) {
  69164. var node = createSynthesizedNode(235 /* ReturnStatement */);
  69165. node.expression = expression;
  69166. return node;
  69167. }
  69168. ts.createReturn = createReturn;
  69169. function updateReturn(node, expression) {
  69170. return node.expression !== expression
  69171. ? updateNode(createReturn(expression), node)
  69172. : node;
  69173. }
  69174. ts.updateReturn = updateReturn;
  69175. function createWith(expression, statement) {
  69176. var node = createSynthesizedNode(236 /* WithStatement */);
  69177. node.expression = expression;
  69178. node.statement = asEmbeddedStatement(statement);
  69179. return node;
  69180. }
  69181. ts.createWith = createWith;
  69182. function updateWith(node, expression, statement) {
  69183. return node.expression !== expression
  69184. || node.statement !== statement
  69185. ? updateNode(createWith(expression, statement), node)
  69186. : node;
  69187. }
  69188. ts.updateWith = updateWith;
  69189. function createSwitch(expression, caseBlock) {
  69190. var node = createSynthesizedNode(237 /* SwitchStatement */);
  69191. node.expression = ts.parenthesizeExpressionForList(expression);
  69192. node.caseBlock = caseBlock;
  69193. return node;
  69194. }
  69195. ts.createSwitch = createSwitch;
  69196. function updateSwitch(node, expression, caseBlock) {
  69197. return node.expression !== expression
  69198. || node.caseBlock !== caseBlock
  69199. ? updateNode(createSwitch(expression, caseBlock), node)
  69200. : node;
  69201. }
  69202. ts.updateSwitch = updateSwitch;
  69203. function createLabel(label, statement) {
  69204. var node = createSynthesizedNode(238 /* LabeledStatement */);
  69205. node.label = asName(label);
  69206. node.statement = asEmbeddedStatement(statement);
  69207. return node;
  69208. }
  69209. ts.createLabel = createLabel;
  69210. function updateLabel(node, label, statement) {
  69211. return node.label !== label
  69212. || node.statement !== statement
  69213. ? updateNode(createLabel(label, statement), node)
  69214. : node;
  69215. }
  69216. ts.updateLabel = updateLabel;
  69217. function createThrow(expression) {
  69218. var node = createSynthesizedNode(239 /* ThrowStatement */);
  69219. node.expression = expression;
  69220. return node;
  69221. }
  69222. ts.createThrow = createThrow;
  69223. function updateThrow(node, expression) {
  69224. return node.expression !== expression
  69225. ? updateNode(createThrow(expression), node)
  69226. : node;
  69227. }
  69228. ts.updateThrow = updateThrow;
  69229. function createTry(tryBlock, catchClause, finallyBlock) {
  69230. var node = createSynthesizedNode(240 /* TryStatement */);
  69231. node.tryBlock = tryBlock;
  69232. node.catchClause = catchClause;
  69233. node.finallyBlock = finallyBlock;
  69234. return node;
  69235. }
  69236. ts.createTry = createTry;
  69237. function updateTry(node, tryBlock, catchClause, finallyBlock) {
  69238. return node.tryBlock !== tryBlock
  69239. || node.catchClause !== catchClause
  69240. || node.finallyBlock !== finallyBlock
  69241. ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
  69242. : node;
  69243. }
  69244. ts.updateTry = updateTry;
  69245. function createDebuggerStatement() {
  69246. return createSynthesizedNode(241 /* DebuggerStatement */);
  69247. }
  69248. ts.createDebuggerStatement = createDebuggerStatement;
  69249. function createVariableDeclaration(name, type, initializer) {
  69250. /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
  69251. var node = createSynthesizedNode(242 /* VariableDeclaration */);
  69252. node.name = asName(name);
  69253. node.type = type;
  69254. node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
  69255. return node;
  69256. }
  69257. ts.createVariableDeclaration = createVariableDeclaration;
  69258. function updateVariableDeclaration(node, name, type, initializer) {
  69259. /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
  69260. return node.name !== name
  69261. || node.type !== type
  69262. || node.initializer !== initializer
  69263. ? updateNode(createVariableDeclaration(name, type, initializer), node)
  69264. : node;
  69265. }
  69266. ts.updateVariableDeclaration = updateVariableDeclaration;
  69267. /* @internal */
  69268. function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
  69269. var node = createSynthesizedNode(242 /* VariableDeclaration */);
  69270. node.name = asName(name);
  69271. node.type = type;
  69272. node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
  69273. node.exclamationToken = exclaimationToken;
  69274. return node;
  69275. }
  69276. ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
  69277. /* @internal */
  69278. function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
  69279. return node.name !== name
  69280. || node.type !== type
  69281. || node.initializer !== initializer
  69282. || node.exclamationToken !== exclaimationToken
  69283. ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
  69284. : node;
  69285. }
  69286. ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
  69287. function createVariableDeclarationList(declarations, flags) {
  69288. if (flags === void 0) { flags = 0 /* None */; }
  69289. var node = createSynthesizedNode(243 /* VariableDeclarationList */);
  69290. node.flags |= flags & 3 /* BlockScoped */;
  69291. node.declarations = createNodeArray(declarations);
  69292. return node;
  69293. }
  69294. ts.createVariableDeclarationList = createVariableDeclarationList;
  69295. function updateVariableDeclarationList(node, declarations) {
  69296. return node.declarations !== declarations
  69297. ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
  69298. : node;
  69299. }
  69300. ts.updateVariableDeclarationList = updateVariableDeclarationList;
  69301. function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
  69302. var node = createSynthesizedNode(244 /* FunctionDeclaration */);
  69303. node.decorators = asNodeArray(decorators);
  69304. node.modifiers = asNodeArray(modifiers);
  69305. node.asteriskToken = asteriskToken;
  69306. node.name = asName(name);
  69307. node.typeParameters = asNodeArray(typeParameters);
  69308. node.parameters = createNodeArray(parameters);
  69309. node.type = type;
  69310. node.body = body;
  69311. return node;
  69312. }
  69313. ts.createFunctionDeclaration = createFunctionDeclaration;
  69314. function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
  69315. return node.decorators !== decorators
  69316. || node.modifiers !== modifiers
  69317. || node.asteriskToken !== asteriskToken
  69318. || node.name !== name
  69319. || node.typeParameters !== typeParameters
  69320. || node.parameters !== parameters
  69321. || node.type !== type
  69322. || node.body !== body
  69323. ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
  69324. : node;
  69325. }
  69326. ts.updateFunctionDeclaration = updateFunctionDeclaration;
  69327. function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
  69328. var node = createSynthesizedNode(245 /* ClassDeclaration */);
  69329. node.decorators = asNodeArray(decorators);
  69330. node.modifiers = asNodeArray(modifiers);
  69331. node.name = asName(name);
  69332. node.typeParameters = asNodeArray(typeParameters);
  69333. node.heritageClauses = asNodeArray(heritageClauses);
  69334. node.members = createNodeArray(members);
  69335. return node;
  69336. }
  69337. ts.createClassDeclaration = createClassDeclaration;
  69338. function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
  69339. return node.decorators !== decorators
  69340. || node.modifiers !== modifiers
  69341. || node.name !== name
  69342. || node.typeParameters !== typeParameters
  69343. || node.heritageClauses !== heritageClauses
  69344. || node.members !== members
  69345. ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
  69346. : node;
  69347. }
  69348. ts.updateClassDeclaration = updateClassDeclaration;
  69349. function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
  69350. var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
  69351. node.decorators = asNodeArray(decorators);
  69352. node.modifiers = asNodeArray(modifiers);
  69353. node.name = asName(name);
  69354. node.typeParameters = asNodeArray(typeParameters);
  69355. node.heritageClauses = asNodeArray(heritageClauses);
  69356. node.members = createNodeArray(members);
  69357. return node;
  69358. }
  69359. ts.createInterfaceDeclaration = createInterfaceDeclaration;
  69360. function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
  69361. return node.decorators !== decorators
  69362. || node.modifiers !== modifiers
  69363. || node.name !== name
  69364. || node.typeParameters !== typeParameters
  69365. || node.heritageClauses !== heritageClauses
  69366. || node.members !== members
  69367. ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
  69368. : node;
  69369. }
  69370. ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
  69371. function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
  69372. var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
  69373. node.decorators = asNodeArray(decorators);
  69374. node.modifiers = asNodeArray(modifiers);
  69375. node.name = asName(name);
  69376. node.typeParameters = asNodeArray(typeParameters);
  69377. node.type = type;
  69378. return node;
  69379. }
  69380. ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
  69381. function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
  69382. return node.decorators !== decorators
  69383. || node.modifiers !== modifiers
  69384. || node.name !== name
  69385. || node.typeParameters !== typeParameters
  69386. || node.type !== type
  69387. ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
  69388. : node;
  69389. }
  69390. ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
  69391. function createEnumDeclaration(decorators, modifiers, name, members) {
  69392. var node = createSynthesizedNode(248 /* EnumDeclaration */);
  69393. node.decorators = asNodeArray(decorators);
  69394. node.modifiers = asNodeArray(modifiers);
  69395. node.name = asName(name);
  69396. node.members = createNodeArray(members);
  69397. return node;
  69398. }
  69399. ts.createEnumDeclaration = createEnumDeclaration;
  69400. function updateEnumDeclaration(node, decorators, modifiers, name, members) {
  69401. return node.decorators !== decorators
  69402. || node.modifiers !== modifiers
  69403. || node.name !== name
  69404. || node.members !== members
  69405. ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
  69406. : node;
  69407. }
  69408. ts.updateEnumDeclaration = updateEnumDeclaration;
  69409. function createModuleDeclaration(decorators, modifiers, name, body, flags) {
  69410. if (flags === void 0) { flags = 0 /* None */; }
  69411. var node = createSynthesizedNode(249 /* ModuleDeclaration */);
  69412. node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
  69413. node.decorators = asNodeArray(decorators);
  69414. node.modifiers = asNodeArray(modifiers);
  69415. node.name = name;
  69416. node.body = body;
  69417. return node;
  69418. }
  69419. ts.createModuleDeclaration = createModuleDeclaration;
  69420. function updateModuleDeclaration(node, decorators, modifiers, name, body) {
  69421. return node.decorators !== decorators
  69422. || node.modifiers !== modifiers
  69423. || node.name !== name
  69424. || node.body !== body
  69425. ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
  69426. : node;
  69427. }
  69428. ts.updateModuleDeclaration = updateModuleDeclaration;
  69429. function createModuleBlock(statements) {
  69430. var node = createSynthesizedNode(250 /* ModuleBlock */);
  69431. node.statements = createNodeArray(statements);
  69432. return node;
  69433. }
  69434. ts.createModuleBlock = createModuleBlock;
  69435. function updateModuleBlock(node, statements) {
  69436. return node.statements !== statements
  69437. ? updateNode(createModuleBlock(statements), node)
  69438. : node;
  69439. }
  69440. ts.updateModuleBlock = updateModuleBlock;
  69441. function createCaseBlock(clauses) {
  69442. var node = createSynthesizedNode(251 /* CaseBlock */);
  69443. node.clauses = createNodeArray(clauses);
  69444. return node;
  69445. }
  69446. ts.createCaseBlock = createCaseBlock;
  69447. function updateCaseBlock(node, clauses) {
  69448. return node.clauses !== clauses
  69449. ? updateNode(createCaseBlock(clauses), node)
  69450. : node;
  69451. }
  69452. ts.updateCaseBlock = updateCaseBlock;
  69453. function createNamespaceExportDeclaration(name) {
  69454. var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
  69455. node.name = asName(name);
  69456. return node;
  69457. }
  69458. ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
  69459. function updateNamespaceExportDeclaration(node, name) {
  69460. return node.name !== name
  69461. ? updateNode(createNamespaceExportDeclaration(name), node)
  69462. : node;
  69463. }
  69464. ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
  69465. function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
  69466. var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
  69467. node.decorators = asNodeArray(decorators);
  69468. node.modifiers = asNodeArray(modifiers);
  69469. node.name = asName(name);
  69470. node.moduleReference = moduleReference;
  69471. return node;
  69472. }
  69473. ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
  69474. function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
  69475. return node.decorators !== decorators
  69476. || node.modifiers !== modifiers
  69477. || node.name !== name
  69478. || node.moduleReference !== moduleReference
  69479. ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
  69480. : node;
  69481. }
  69482. ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
  69483. function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
  69484. var node = createSynthesizedNode(254 /* ImportDeclaration */);
  69485. node.decorators = asNodeArray(decorators);
  69486. node.modifiers = asNodeArray(modifiers);
  69487. node.importClause = importClause;
  69488. node.moduleSpecifier = moduleSpecifier;
  69489. return node;
  69490. }
  69491. ts.createImportDeclaration = createImportDeclaration;
  69492. function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
  69493. return node.decorators !== decorators
  69494. || node.modifiers !== modifiers
  69495. || node.importClause !== importClause
  69496. || node.moduleSpecifier !== moduleSpecifier
  69497. ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
  69498. : node;
  69499. }
  69500. ts.updateImportDeclaration = updateImportDeclaration;
  69501. function createImportClause(name, namedBindings, isTypeOnly) {
  69502. if (isTypeOnly === void 0) { isTypeOnly = false; }
  69503. var node = createSynthesizedNode(255 /* ImportClause */);
  69504. node.name = name;
  69505. node.namedBindings = namedBindings;
  69506. node.isTypeOnly = isTypeOnly;
  69507. return node;
  69508. }
  69509. ts.createImportClause = createImportClause;
  69510. function updateImportClause(node, name, namedBindings, isTypeOnly) {
  69511. return node.name !== name
  69512. || node.namedBindings !== namedBindings
  69513. || node.isTypeOnly !== isTypeOnly
  69514. ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
  69515. : node;
  69516. }
  69517. ts.updateImportClause = updateImportClause;
  69518. function createNamespaceImport(name) {
  69519. var node = createSynthesizedNode(256 /* NamespaceImport */);
  69520. node.name = name;
  69521. return node;
  69522. }
  69523. ts.createNamespaceImport = createNamespaceImport;
  69524. function createNamespaceExport(name) {
  69525. var node = createSynthesizedNode(262 /* NamespaceExport */);
  69526. node.name = name;
  69527. return node;
  69528. }
  69529. ts.createNamespaceExport = createNamespaceExport;
  69530. function updateNamespaceImport(node, name) {
  69531. return node.name !== name
  69532. ? updateNode(createNamespaceImport(name), node)
  69533. : node;
  69534. }
  69535. ts.updateNamespaceImport = updateNamespaceImport;
  69536. function updateNamespaceExport(node, name) {
  69537. return node.name !== name
  69538. ? updateNode(createNamespaceExport(name), node)
  69539. : node;
  69540. }
  69541. ts.updateNamespaceExport = updateNamespaceExport;
  69542. function createNamedImports(elements) {
  69543. var node = createSynthesizedNode(257 /* NamedImports */);
  69544. node.elements = createNodeArray(elements);
  69545. return node;
  69546. }
  69547. ts.createNamedImports = createNamedImports;
  69548. function updateNamedImports(node, elements) {
  69549. return node.elements !== elements
  69550. ? updateNode(createNamedImports(elements), node)
  69551. : node;
  69552. }
  69553. ts.updateNamedImports = updateNamedImports;
  69554. function createImportSpecifier(propertyName, name) {
  69555. var node = createSynthesizedNode(258 /* ImportSpecifier */);
  69556. node.propertyName = propertyName;
  69557. node.name = name;
  69558. return node;
  69559. }
  69560. ts.createImportSpecifier = createImportSpecifier;
  69561. function updateImportSpecifier(node, propertyName, name) {
  69562. return node.propertyName !== propertyName
  69563. || node.name !== name
  69564. ? updateNode(createImportSpecifier(propertyName, name), node)
  69565. : node;
  69566. }
  69567. ts.updateImportSpecifier = updateImportSpecifier;
  69568. function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
  69569. var node = createSynthesizedNode(259 /* ExportAssignment */);
  69570. node.decorators = asNodeArray(decorators);
  69571. node.modifiers = asNodeArray(modifiers);
  69572. node.isExportEquals = isExportEquals;
  69573. node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
  69574. return node;
  69575. }
  69576. ts.createExportAssignment = createExportAssignment;
  69577. function updateExportAssignment(node, decorators, modifiers, expression) {
  69578. return node.decorators !== decorators
  69579. || node.modifiers !== modifiers
  69580. || node.expression !== expression
  69581. ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
  69582. : node;
  69583. }
  69584. ts.updateExportAssignment = updateExportAssignment;
  69585. function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
  69586. if (isTypeOnly === void 0) { isTypeOnly = false; }
  69587. var node = createSynthesizedNode(260 /* ExportDeclaration */);
  69588. node.decorators = asNodeArray(decorators);
  69589. node.modifiers = asNodeArray(modifiers);
  69590. node.isTypeOnly = isTypeOnly;
  69591. node.exportClause = exportClause;
  69592. node.moduleSpecifier = moduleSpecifier;
  69593. return node;
  69594. }
  69595. ts.createExportDeclaration = createExportDeclaration;
  69596. function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
  69597. return node.decorators !== decorators
  69598. || node.modifiers !== modifiers
  69599. || node.isTypeOnly !== isTypeOnly
  69600. || node.exportClause !== exportClause
  69601. || node.moduleSpecifier !== moduleSpecifier
  69602. ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
  69603. : node;
  69604. }
  69605. ts.updateExportDeclaration = updateExportDeclaration;
  69606. /* @internal */
  69607. function createEmptyExports() {
  69608. return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
  69609. }
  69610. ts.createEmptyExports = createEmptyExports;
  69611. function createNamedExports(elements) {
  69612. var node = createSynthesizedNode(261 /* NamedExports */);
  69613. node.elements = createNodeArray(elements);
  69614. return node;
  69615. }
  69616. ts.createNamedExports = createNamedExports;
  69617. function updateNamedExports(node, elements) {
  69618. return node.elements !== elements
  69619. ? updateNode(createNamedExports(elements), node)
  69620. : node;
  69621. }
  69622. ts.updateNamedExports = updateNamedExports;
  69623. function createExportSpecifier(propertyName, name) {
  69624. var node = createSynthesizedNode(263 /* ExportSpecifier */);
  69625. node.propertyName = asName(propertyName);
  69626. node.name = asName(name);
  69627. return node;
  69628. }
  69629. ts.createExportSpecifier = createExportSpecifier;
  69630. function updateExportSpecifier(node, propertyName, name) {
  69631. return node.propertyName !== propertyName
  69632. || node.name !== name
  69633. ? updateNode(createExportSpecifier(propertyName, name), node)
  69634. : node;
  69635. }
  69636. ts.updateExportSpecifier = updateExportSpecifier;
  69637. // Module references
  69638. function createExternalModuleReference(expression) {
  69639. var node = createSynthesizedNode(265 /* ExternalModuleReference */);
  69640. node.expression = expression;
  69641. return node;
  69642. }
  69643. ts.createExternalModuleReference = createExternalModuleReference;
  69644. function updateExternalModuleReference(node, expression) {
  69645. return node.expression !== expression
  69646. ? updateNode(createExternalModuleReference(expression), node)
  69647. : node;
  69648. }
  69649. ts.updateExternalModuleReference = updateExternalModuleReference;
  69650. // JSDoc
  69651. /* @internal */
  69652. function createJSDocTypeExpression(type) {
  69653. var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
  69654. node.type = type;
  69655. return node;
  69656. }
  69657. ts.createJSDocTypeExpression = createJSDocTypeExpression;
  69658. /* @internal */
  69659. function createJSDocTypeTag(typeExpression, comment) {
  69660. var tag = createJSDocTag(319 /* JSDocTypeTag */, "type");
  69661. tag.typeExpression = typeExpression;
  69662. tag.comment = comment;
  69663. return tag;
  69664. }
  69665. ts.createJSDocTypeTag = createJSDocTypeTag;
  69666. /* @internal */
  69667. function createJSDocReturnTag(typeExpression, comment) {
  69668. var tag = createJSDocTag(317 /* JSDocReturnTag */, "returns");
  69669. tag.typeExpression = typeExpression;
  69670. tag.comment = comment;
  69671. return tag;
  69672. }
  69673. ts.createJSDocReturnTag = createJSDocReturnTag;
  69674. /** @internal */
  69675. function createJSDocThisTag(typeExpression) {
  69676. var tag = createJSDocTag(318 /* JSDocThisTag */, "this");
  69677. tag.typeExpression = typeExpression;
  69678. return tag;
  69679. }
  69680. ts.createJSDocThisTag = createJSDocThisTag;
  69681. /* @internal */
  69682. function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
  69683. var tag = createJSDocTag(316 /* JSDocParameterTag */, "param");
  69684. tag.typeExpression = typeExpression;
  69685. tag.name = name;
  69686. tag.isBracketed = isBracketed;
  69687. tag.comment = comment;
  69688. return tag;
  69689. }
  69690. ts.createJSDocParamTag = createJSDocParamTag;
  69691. /* @internal */
  69692. function createJSDocComment(comment, tags) {
  69693. var node = createSynthesizedNode(303 /* JSDocComment */);
  69694. node.comment = comment;
  69695. node.tags = tags;
  69696. return node;
  69697. }
  69698. ts.createJSDocComment = createJSDocComment;
  69699. /* @internal */
  69700. function createJSDocTag(kind, tagName) {
  69701. var node = createSynthesizedNode(kind);
  69702. node.tagName = createIdentifier(tagName);
  69703. return node;
  69704. }
  69705. // JSX
  69706. function createJsxElement(openingElement, children, closingElement) {
  69707. var node = createSynthesizedNode(266 /* JsxElement */);
  69708. node.openingElement = openingElement;
  69709. node.children = createNodeArray(children);
  69710. node.closingElement = closingElement;
  69711. return node;
  69712. }
  69713. ts.createJsxElement = createJsxElement;
  69714. function updateJsxElement(node, openingElement, children, closingElement) {
  69715. return node.openingElement !== openingElement
  69716. || node.children !== children
  69717. || node.closingElement !== closingElement
  69718. ? updateNode(createJsxElement(openingElement, children, closingElement), node)
  69719. : node;
  69720. }
  69721. ts.updateJsxElement = updateJsxElement;
  69722. function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
  69723. var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
  69724. node.tagName = tagName;
  69725. node.typeArguments = asNodeArray(typeArguments);
  69726. node.attributes = attributes;
  69727. return node;
  69728. }
  69729. ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
  69730. function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
  69731. return node.tagName !== tagName
  69732. || node.typeArguments !== typeArguments
  69733. || node.attributes !== attributes
  69734. ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
  69735. : node;
  69736. }
  69737. ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
  69738. function createJsxOpeningElement(tagName, typeArguments, attributes) {
  69739. var node = createSynthesizedNode(268 /* JsxOpeningElement */);
  69740. node.tagName = tagName;
  69741. node.typeArguments = asNodeArray(typeArguments);
  69742. node.attributes = attributes;
  69743. return node;
  69744. }
  69745. ts.createJsxOpeningElement = createJsxOpeningElement;
  69746. function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
  69747. return node.tagName !== tagName
  69748. || node.typeArguments !== typeArguments
  69749. || node.attributes !== attributes
  69750. ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
  69751. : node;
  69752. }
  69753. ts.updateJsxOpeningElement = updateJsxOpeningElement;
  69754. function createJsxClosingElement(tagName) {
  69755. var node = createSynthesizedNode(269 /* JsxClosingElement */);
  69756. node.tagName = tagName;
  69757. return node;
  69758. }
  69759. ts.createJsxClosingElement = createJsxClosingElement;
  69760. function updateJsxClosingElement(node, tagName) {
  69761. return node.tagName !== tagName
  69762. ? updateNode(createJsxClosingElement(tagName), node)
  69763. : node;
  69764. }
  69765. ts.updateJsxClosingElement = updateJsxClosingElement;
  69766. function createJsxFragment(openingFragment, children, closingFragment) {
  69767. var node = createSynthesizedNode(270 /* JsxFragment */);
  69768. node.openingFragment = openingFragment;
  69769. node.children = createNodeArray(children);
  69770. node.closingFragment = closingFragment;
  69771. return node;
  69772. }
  69773. ts.createJsxFragment = createJsxFragment;
  69774. function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
  69775. var node = createSynthesizedNode(11 /* JsxText */);
  69776. node.text = text;
  69777. node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
  69778. return node;
  69779. }
  69780. ts.createJsxText = createJsxText;
  69781. function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
  69782. return node.text !== text
  69783. || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
  69784. ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
  69785. : node;
  69786. }
  69787. ts.updateJsxText = updateJsxText;
  69788. function createJsxOpeningFragment() {
  69789. return createSynthesizedNode(271 /* JsxOpeningFragment */);
  69790. }
  69791. ts.createJsxOpeningFragment = createJsxOpeningFragment;
  69792. function createJsxJsxClosingFragment() {
  69793. return createSynthesizedNode(272 /* JsxClosingFragment */);
  69794. }
  69795. ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
  69796. function updateJsxFragment(node, openingFragment, children, closingFragment) {
  69797. return node.openingFragment !== openingFragment
  69798. || node.children !== children
  69799. || node.closingFragment !== closingFragment
  69800. ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
  69801. : node;
  69802. }
  69803. ts.updateJsxFragment = updateJsxFragment;
  69804. function createJsxAttribute(name, initializer) {
  69805. var node = createSynthesizedNode(273 /* JsxAttribute */);
  69806. node.name = name;
  69807. node.initializer = initializer;
  69808. return node;
  69809. }
  69810. ts.createJsxAttribute = createJsxAttribute;
  69811. function updateJsxAttribute(node, name, initializer) {
  69812. return node.name !== name
  69813. || node.initializer !== initializer
  69814. ? updateNode(createJsxAttribute(name, initializer), node)
  69815. : node;
  69816. }
  69817. ts.updateJsxAttribute = updateJsxAttribute;
  69818. function createJsxAttributes(properties) {
  69819. var node = createSynthesizedNode(274 /* JsxAttributes */);
  69820. node.properties = createNodeArray(properties);
  69821. return node;
  69822. }
  69823. ts.createJsxAttributes = createJsxAttributes;
  69824. function updateJsxAttributes(node, properties) {
  69825. return node.properties !== properties
  69826. ? updateNode(createJsxAttributes(properties), node)
  69827. : node;
  69828. }
  69829. ts.updateJsxAttributes = updateJsxAttributes;
  69830. function createJsxSpreadAttribute(expression) {
  69831. var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
  69832. node.expression = expression;
  69833. return node;
  69834. }
  69835. ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
  69836. function updateJsxSpreadAttribute(node, expression) {
  69837. return node.expression !== expression
  69838. ? updateNode(createJsxSpreadAttribute(expression), node)
  69839. : node;
  69840. }
  69841. ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
  69842. function createJsxExpression(dotDotDotToken, expression) {
  69843. var node = createSynthesizedNode(276 /* JsxExpression */);
  69844. node.dotDotDotToken = dotDotDotToken;
  69845. node.expression = expression;
  69846. return node;
  69847. }
  69848. ts.createJsxExpression = createJsxExpression;
  69849. function updateJsxExpression(node, expression) {
  69850. return node.expression !== expression
  69851. ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
  69852. : node;
  69853. }
  69854. ts.updateJsxExpression = updateJsxExpression;
  69855. // Clauses
  69856. function createCaseClause(expression, statements) {
  69857. var node = createSynthesizedNode(277 /* CaseClause */);
  69858. node.expression = ts.parenthesizeExpressionForList(expression);
  69859. node.statements = createNodeArray(statements);
  69860. return node;
  69861. }
  69862. ts.createCaseClause = createCaseClause;
  69863. function updateCaseClause(node, expression, statements) {
  69864. return node.expression !== expression
  69865. || node.statements !== statements
  69866. ? updateNode(createCaseClause(expression, statements), node)
  69867. : node;
  69868. }
  69869. ts.updateCaseClause = updateCaseClause;
  69870. function createDefaultClause(statements) {
  69871. var node = createSynthesizedNode(278 /* DefaultClause */);
  69872. node.statements = createNodeArray(statements);
  69873. return node;
  69874. }
  69875. ts.createDefaultClause = createDefaultClause;
  69876. function updateDefaultClause(node, statements) {
  69877. return node.statements !== statements
  69878. ? updateNode(createDefaultClause(statements), node)
  69879. : node;
  69880. }
  69881. ts.updateDefaultClause = updateDefaultClause;
  69882. function createHeritageClause(token, types) {
  69883. var node = createSynthesizedNode(279 /* HeritageClause */);
  69884. node.token = token;
  69885. node.types = createNodeArray(types);
  69886. return node;
  69887. }
  69888. ts.createHeritageClause = createHeritageClause;
  69889. function updateHeritageClause(node, types) {
  69890. return node.types !== types
  69891. ? updateNode(createHeritageClause(node.token, types), node)
  69892. : node;
  69893. }
  69894. ts.updateHeritageClause = updateHeritageClause;
  69895. function createCatchClause(variableDeclaration, block) {
  69896. var node = createSynthesizedNode(280 /* CatchClause */);
  69897. node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
  69898. node.block = block;
  69899. return node;
  69900. }
  69901. ts.createCatchClause = createCatchClause;
  69902. function updateCatchClause(node, variableDeclaration, block) {
  69903. return node.variableDeclaration !== variableDeclaration
  69904. || node.block !== block
  69905. ? updateNode(createCatchClause(variableDeclaration, block), node)
  69906. : node;
  69907. }
  69908. ts.updateCatchClause = updateCatchClause;
  69909. // Property assignments
  69910. function createPropertyAssignment(name, initializer) {
  69911. var node = createSynthesizedNode(281 /* PropertyAssignment */);
  69912. node.name = asName(name);
  69913. node.questionToken = undefined;
  69914. node.initializer = ts.parenthesizeExpressionForList(initializer);
  69915. return node;
  69916. }
  69917. ts.createPropertyAssignment = createPropertyAssignment;
  69918. function updatePropertyAssignment(node, name, initializer) {
  69919. return node.name !== name
  69920. || node.initializer !== initializer
  69921. ? updateNode(createPropertyAssignment(name, initializer), node)
  69922. : node;
  69923. }
  69924. ts.updatePropertyAssignment = updatePropertyAssignment;
  69925. function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
  69926. var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
  69927. node.name = asName(name);
  69928. node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
  69929. return node;
  69930. }
  69931. ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
  69932. function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
  69933. return node.name !== name
  69934. || node.objectAssignmentInitializer !== objectAssignmentInitializer
  69935. ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
  69936. : node;
  69937. }
  69938. ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
  69939. function createSpreadAssignment(expression) {
  69940. var node = createSynthesizedNode(283 /* SpreadAssignment */);
  69941. node.expression = ts.parenthesizeExpressionForList(expression);
  69942. return node;
  69943. }
  69944. ts.createSpreadAssignment = createSpreadAssignment;
  69945. function updateSpreadAssignment(node, expression) {
  69946. return node.expression !== expression
  69947. ? updateNode(createSpreadAssignment(expression), node)
  69948. : node;
  69949. }
  69950. ts.updateSpreadAssignment = updateSpreadAssignment;
  69951. // Enum
  69952. function createEnumMember(name, initializer) {
  69953. var node = createSynthesizedNode(284 /* EnumMember */);
  69954. node.name = asName(name);
  69955. node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
  69956. return node;
  69957. }
  69958. ts.createEnumMember = createEnumMember;
  69959. function updateEnumMember(node, name, initializer) {
  69960. return node.name !== name
  69961. || node.initializer !== initializer
  69962. ? updateNode(createEnumMember(name, initializer), node)
  69963. : node;
  69964. }
  69965. ts.updateEnumMember = updateEnumMember;
  69966. // Top-level nodes
  69967. function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
  69968. if (node.statements !== statements ||
  69969. (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
  69970. (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
  69971. (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
  69972. (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
  69973. (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
  69974. var updated = createSynthesizedNode(290 /* SourceFile */);
  69975. updated.flags |= node.flags;
  69976. updated.statements = createNodeArray(statements);
  69977. updated.endOfFileToken = node.endOfFileToken;
  69978. updated.fileName = node.fileName;
  69979. updated.path = node.path;
  69980. updated.text = node.text;
  69981. updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
  69982. updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
  69983. updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
  69984. updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
  69985. updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
  69986. if (node.amdDependencies !== undefined)
  69987. updated.amdDependencies = node.amdDependencies;
  69988. if (node.moduleName !== undefined)
  69989. updated.moduleName = node.moduleName;
  69990. if (node.languageVariant !== undefined)
  69991. updated.languageVariant = node.languageVariant;
  69992. if (node.renamedDependencies !== undefined)
  69993. updated.renamedDependencies = node.renamedDependencies;
  69994. if (node.languageVersion !== undefined)
  69995. updated.languageVersion = node.languageVersion;
  69996. if (node.scriptKind !== undefined)
  69997. updated.scriptKind = node.scriptKind;
  69998. if (node.externalModuleIndicator !== undefined)
  69999. updated.externalModuleIndicator = node.externalModuleIndicator;
  70000. if (node.commonJsModuleIndicator !== undefined)
  70001. updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
  70002. if (node.identifiers !== undefined)
  70003. updated.identifiers = node.identifiers;
  70004. if (node.nodeCount !== undefined)
  70005. updated.nodeCount = node.nodeCount;
  70006. if (node.identifierCount !== undefined)
  70007. updated.identifierCount = node.identifierCount;
  70008. if (node.symbolCount !== undefined)
  70009. updated.symbolCount = node.symbolCount;
  70010. if (node.parseDiagnostics !== undefined)
  70011. updated.parseDiagnostics = node.parseDiagnostics;
  70012. if (node.bindDiagnostics !== undefined)
  70013. updated.bindDiagnostics = node.bindDiagnostics;
  70014. if (node.bindSuggestionDiagnostics !== undefined)
  70015. updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
  70016. if (node.lineMap !== undefined)
  70017. updated.lineMap = node.lineMap;
  70018. if (node.classifiableNames !== undefined)
  70019. updated.classifiableNames = node.classifiableNames;
  70020. if (node.resolvedModules !== undefined)
  70021. updated.resolvedModules = node.resolvedModules;
  70022. if (node.resolvedTypeReferenceDirectiveNames !== undefined)
  70023. updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
  70024. if (node.imports !== undefined)
  70025. updated.imports = node.imports;
  70026. if (node.moduleAugmentations !== undefined)
  70027. updated.moduleAugmentations = node.moduleAugmentations;
  70028. if (node.pragmas !== undefined)
  70029. updated.pragmas = node.pragmas;
  70030. if (node.localJsxFactory !== undefined)
  70031. updated.localJsxFactory = node.localJsxFactory;
  70032. if (node.localJsxNamespace !== undefined)
  70033. updated.localJsxNamespace = node.localJsxNamespace;
  70034. return updateNode(updated, node);
  70035. }
  70036. return node;
  70037. }
  70038. ts.updateSourceFileNode = updateSourceFileNode;
  70039. /**
  70040. * Creates a shallow, memberwise clone of a node for mutation.
  70041. */
  70042. function getMutableClone(node) {
  70043. var clone = getSynthesizedClone(node);
  70044. clone.pos = node.pos;
  70045. clone.end = node.end;
  70046. clone.parent = node.parent;
  70047. return clone;
  70048. }
  70049. ts.getMutableClone = getMutableClone;
  70050. // Transformation nodes
  70051. /**
  70052. * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
  70053. * order to preserve comments.
  70054. *
  70055. * @param original The original statement.
  70056. */
  70057. function createNotEmittedStatement(original) {
  70058. var node = createSynthesizedNode(324 /* NotEmittedStatement */);
  70059. node.original = original;
  70060. setTextRange(node, original);
  70061. return node;
  70062. }
  70063. ts.createNotEmittedStatement = createNotEmittedStatement;
  70064. /**
  70065. * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
  70066. * order to properly emit exports.
  70067. */
  70068. /* @internal */
  70069. function createEndOfDeclarationMarker(original) {
  70070. var node = createSynthesizedNode(328 /* EndOfDeclarationMarker */);
  70071. node.emitNode = {};
  70072. node.original = original;
  70073. return node;
  70074. }
  70075. ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
  70076. /**
  70077. * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
  70078. * order to properly emit exports.
  70079. */
  70080. /* @internal */
  70081. function createMergeDeclarationMarker(original) {
  70082. var node = createSynthesizedNode(327 /* MergeDeclarationMarker */);
  70083. node.emitNode = {};
  70084. node.original = original;
  70085. return node;
  70086. }
  70087. ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
  70088. /**
  70089. * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
  70090. * order to preserve comments or sourcemap positions.
  70091. *
  70092. * @param expression The inner expression to emit.
  70093. * @param original The original outer expression.
  70094. * @param location The location for the expression. Defaults to the positions from "original" if provided.
  70095. */
  70096. function createPartiallyEmittedExpression(expression, original) {
  70097. var node = createSynthesizedNode(325 /* PartiallyEmittedExpression */);
  70098. node.expression = expression;
  70099. node.original = original;
  70100. setTextRange(node, original);
  70101. return node;
  70102. }
  70103. ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
  70104. function updatePartiallyEmittedExpression(node, expression) {
  70105. if (node.expression !== expression) {
  70106. return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
  70107. }
  70108. return node;
  70109. }
  70110. ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
  70111. function flattenCommaElements(node) {
  70112. if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
  70113. if (node.kind === 326 /* CommaListExpression */) {
  70114. return node.elements;
  70115. }
  70116. if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
  70117. return [node.left, node.right];
  70118. }
  70119. }
  70120. return node;
  70121. }
  70122. function createCommaList(elements) {
  70123. var node = createSynthesizedNode(326 /* CommaListExpression */);
  70124. node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
  70125. return node;
  70126. }
  70127. ts.createCommaList = createCommaList;
  70128. function updateCommaList(node, elements) {
  70129. return node.elements !== elements
  70130. ? updateNode(createCommaList(elements), node)
  70131. : node;
  70132. }
  70133. ts.updateCommaList = updateCommaList;
  70134. /* @internal */
  70135. function createSyntheticReferenceExpression(expression, thisArg) {
  70136. var node = createSynthesizedNode(329 /* SyntheticReferenceExpression */);
  70137. node.expression = expression;
  70138. node.thisArg = thisArg;
  70139. return node;
  70140. }
  70141. ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
  70142. /* @internal */
  70143. function updateSyntheticReferenceExpression(node, expression, thisArg) {
  70144. return node.expression !== expression
  70145. || node.thisArg !== thisArg
  70146. ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
  70147. : node;
  70148. }
  70149. ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
  70150. function createBundle(sourceFiles, prepends) {
  70151. if (prepends === void 0) { prepends = ts.emptyArray; }
  70152. var node = ts.createNode(291 /* Bundle */);
  70153. node.prepends = prepends;
  70154. node.sourceFiles = sourceFiles;
  70155. return node;
  70156. }
  70157. ts.createBundle = createBundle;
  70158. var allUnscopedEmitHelpers;
  70159. function getAllUnscopedEmitHelpers() {
  70160. return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
  70161. ts.valuesHelper,
  70162. ts.readHelper,
  70163. ts.spreadHelper,
  70164. ts.spreadArraysHelper,
  70165. ts.restHelper,
  70166. ts.decorateHelper,
  70167. ts.metadataHelper,
  70168. ts.paramHelper,
  70169. ts.awaiterHelper,
  70170. ts.assignHelper,
  70171. ts.awaitHelper,
  70172. ts.asyncGeneratorHelper,
  70173. ts.asyncDelegator,
  70174. ts.asyncValues,
  70175. ts.extendsHelper,
  70176. ts.templateObjectHelper,
  70177. ts.generatorHelper,
  70178. ts.importStarHelper,
  70179. ts.importDefaultHelper,
  70180. ts.classPrivateFieldGetHelper,
  70181. ts.classPrivateFieldSetHelper,
  70182. ], function (helper) { return helper.name; }));
  70183. }
  70184. function createUnparsedSource() {
  70185. var node = ts.createNode(292 /* UnparsedSource */);
  70186. node.prologues = ts.emptyArray;
  70187. node.referencedFiles = ts.emptyArray;
  70188. node.libReferenceDirectives = ts.emptyArray;
  70189. node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
  70190. return node;
  70191. }
  70192. function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
  70193. var node = createUnparsedSource();
  70194. var stripInternal;
  70195. var bundleFileInfo;
  70196. if (!ts.isString(textOrInputFiles)) {
  70197. ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
  70198. node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
  70199. node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
  70200. Object.defineProperties(node, {
  70201. text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
  70202. sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
  70203. });
  70204. if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
  70205. node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
  70206. ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
  70207. stripInternal = mapTextOrStripInternal;
  70208. bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
  70209. if (node.oldFileOfCurrentEmit) {
  70210. parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
  70211. return node;
  70212. }
  70213. }
  70214. }
  70215. else {
  70216. node.fileName = "";
  70217. node.text = textOrInputFiles;
  70218. node.sourceMapPath = mapPathOrType;
  70219. node.sourceMapText = mapTextOrStripInternal;
  70220. }
  70221. ts.Debug.assert(!node.oldFileOfCurrentEmit);
  70222. parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
  70223. return node;
  70224. }
  70225. ts.createUnparsedSourceFile = createUnparsedSourceFile;
  70226. function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
  70227. var prologues;
  70228. var helpers;
  70229. var referencedFiles;
  70230. var typeReferenceDirectives;
  70231. var libReferenceDirectives;
  70232. var texts;
  70233. for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
  70234. var section = _a[_i];
  70235. switch (section.kind) {
  70236. case "prologue" /* Prologue */:
  70237. (prologues || (prologues = [])).push(createUnparsedNode(section, node));
  70238. break;
  70239. case "emitHelpers" /* EmitHelpers */:
  70240. (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
  70241. break;
  70242. case "no-default-lib" /* NoDefaultLib */:
  70243. node.hasNoDefaultLib = true;
  70244. break;
  70245. case "reference" /* Reference */:
  70246. (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
  70247. break;
  70248. case "type" /* Type */:
  70249. (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
  70250. break;
  70251. case "lib" /* Lib */:
  70252. (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
  70253. break;
  70254. case "prepend" /* Prepend */:
  70255. var prependNode = createUnparsedNode(section, node);
  70256. var prependTexts = void 0;
  70257. for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
  70258. var text = _c[_b];
  70259. if (!stripInternal || text.kind !== "internal" /* Internal */) {
  70260. (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
  70261. }
  70262. }
  70263. prependNode.texts = prependTexts || ts.emptyArray;
  70264. (texts || (texts = [])).push(prependNode);
  70265. break;
  70266. case "internal" /* Internal */:
  70267. if (stripInternal) {
  70268. if (!texts)
  70269. texts = [];
  70270. break;
  70271. }
  70272. // falls through
  70273. case "text" /* Text */:
  70274. (texts || (texts = [])).push(createUnparsedNode(section, node));
  70275. break;
  70276. default:
  70277. ts.Debug.assertNever(section);
  70278. }
  70279. }
  70280. node.prologues = prologues || ts.emptyArray;
  70281. node.helpers = helpers;
  70282. node.referencedFiles = referencedFiles || ts.emptyArray;
  70283. node.typeReferenceDirectives = typeReferenceDirectives;
  70284. node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
  70285. node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
  70286. }
  70287. function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
  70288. ts.Debug.assert(!!node.oldFileOfCurrentEmit);
  70289. var texts;
  70290. var syntheticReferences;
  70291. for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
  70292. var section = _a[_i];
  70293. switch (section.kind) {
  70294. case "internal" /* Internal */:
  70295. case "text" /* Text */:
  70296. (texts || (texts = [])).push(createUnparsedNode(section, node));
  70297. break;
  70298. case "no-default-lib" /* NoDefaultLib */:
  70299. case "reference" /* Reference */:
  70300. case "type" /* Type */:
  70301. case "lib" /* Lib */:
  70302. (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
  70303. break;
  70304. // Ignore
  70305. case "prologue" /* Prologue */:
  70306. case "emitHelpers" /* EmitHelpers */:
  70307. case "prepend" /* Prepend */:
  70308. break;
  70309. default:
  70310. ts.Debug.assertNever(section);
  70311. }
  70312. }
  70313. node.texts = texts || ts.emptyArray;
  70314. node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
  70315. node.syntheticReferences = syntheticReferences;
  70316. return node;
  70317. }
  70318. function mapBundleFileSectionKindToSyntaxKind(kind) {
  70319. switch (kind) {
  70320. case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
  70321. case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
  70322. case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
  70323. case "text" /* Text */: return 287 /* UnparsedText */;
  70324. case "emitHelpers" /* EmitHelpers */:
  70325. case "no-default-lib" /* NoDefaultLib */:
  70326. case "reference" /* Reference */:
  70327. case "type" /* Type */:
  70328. case "lib" /* Lib */:
  70329. return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
  70330. default:
  70331. return ts.Debug.assertNever(kind);
  70332. }
  70333. }
  70334. function createUnparsedNode(section, parent) {
  70335. var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
  70336. node.parent = parent;
  70337. node.data = section.data;
  70338. return node;
  70339. }
  70340. function createUnparsedSyntheticReference(section, parent) {
  70341. var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
  70342. node.parent = parent;
  70343. node.data = section.data;
  70344. node.section = section;
  70345. return node;
  70346. }
  70347. function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
  70348. var node = ts.createNode(293 /* InputFiles */);
  70349. if (!ts.isString(javascriptTextOrReadFileText)) {
  70350. var cache_1 = ts.createMap();
  70351. var textGetter_1 = function (path) {
  70352. if (path === undefined)
  70353. return undefined;
  70354. var value = cache_1.get(path);
  70355. if (value === undefined) {
  70356. value = javascriptTextOrReadFileText(path);
  70357. cache_1.set(path, value !== undefined ? value : false);
  70358. }
  70359. return value !== false ? value : undefined;
  70360. };
  70361. var definedTextGetter_1 = function (path) {
  70362. var result = textGetter_1(path);
  70363. return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
  70364. };
  70365. var buildInfo_1;
  70366. var getAndCacheBuildInfo_1 = function (getText) {
  70367. if (buildInfo_1 === undefined) {
  70368. var result = getText();
  70369. buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
  70370. }
  70371. return buildInfo_1 || undefined;
  70372. };
  70373. node.javascriptPath = declarationTextOrJavascriptPath;
  70374. node.javascriptMapPath = javascriptMapPath;
  70375. node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
  70376. node.declarationMapPath = declarationMapPath;
  70377. node.buildInfoPath = declarationMapTextOrBuildInfoPath;
  70378. Object.defineProperties(node, {
  70379. javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
  70380. javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
  70381. declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
  70382. declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
  70383. buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
  70384. });
  70385. }
  70386. else {
  70387. node.javascriptText = javascriptTextOrReadFileText;
  70388. node.javascriptMapPath = javascriptMapPath;
  70389. node.javascriptMapText = javascriptMapTextOrDeclarationPath;
  70390. node.declarationText = declarationTextOrJavascriptPath;
  70391. node.declarationMapPath = declarationMapPath;
  70392. node.declarationMapText = declarationMapTextOrBuildInfoPath;
  70393. node.javascriptPath = javascriptPath;
  70394. node.declarationPath = declarationPath;
  70395. node.buildInfoPath = buildInfoPath;
  70396. node.buildInfo = buildInfo;
  70397. node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
  70398. }
  70399. return node;
  70400. }
  70401. ts.createInputFiles = createInputFiles;
  70402. function updateBundle(node, sourceFiles, prepends) {
  70403. if (prepends === void 0) { prepends = ts.emptyArray; }
  70404. if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
  70405. return createBundle(sourceFiles, prepends);
  70406. }
  70407. return node;
  70408. }
  70409. ts.updateBundle = updateBundle;
  70410. function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
  70411. return createCall(createFunctionExpression(
  70412. /*modifiers*/ undefined,
  70413. /*asteriskToken*/ undefined,
  70414. /*name*/ undefined,
  70415. /*typeParameters*/ undefined,
  70416. /*parameters*/ param ? [param] : [],
  70417. /*type*/ undefined, createBlock(statements, /*multiLine*/ true)),
  70418. /*typeArguments*/ undefined,
  70419. /*argumentsArray*/ paramValue ? [paramValue] : []);
  70420. }
  70421. ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
  70422. function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
  70423. return createCall(createArrowFunction(
  70424. /*modifiers*/ undefined,
  70425. /*typeParameters*/ undefined,
  70426. /*parameters*/ param ? [param] : [],
  70427. /*type*/ undefined,
  70428. /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)),
  70429. /*typeArguments*/ undefined,
  70430. /*argumentsArray*/ paramValue ? [paramValue] : []);
  70431. }
  70432. ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
  70433. function createComma(left, right) {
  70434. return createBinary(left, 27 /* CommaToken */, right);
  70435. }
  70436. ts.createComma = createComma;
  70437. function createLessThan(left, right) {
  70438. return createBinary(left, 29 /* LessThanToken */, right);
  70439. }
  70440. ts.createLessThan = createLessThan;
  70441. function createAssignment(left, right) {
  70442. return createBinary(left, 62 /* EqualsToken */, right);
  70443. }
  70444. ts.createAssignment = createAssignment;
  70445. function createStrictEquality(left, right) {
  70446. return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
  70447. }
  70448. ts.createStrictEquality = createStrictEquality;
  70449. function createStrictInequality(left, right) {
  70450. return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
  70451. }
  70452. ts.createStrictInequality = createStrictInequality;
  70453. function createAdd(left, right) {
  70454. return createBinary(left, 39 /* PlusToken */, right);
  70455. }
  70456. ts.createAdd = createAdd;
  70457. function createSubtract(left, right) {
  70458. return createBinary(left, 40 /* MinusToken */, right);
  70459. }
  70460. ts.createSubtract = createSubtract;
  70461. function createPostfixIncrement(operand) {
  70462. return createPostfix(operand, 45 /* PlusPlusToken */);
  70463. }
  70464. ts.createPostfixIncrement = createPostfixIncrement;
  70465. function createLogicalAnd(left, right) {
  70466. return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
  70467. }
  70468. ts.createLogicalAnd = createLogicalAnd;
  70469. function createLogicalOr(left, right) {
  70470. return createBinary(left, 56 /* BarBarToken */, right);
  70471. }
  70472. ts.createLogicalOr = createLogicalOr;
  70473. function createNullishCoalesce(left, right) {
  70474. return createBinary(left, 60 /* QuestionQuestionToken */, right);
  70475. }
  70476. ts.createNullishCoalesce = createNullishCoalesce;
  70477. function createLogicalNot(operand) {
  70478. return createPrefix(53 /* ExclamationToken */, operand);
  70479. }
  70480. ts.createLogicalNot = createLogicalNot;
  70481. function createVoidZero() {
  70482. return createVoid(createLiteral(0));
  70483. }
  70484. ts.createVoidZero = createVoidZero;
  70485. function createExportDefault(expression) {
  70486. return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
  70487. }
  70488. ts.createExportDefault = createExportDefault;
  70489. function createExternalModuleExport(exportName) {
  70490. return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
  70491. }
  70492. ts.createExternalModuleExport = createExternalModuleExport;
  70493. // Utilities
  70494. function asName(name) {
  70495. return ts.isString(name) ? createIdentifier(name) : name;
  70496. }
  70497. function asExpression(value) {
  70498. return typeof value === "string" ? createStringLiteral(value) :
  70499. typeof value === "number" ? createNumericLiteral("" + value) :
  70500. typeof value === "boolean" ? value ? createTrue() : createFalse() :
  70501. value;
  70502. }
  70503. function asNodeArray(array) {
  70504. return array ? createNodeArray(array) : undefined;
  70505. }
  70506. function asToken(value) {
  70507. return typeof value === "number" ? createToken(value) : value;
  70508. }
  70509. function asEmbeddedStatement(statement) {
  70510. return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
  70511. }
  70512. /**
  70513. * Clears any EmitNode entries from parse-tree nodes.
  70514. * @param sourceFile A source file.
  70515. */
  70516. function disposeEmitNodes(sourceFile) {
  70517. // During transformation we may need to annotate a parse tree node with transient
  70518. // transformation properties. As parse tree nodes live longer than transformation
  70519. // nodes, we need to make sure we reclaim any memory allocated for custom ranges
  70520. // from these nodes to ensure we do not hold onto entire subtrees just for position
  70521. // information. We also need to reset these nodes to a pre-transformation state
  70522. // for incremental parsing scenarios so that we do not impact later emit.
  70523. sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
  70524. var emitNode = sourceFile && sourceFile.emitNode;
  70525. var annotatedNodes = emitNode && emitNode.annotatedNodes;
  70526. if (annotatedNodes) {
  70527. for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
  70528. var node = annotatedNodes_1[_i];
  70529. node.emitNode = undefined;
  70530. }
  70531. }
  70532. }
  70533. ts.disposeEmitNodes = disposeEmitNodes;
  70534. /**
  70535. * Associates a node with the current transformation, initializing
  70536. * various transient transformation properties.
  70537. */
  70538. /* @internal */
  70539. function getOrCreateEmitNode(node) {
  70540. if (!node.emitNode) {
  70541. if (ts.isParseTreeNode(node)) {
  70542. // To avoid holding onto transformation artifacts, we keep track of any
  70543. // parse tree node we are annotating. This allows us to clean them up after
  70544. // all transformations have completed.
  70545. if (node.kind === 290 /* SourceFile */) {
  70546. return node.emitNode = { annotatedNodes: [node] };
  70547. }
  70548. var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
  70549. getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
  70550. }
  70551. node.emitNode = {};
  70552. }
  70553. return node.emitNode;
  70554. }
  70555. ts.getOrCreateEmitNode = getOrCreateEmitNode;
  70556. /**
  70557. * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
  70558. * @internal
  70559. */
  70560. function removeAllComments(node) {
  70561. var emitNode = getOrCreateEmitNode(node);
  70562. emitNode.flags |= 1536 /* NoComments */;
  70563. emitNode.leadingComments = undefined;
  70564. emitNode.trailingComments = undefined;
  70565. return node;
  70566. }
  70567. ts.removeAllComments = removeAllComments;
  70568. function setTextRange(range, location) {
  70569. if (location) {
  70570. range.pos = location.pos;
  70571. range.end = location.end;
  70572. }
  70573. return range;
  70574. }
  70575. ts.setTextRange = setTextRange;
  70576. /**
  70577. * Sets flags that control emit behavior of a node.
  70578. */
  70579. function setEmitFlags(node, emitFlags) {
  70580. getOrCreateEmitNode(node).flags = emitFlags;
  70581. return node;
  70582. }
  70583. ts.setEmitFlags = setEmitFlags;
  70584. /**
  70585. * Sets flags that control emit behavior of a node.
  70586. */
  70587. /* @internal */
  70588. function addEmitFlags(node, emitFlags) {
  70589. var emitNode = getOrCreateEmitNode(node);
  70590. emitNode.flags = emitNode.flags | emitFlags;
  70591. return node;
  70592. }
  70593. ts.addEmitFlags = addEmitFlags;
  70594. /**
  70595. * Gets a custom text range to use when emitting source maps.
  70596. */
  70597. function getSourceMapRange(node) {
  70598. var emitNode = node.emitNode;
  70599. return (emitNode && emitNode.sourceMapRange) || node;
  70600. }
  70601. ts.getSourceMapRange = getSourceMapRange;
  70602. /**
  70603. * Sets a custom text range to use when emitting source maps.
  70604. */
  70605. function setSourceMapRange(node, range) {
  70606. getOrCreateEmitNode(node).sourceMapRange = range;
  70607. return node;
  70608. }
  70609. ts.setSourceMapRange = setSourceMapRange;
  70610. var SourceMapSource;
  70611. /**
  70612. * Create an external source map source file reference
  70613. */
  70614. function createSourceMapSource(fileName, text, skipTrivia) {
  70615. return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
  70616. }
  70617. ts.createSourceMapSource = createSourceMapSource;
  70618. /**
  70619. * Gets the TextRange to use for source maps for a token of a node.
  70620. */
  70621. function getTokenSourceMapRange(node, token) {
  70622. var emitNode = node.emitNode;
  70623. var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
  70624. return tokenSourceMapRanges && tokenSourceMapRanges[token];
  70625. }
  70626. ts.getTokenSourceMapRange = getTokenSourceMapRange;
  70627. /**
  70628. * Sets the TextRange to use for source maps for a token of a node.
  70629. */
  70630. function setTokenSourceMapRange(node, token, range) {
  70631. var emitNode = getOrCreateEmitNode(node);
  70632. var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
  70633. tokenSourceMapRanges[token] = range;
  70634. return node;
  70635. }
  70636. ts.setTokenSourceMapRange = setTokenSourceMapRange;
  70637. /**
  70638. * Gets a custom text range to use when emitting comments.
  70639. */
  70640. /*@internal*/
  70641. function getStartsOnNewLine(node) {
  70642. var emitNode = node.emitNode;
  70643. return emitNode && emitNode.startsOnNewLine;
  70644. }
  70645. ts.getStartsOnNewLine = getStartsOnNewLine;
  70646. /**
  70647. * Sets a custom text range to use when emitting comments.
  70648. */
  70649. /*@internal*/
  70650. function setStartsOnNewLine(node, newLine) {
  70651. getOrCreateEmitNode(node).startsOnNewLine = newLine;
  70652. return node;
  70653. }
  70654. ts.setStartsOnNewLine = setStartsOnNewLine;
  70655. /**
  70656. * Gets a custom text range to use when emitting comments.
  70657. */
  70658. function getCommentRange(node) {
  70659. var emitNode = node.emitNode;
  70660. return (emitNode && emitNode.commentRange) || node;
  70661. }
  70662. ts.getCommentRange = getCommentRange;
  70663. /**
  70664. * Sets a custom text range to use when emitting comments.
  70665. */
  70666. function setCommentRange(node, range) {
  70667. getOrCreateEmitNode(node).commentRange = range;
  70668. return node;
  70669. }
  70670. ts.setCommentRange = setCommentRange;
  70671. function getSyntheticLeadingComments(node) {
  70672. var emitNode = node.emitNode;
  70673. return emitNode && emitNode.leadingComments;
  70674. }
  70675. ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
  70676. function setSyntheticLeadingComments(node, comments) {
  70677. getOrCreateEmitNode(node).leadingComments = comments;
  70678. return node;
  70679. }
  70680. ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
  70681. function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
  70682. return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
  70683. }
  70684. ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
  70685. function getSyntheticTrailingComments(node) {
  70686. var emitNode = node.emitNode;
  70687. return emitNode && emitNode.trailingComments;
  70688. }
  70689. ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
  70690. function setSyntheticTrailingComments(node, comments) {
  70691. getOrCreateEmitNode(node).trailingComments = comments;
  70692. return node;
  70693. }
  70694. ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
  70695. function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
  70696. return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
  70697. }
  70698. ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
  70699. function moveSyntheticComments(node, original) {
  70700. setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
  70701. setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
  70702. var emit = getOrCreateEmitNode(original);
  70703. emit.leadingComments = undefined;
  70704. emit.trailingComments = undefined;
  70705. return node;
  70706. }
  70707. ts.moveSyntheticComments = moveSyntheticComments;
  70708. /**
  70709. * Gets the constant value to emit for an expression.
  70710. */
  70711. function getConstantValue(node) {
  70712. var emitNode = node.emitNode;
  70713. return emitNode && emitNode.constantValue;
  70714. }
  70715. ts.getConstantValue = getConstantValue;
  70716. /**
  70717. * Sets the constant value to emit for an expression.
  70718. */
  70719. function setConstantValue(node, value) {
  70720. var emitNode = getOrCreateEmitNode(node);
  70721. emitNode.constantValue = value;
  70722. return node;
  70723. }
  70724. ts.setConstantValue = setConstantValue;
  70725. /**
  70726. * Adds an EmitHelper to a node.
  70727. */
  70728. function addEmitHelper(node, helper) {
  70729. var emitNode = getOrCreateEmitNode(node);
  70730. emitNode.helpers = ts.append(emitNode.helpers, helper);
  70731. return node;
  70732. }
  70733. ts.addEmitHelper = addEmitHelper;
  70734. /**
  70735. * Add EmitHelpers to a node.
  70736. */
  70737. function addEmitHelpers(node, helpers) {
  70738. if (ts.some(helpers)) {
  70739. var emitNode = getOrCreateEmitNode(node);
  70740. for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
  70741. var helper = helpers_1[_i];
  70742. emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
  70743. }
  70744. }
  70745. return node;
  70746. }
  70747. ts.addEmitHelpers = addEmitHelpers;
  70748. /**
  70749. * Removes an EmitHelper from a node.
  70750. */
  70751. function removeEmitHelper(node, helper) {
  70752. var emitNode = node.emitNode;
  70753. if (emitNode) {
  70754. var helpers = emitNode.helpers;
  70755. if (helpers) {
  70756. return ts.orderedRemoveItem(helpers, helper);
  70757. }
  70758. }
  70759. return false;
  70760. }
  70761. ts.removeEmitHelper = removeEmitHelper;
  70762. /**
  70763. * Gets the EmitHelpers of a node.
  70764. */
  70765. function getEmitHelpers(node) {
  70766. var emitNode = node.emitNode;
  70767. return emitNode && emitNode.helpers;
  70768. }
  70769. ts.getEmitHelpers = getEmitHelpers;
  70770. /**
  70771. * Moves matching emit helpers from a source node to a target node.
  70772. */
  70773. function moveEmitHelpers(source, target, predicate) {
  70774. var sourceEmitNode = source.emitNode;
  70775. var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
  70776. if (!ts.some(sourceEmitHelpers))
  70777. return;
  70778. var targetEmitNode = getOrCreateEmitNode(target);
  70779. var helpersRemoved = 0;
  70780. for (var i = 0; i < sourceEmitHelpers.length; i++) {
  70781. var helper = sourceEmitHelpers[i];
  70782. if (predicate(helper)) {
  70783. helpersRemoved++;
  70784. targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
  70785. }
  70786. else if (helpersRemoved > 0) {
  70787. sourceEmitHelpers[i - helpersRemoved] = helper;
  70788. }
  70789. }
  70790. if (helpersRemoved > 0) {
  70791. sourceEmitHelpers.length -= helpersRemoved;
  70792. }
  70793. }
  70794. ts.moveEmitHelpers = moveEmitHelpers;
  70795. /* @internal */
  70796. function compareEmitHelpers(x, y) {
  70797. if (x === y)
  70798. return 0 /* EqualTo */;
  70799. if (x.priority === y.priority)
  70800. return 0 /* EqualTo */;
  70801. if (x.priority === undefined)
  70802. return 1 /* GreaterThan */;
  70803. if (y.priority === undefined)
  70804. return -1 /* LessThan */;
  70805. return ts.compareValues(x.priority, y.priority);
  70806. }
  70807. ts.compareEmitHelpers = compareEmitHelpers;
  70808. function setOriginalNode(node, original) {
  70809. node.original = original;
  70810. if (original) {
  70811. var emitNode = original.emitNode;
  70812. if (emitNode)
  70813. node.emitNode = mergeEmitNode(emitNode, node.emitNode);
  70814. }
  70815. return node;
  70816. }
  70817. ts.setOriginalNode = setOriginalNode;
  70818. function mergeEmitNode(sourceEmitNode, destEmitNode) {
  70819. var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine;
  70820. if (!destEmitNode)
  70821. destEmitNode = {};
  70822. // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
  70823. if (leadingComments)
  70824. destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
  70825. if (trailingComments)
  70826. destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
  70827. if (flags)
  70828. destEmitNode.flags = flags;
  70829. if (commentRange)
  70830. destEmitNode.commentRange = commentRange;
  70831. if (sourceMapRange)
  70832. destEmitNode.sourceMapRange = sourceMapRange;
  70833. if (tokenSourceMapRanges)
  70834. destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
  70835. if (constantValue !== undefined)
  70836. destEmitNode.constantValue = constantValue;
  70837. if (helpers)
  70838. destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
  70839. if (startsOnNewLine !== undefined)
  70840. destEmitNode.startsOnNewLine = startsOnNewLine;
  70841. return destEmitNode;
  70842. }
  70843. function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
  70844. if (!destRanges)
  70845. destRanges = [];
  70846. for (var key in sourceRanges) {
  70847. destRanges[key] = sourceRanges[key];
  70848. }
  70849. return destRanges;
  70850. }
  70851. })(ts || (ts = {}));
  70852. /* @internal */
  70853. var ts;
  70854. (function (ts) {
  70855. ts.nullTransformationContext = {
  70856. enableEmitNotification: ts.noop,
  70857. enableSubstitution: ts.noop,
  70858. endLexicalEnvironment: ts.returnUndefined,
  70859. getCompilerOptions: ts.notImplemented,
  70860. getEmitHost: ts.notImplemented,
  70861. getEmitResolver: ts.notImplemented,
  70862. hoistFunctionDeclaration: ts.noop,
  70863. hoistVariableDeclaration: ts.noop,
  70864. isEmitNotificationEnabled: ts.notImplemented,
  70865. isSubstitutionEnabled: ts.notImplemented,
  70866. onEmitNode: ts.noop,
  70867. onSubstituteNode: ts.notImplemented,
  70868. readEmitHelpers: ts.notImplemented,
  70869. requestEmitHelper: ts.noop,
  70870. resumeLexicalEnvironment: ts.noop,
  70871. startLexicalEnvironment: ts.noop,
  70872. suspendLexicalEnvironment: ts.noop,
  70873. addDiagnostic: ts.noop,
  70874. };
  70875. function createTypeCheck(value, tag) {
  70876. return tag === "undefined"
  70877. ? ts.createStrictEquality(value, ts.createVoidZero())
  70878. : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
  70879. }
  70880. ts.createTypeCheck = createTypeCheck;
  70881. function createMemberAccessForPropertyName(target, memberName, location) {
  70882. if (ts.isComputedPropertyName(memberName)) {
  70883. return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
  70884. }
  70885. else {
  70886. var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
  70887. ? ts.createPropertyAccess(target, memberName)
  70888. : ts.createElementAccess(target, memberName), memberName);
  70889. ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
  70890. return expression;
  70891. }
  70892. }
  70893. ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
  70894. function createFunctionCall(func, thisArg, argumentsList, location) {
  70895. return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"),
  70896. /*typeArguments*/ undefined, __spreadArrays([
  70897. thisArg
  70898. ], argumentsList)), location);
  70899. }
  70900. ts.createFunctionCall = createFunctionCall;
  70901. function createFunctionApply(func, thisArg, argumentsExpression, location) {
  70902. return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"),
  70903. /*typeArguments*/ undefined, [
  70904. thisArg,
  70905. argumentsExpression
  70906. ]), location);
  70907. }
  70908. ts.createFunctionApply = createFunctionApply;
  70909. function createArraySlice(array, start) {
  70910. var argumentsList = [];
  70911. if (start !== undefined) {
  70912. argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
  70913. }
  70914. return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
  70915. }
  70916. ts.createArraySlice = createArraySlice;
  70917. function createArrayConcat(array, values) {
  70918. return ts.createCall(ts.createPropertyAccess(array, "concat"),
  70919. /*typeArguments*/ undefined, values);
  70920. }
  70921. ts.createArrayConcat = createArrayConcat;
  70922. function createMathPow(left, right, location) {
  70923. return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"),
  70924. /*typeArguments*/ undefined, [left, right]), location);
  70925. }
  70926. ts.createMathPow = createMathPow;
  70927. function createReactNamespace(reactNamespace, parent) {
  70928. // To ensure the emit resolver can properly resolve the namespace, we need to
  70929. // treat this identifier as if it were a source tree node by clearing the `Synthesized`
  70930. // flag and setting a parent node.
  70931. var react = ts.createIdentifier(reactNamespace || "React");
  70932. react.flags &= ~8 /* Synthesized */;
  70933. // Set the parent that is in parse tree
  70934. // this makes sure that parent chain is intact for checker to traverse complete scope tree
  70935. react.parent = ts.getParseTreeNode(parent);
  70936. return react;
  70937. }
  70938. function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
  70939. if (ts.isQualifiedName(jsxFactory)) {
  70940. var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
  70941. var right = ts.createIdentifier(ts.idText(jsxFactory.right));
  70942. right.escapedText = jsxFactory.right.escapedText;
  70943. return ts.createPropertyAccess(left, right);
  70944. }
  70945. else {
  70946. return createReactNamespace(ts.idText(jsxFactory), parent);
  70947. }
  70948. }
  70949. function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
  70950. return jsxFactoryEntity ?
  70951. createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
  70952. ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
  70953. }
  70954. function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
  70955. var argumentsList = [tagName];
  70956. if (props) {
  70957. argumentsList.push(props);
  70958. }
  70959. if (children && children.length > 0) {
  70960. if (!props) {
  70961. argumentsList.push(ts.createNull());
  70962. }
  70963. if (children.length > 1) {
  70964. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  70965. var child = children_2[_i];
  70966. startOnNewLine(child);
  70967. argumentsList.push(child);
  70968. }
  70969. }
  70970. else {
  70971. argumentsList.push(children[0]);
  70972. }
  70973. }
  70974. return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
  70975. /*typeArguments*/ undefined, argumentsList), location);
  70976. }
  70977. ts.createExpressionForJsxElement = createExpressionForJsxElement;
  70978. function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
  70979. var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
  70980. var argumentsList = [tagName];
  70981. argumentsList.push(ts.createNull());
  70982. if (children && children.length > 0) {
  70983. if (children.length > 1) {
  70984. for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
  70985. var child = children_3[_i];
  70986. startOnNewLine(child);
  70987. argumentsList.push(child);
  70988. }
  70989. }
  70990. else {
  70991. argumentsList.push(children[0]);
  70992. }
  70993. }
  70994. return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
  70995. /*typeArguments*/ undefined, argumentsList), location);
  70996. }
  70997. ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
  70998. // Helpers
  70999. /**
  71000. * Gets an identifier for the name of an *unscoped* emit helper.
  71001. */
  71002. function getUnscopedHelperName(name) {
  71003. return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
  71004. }
  71005. ts.getUnscopedHelperName = getUnscopedHelperName;
  71006. ts.valuesHelper = {
  71007. name: "typescript:values",
  71008. importName: "__values",
  71009. scoped: false,
  71010. text: "\n var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n };"
  71011. };
  71012. function createValuesHelper(context, expression, location) {
  71013. context.requestEmitHelper(ts.valuesHelper);
  71014. return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"),
  71015. /*typeArguments*/ undefined, [expression]), location);
  71016. }
  71017. ts.createValuesHelper = createValuesHelper;
  71018. ts.readHelper = {
  71019. name: "typescript:read",
  71020. importName: "__read",
  71021. scoped: false,
  71022. text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
  71023. };
  71024. function createReadHelper(context, iteratorRecord, count, location) {
  71025. context.requestEmitHelper(ts.readHelper);
  71026. return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"),
  71027. /*typeArguments*/ undefined, count !== undefined
  71028. ? [iteratorRecord, ts.createLiteral(count)]
  71029. : [iteratorRecord]), location);
  71030. }
  71031. ts.createReadHelper = createReadHelper;
  71032. ts.spreadHelper = {
  71033. name: "typescript:spread",
  71034. importName: "__spread",
  71035. scoped: false,
  71036. text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
  71037. };
  71038. function createSpreadHelper(context, argumentList, location) {
  71039. context.requestEmitHelper(ts.readHelper);
  71040. context.requestEmitHelper(ts.spreadHelper);
  71041. return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"),
  71042. /*typeArguments*/ undefined, argumentList), location);
  71043. }
  71044. ts.createSpreadHelper = createSpreadHelper;
  71045. ts.spreadArraysHelper = {
  71046. name: "typescript:spreadArrays",
  71047. importName: "__spreadArrays",
  71048. scoped: false,
  71049. text: "\n var __spreadArrays = (this && this.__spreadArrays) || function () {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n };"
  71050. };
  71051. function createSpreadArraysHelper(context, argumentList, location) {
  71052. context.requestEmitHelper(ts.spreadArraysHelper);
  71053. return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"),
  71054. /*typeArguments*/ undefined, argumentList), location);
  71055. }
  71056. ts.createSpreadArraysHelper = createSpreadArraysHelper;
  71057. // Utilities
  71058. function createForOfBindingStatement(node, boundValue) {
  71059. if (ts.isVariableDeclarationList(node)) {
  71060. var firstDeclaration = ts.first(node.declarations);
  71061. var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name,
  71062. /*typeNode*/ undefined, boundValue);
  71063. return ts.setTextRange(ts.createVariableStatement(
  71064. /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])),
  71065. /*location*/ node);
  71066. }
  71067. else {
  71068. var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
  71069. return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
  71070. }
  71071. }
  71072. ts.createForOfBindingStatement = createForOfBindingStatement;
  71073. function insertLeadingStatement(dest, source) {
  71074. if (ts.isBlock(dest)) {
  71075. return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
  71076. }
  71077. else {
  71078. return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
  71079. }
  71080. }
  71081. ts.insertLeadingStatement = insertLeadingStatement;
  71082. function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
  71083. if (!outermostLabeledStatement) {
  71084. return node;
  71085. }
  71086. var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
  71087. ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
  71088. : node);
  71089. if (afterRestoreLabelCallback) {
  71090. afterRestoreLabelCallback(outermostLabeledStatement);
  71091. }
  71092. return updated;
  71093. }
  71094. ts.restoreEnclosingLabel = restoreEnclosingLabel;
  71095. function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
  71096. var target = ts.skipParentheses(node);
  71097. switch (target.kind) {
  71098. case 75 /* Identifier */:
  71099. return cacheIdentifiers;
  71100. case 104 /* ThisKeyword */:
  71101. case 8 /* NumericLiteral */:
  71102. case 9 /* BigIntLiteral */:
  71103. case 10 /* StringLiteral */:
  71104. return false;
  71105. case 192 /* ArrayLiteralExpression */:
  71106. var elements = target.elements;
  71107. if (elements.length === 0) {
  71108. return false;
  71109. }
  71110. return true;
  71111. case 193 /* ObjectLiteralExpression */:
  71112. return target.properties.length > 0;
  71113. default:
  71114. return true;
  71115. }
  71116. }
  71117. function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
  71118. if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
  71119. var callee = skipOuterExpressions(expression, 7 /* All */);
  71120. var thisArg;
  71121. var target;
  71122. if (ts.isSuperProperty(callee)) {
  71123. thisArg = ts.createThis();
  71124. target = callee;
  71125. }
  71126. else if (callee.kind === 102 /* SuperKeyword */) {
  71127. thisArg = ts.createThis();
  71128. target = languageVersion < 2 /* ES2015 */
  71129. ? ts.setTextRange(ts.createIdentifier("_super"), callee)
  71130. : callee;
  71131. }
  71132. else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
  71133. thisArg = ts.createVoidZero();
  71134. target = parenthesizeForAccess(callee);
  71135. }
  71136. else {
  71137. switch (callee.kind) {
  71138. case 194 /* PropertyAccessExpression */: {
  71139. if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
  71140. // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
  71141. thisArg = ts.createTempVariable(recordTempVariable);
  71142. target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
  71143. ts.setTextRange(target, callee);
  71144. }
  71145. else {
  71146. thisArg = callee.expression;
  71147. target = callee;
  71148. }
  71149. break;
  71150. }
  71151. case 195 /* ElementAccessExpression */: {
  71152. if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
  71153. // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
  71154. thisArg = ts.createTempVariable(recordTempVariable);
  71155. target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
  71156. ts.setTextRange(target, callee);
  71157. }
  71158. else {
  71159. thisArg = callee.expression;
  71160. target = callee;
  71161. }
  71162. break;
  71163. }
  71164. default: {
  71165. // for `a()` target is `a` and thisArg is `void 0`
  71166. thisArg = ts.createVoidZero();
  71167. target = parenthesizeForAccess(expression);
  71168. break;
  71169. }
  71170. }
  71171. }
  71172. return { target: target, thisArg: thisArg };
  71173. }
  71174. ts.createCallBinding = createCallBinding;
  71175. function inlineExpressions(expressions) {
  71176. // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
  71177. // stack size exceeded" errors.
  71178. return expressions.length > 10
  71179. ? ts.createCommaList(expressions)
  71180. : ts.reduceLeft(expressions, ts.createComma);
  71181. }
  71182. ts.inlineExpressions = inlineExpressions;
  71183. function createExpressionFromEntityName(node) {
  71184. if (ts.isQualifiedName(node)) {
  71185. var left = createExpressionFromEntityName(node.left);
  71186. var right = ts.getMutableClone(node.right);
  71187. return ts.setTextRange(ts.createPropertyAccess(left, right), node);
  71188. }
  71189. else {
  71190. return ts.getMutableClone(node);
  71191. }
  71192. }
  71193. ts.createExpressionFromEntityName = createExpressionFromEntityName;
  71194. function createExpressionForPropertyName(memberName) {
  71195. if (ts.isIdentifier(memberName)) {
  71196. return ts.createLiteral(memberName);
  71197. }
  71198. else if (ts.isComputedPropertyName(memberName)) {
  71199. return ts.getMutableClone(memberName.expression);
  71200. }
  71201. else {
  71202. return ts.getMutableClone(memberName);
  71203. }
  71204. }
  71205. ts.createExpressionForPropertyName = createExpressionForPropertyName;
  71206. function createExpressionForObjectLiteralElementLike(node, property, receiver) {
  71207. if (property.name && ts.isPrivateIdentifier(property.name)) {
  71208. ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
  71209. }
  71210. switch (property.kind) {
  71211. case 163 /* GetAccessor */:
  71212. case 164 /* SetAccessor */:
  71213. return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
  71214. case 281 /* PropertyAssignment */:
  71215. return createExpressionForPropertyAssignment(property, receiver);
  71216. case 282 /* ShorthandPropertyAssignment */:
  71217. return createExpressionForShorthandPropertyAssignment(property, receiver);
  71218. case 161 /* MethodDeclaration */:
  71219. return createExpressionForMethodDeclaration(property, receiver);
  71220. }
  71221. }
  71222. ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
  71223. function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
  71224. var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
  71225. if (property === firstAccessor) {
  71226. var properties_5 = [];
  71227. if (getAccessor) {
  71228. var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
  71229. /*asteriskToken*/ undefined,
  71230. /*name*/ undefined,
  71231. /*typeParameters*/ undefined, getAccessor.parameters,
  71232. /*type*/ undefined, getAccessor.body // TODO: GH#18217
  71233. );
  71234. ts.setTextRange(getterFunction, getAccessor);
  71235. ts.setOriginalNode(getterFunction, getAccessor);
  71236. var getter = ts.createPropertyAssignment("get", getterFunction);
  71237. properties_5.push(getter);
  71238. }
  71239. if (setAccessor) {
  71240. var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
  71241. /*asteriskToken*/ undefined,
  71242. /*name*/ undefined,
  71243. /*typeParameters*/ undefined, setAccessor.parameters,
  71244. /*type*/ undefined, setAccessor.body // TODO: GH#18217
  71245. );
  71246. ts.setTextRange(setterFunction, setAccessor);
  71247. ts.setOriginalNode(setterFunction, setAccessor);
  71248. var setter = ts.createPropertyAssignment("set", setterFunction);
  71249. properties_5.push(setter);
  71250. }
  71251. properties_5.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
  71252. properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
  71253. var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
  71254. /*typeArguments*/ undefined, [
  71255. receiver,
  71256. createExpressionForPropertyName(property.name),
  71257. ts.createObjectLiteral(properties_5, multiLine)
  71258. ]),
  71259. /*location*/ firstAccessor);
  71260. return ts.aggregateTransformFlags(expression);
  71261. }
  71262. return undefined;
  71263. }
  71264. function createExpressionForPropertyAssignment(property, receiver) {
  71265. return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
  71266. }
  71267. function createExpressionForShorthandPropertyAssignment(property, receiver) {
  71268. return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)),
  71269. /*location*/ property),
  71270. /*original*/ property));
  71271. }
  71272. function createExpressionForMethodDeclaration(method, receiver) {
  71273. return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken,
  71274. /*name*/ undefined,
  71275. /*typeParameters*/ undefined, method.parameters,
  71276. /*type*/ undefined, method.body // TODO: GH#18217
  71277. ),
  71278. /*location*/ method),
  71279. /*original*/ method)),
  71280. /*location*/ method),
  71281. /*original*/ method));
  71282. }
  71283. /**
  71284. * Gets the internal name of a declaration. This is primarily used for declarations that can be
  71285. * referred to by name in the body of an ES5 class function body. An internal name will *never*
  71286. * be prefixed with an module or namespace export modifier like "exports." when emitted as an
  71287. * expression. An internal name will also *never* be renamed due to a collision with a block
  71288. * scoped variable.
  71289. *
  71290. * @param node The declaration.
  71291. * @param allowComments A value indicating whether comments may be emitted for the name.
  71292. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
  71293. */
  71294. function getInternalName(node, allowComments, allowSourceMaps) {
  71295. return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
  71296. }
  71297. ts.getInternalName = getInternalName;
  71298. /**
  71299. * Gets whether an identifier should only be referred to by its internal name.
  71300. */
  71301. function isInternalName(node) {
  71302. return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
  71303. }
  71304. ts.isInternalName = isInternalName;
  71305. /**
  71306. * Gets the local name of a declaration. This is primarily used for declarations that can be
  71307. * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
  71308. * local name will *never* be prefixed with an module or namespace export modifier like
  71309. * "exports." when emitted as an expression.
  71310. *
  71311. * @param node The declaration.
  71312. * @param allowComments A value indicating whether comments may be emitted for the name.
  71313. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
  71314. */
  71315. function getLocalName(node, allowComments, allowSourceMaps) {
  71316. return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
  71317. }
  71318. ts.getLocalName = getLocalName;
  71319. /**
  71320. * Gets whether an identifier should only be referred to by its local name.
  71321. */
  71322. function isLocalName(node) {
  71323. return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
  71324. }
  71325. ts.isLocalName = isLocalName;
  71326. /**
  71327. * Gets the export name of a declaration. This is primarily used for declarations that can be
  71328. * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
  71329. * export name will *always* be prefixed with an module or namespace export modifier like
  71330. * `"exports."` when emitted as an expression if the name points to an exported symbol.
  71331. *
  71332. * @param node The declaration.
  71333. * @param allowComments A value indicating whether comments may be emitted for the name.
  71334. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
  71335. */
  71336. function getExportName(node, allowComments, allowSourceMaps) {
  71337. return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
  71338. }
  71339. ts.getExportName = getExportName;
  71340. /**
  71341. * Gets whether an identifier should only be referred to by its export representation if the
  71342. * name points to an exported symbol.
  71343. */
  71344. function isExportName(node) {
  71345. return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
  71346. }
  71347. ts.isExportName = isExportName;
  71348. /**
  71349. * Gets the name of a declaration for use in declarations.
  71350. *
  71351. * @param node The declaration.
  71352. * @param allowComments A value indicating whether comments may be emitted for the name.
  71353. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
  71354. */
  71355. function getDeclarationName(node, allowComments, allowSourceMaps) {
  71356. return getName(node, allowComments, allowSourceMaps);
  71357. }
  71358. ts.getDeclarationName = getDeclarationName;
  71359. function getName(node, allowComments, allowSourceMaps, emitFlags) {
  71360. if (emitFlags === void 0) { emitFlags = 0; }
  71361. var nodeName = ts.getNameOfDeclaration(node);
  71362. if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
  71363. var name = ts.getMutableClone(nodeName);
  71364. emitFlags |= ts.getEmitFlags(nodeName);
  71365. if (!allowSourceMaps)
  71366. emitFlags |= 48 /* NoSourceMap */;
  71367. if (!allowComments)
  71368. emitFlags |= 1536 /* NoComments */;
  71369. if (emitFlags)
  71370. ts.setEmitFlags(name, emitFlags);
  71371. return name;
  71372. }
  71373. return ts.getGeneratedNameForNode(node);
  71374. }
  71375. /**
  71376. * Gets the exported name of a declaration for use in expressions.
  71377. *
  71378. * An exported name will *always* be prefixed with an module or namespace export modifier like
  71379. * "exports." if the name points to an exported symbol.
  71380. *
  71381. * @param ns The namespace identifier.
  71382. * @param node The declaration.
  71383. * @param allowComments A value indicating whether comments may be emitted for the name.
  71384. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
  71385. */
  71386. function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
  71387. if (ns && ts.hasModifier(node, 1 /* Export */)) {
  71388. return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
  71389. }
  71390. return getExportName(node, allowComments, allowSourceMaps);
  71391. }
  71392. ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
  71393. /**
  71394. * Gets a namespace-qualified name for use in expressions.
  71395. *
  71396. * @param ns The namespace identifier.
  71397. * @param name The name.
  71398. * @param allowComments A value indicating whether comments may be emitted for the name.
  71399. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
  71400. */
  71401. function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
  71402. var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
  71403. ts.setTextRange(qualifiedName, name);
  71404. var emitFlags = 0;
  71405. if (!allowSourceMaps)
  71406. emitFlags |= 48 /* NoSourceMap */;
  71407. if (!allowComments)
  71408. emitFlags |= 1536 /* NoComments */;
  71409. if (emitFlags)
  71410. ts.setEmitFlags(qualifiedName, emitFlags);
  71411. return qualifiedName;
  71412. }
  71413. ts.getNamespaceMemberName = getNamespaceMemberName;
  71414. function convertToFunctionBody(node, multiLine) {
  71415. return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
  71416. }
  71417. ts.convertToFunctionBody = convertToFunctionBody;
  71418. function convertFunctionDeclarationToExpression(node) {
  71419. if (!node.body)
  71420. return ts.Debug.fail();
  71421. var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
  71422. ts.setOriginalNode(updated, node);
  71423. ts.setTextRange(updated, node);
  71424. if (ts.getStartsOnNewLine(node)) {
  71425. ts.setStartsOnNewLine(updated, /*newLine*/ true);
  71426. }
  71427. ts.aggregateTransformFlags(updated);
  71428. return updated;
  71429. }
  71430. ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
  71431. function isUseStrictPrologue(node) {
  71432. return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
  71433. }
  71434. /**
  71435. * Add any necessary prologue-directives into target statement-array.
  71436. * The function needs to be called during each transformation step.
  71437. * This function needs to be called whenever we transform the statement
  71438. * list of a source file, namespace, or function-like body.
  71439. *
  71440. * @param target: result statements array
  71441. * @param source: origin statements array
  71442. * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
  71443. * @param visitor: Optional callback used to visit any custom prologue directives.
  71444. */
  71445. function addPrologue(target, source, ensureUseStrict, visitor) {
  71446. var offset = addStandardPrologue(target, source, ensureUseStrict);
  71447. return addCustomPrologue(target, source, offset, visitor);
  71448. }
  71449. ts.addPrologue = addPrologue;
  71450. /**
  71451. * Add just the standard (string-expression) prologue-directives into target statement-array.
  71452. * The function needs to be called during each transformation step.
  71453. * This function needs to be called whenever we transform the statement
  71454. * list of a source file, namespace, or function-like body.
  71455. */
  71456. function addStandardPrologue(target, source, ensureUseStrict) {
  71457. ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
  71458. var foundUseStrict = false;
  71459. var statementOffset = 0;
  71460. var numStatements = source.length;
  71461. while (statementOffset < numStatements) {
  71462. var statement = source[statementOffset];
  71463. if (ts.isPrologueDirective(statement)) {
  71464. if (isUseStrictPrologue(statement)) {
  71465. foundUseStrict = true;
  71466. }
  71467. target.push(statement);
  71468. }
  71469. else {
  71470. break;
  71471. }
  71472. statementOffset++;
  71473. }
  71474. if (ensureUseStrict && !foundUseStrict) {
  71475. target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
  71476. }
  71477. return statementOffset;
  71478. }
  71479. ts.addStandardPrologue = addStandardPrologue;
  71480. function addCustomPrologue(target, source, statementOffset, visitor) {
  71481. var numStatements = source.length;
  71482. while (statementOffset !== undefined && statementOffset < numStatements) {
  71483. var statement = source[statementOffset];
  71484. if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) {
  71485. ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
  71486. }
  71487. else {
  71488. break;
  71489. }
  71490. statementOffset++;
  71491. }
  71492. return statementOffset;
  71493. }
  71494. ts.addCustomPrologue = addCustomPrologue;
  71495. function findUseStrictPrologue(statements) {
  71496. for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
  71497. var statement = statements_4[_i];
  71498. if (ts.isPrologueDirective(statement)) {
  71499. if (isUseStrictPrologue(statement)) {
  71500. return statement;
  71501. }
  71502. }
  71503. else {
  71504. break;
  71505. }
  71506. }
  71507. return undefined;
  71508. }
  71509. ts.findUseStrictPrologue = findUseStrictPrologue;
  71510. function startsWithUseStrict(statements) {
  71511. var firstStatement = ts.firstOrUndefined(statements);
  71512. return firstStatement !== undefined
  71513. && ts.isPrologueDirective(firstStatement)
  71514. && isUseStrictPrologue(firstStatement);
  71515. }
  71516. ts.startsWithUseStrict = startsWithUseStrict;
  71517. /**
  71518. * Ensures "use strict" directive is added
  71519. *
  71520. * @param statements An array of statements
  71521. */
  71522. function ensureUseStrict(statements) {
  71523. var foundUseStrict = findUseStrictPrologue(statements);
  71524. if (!foundUseStrict) {
  71525. return ts.setTextRange(ts.createNodeArray(__spreadArrays([
  71526. startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
  71527. ], statements)), statements);
  71528. }
  71529. return statements;
  71530. }
  71531. ts.ensureUseStrict = ensureUseStrict;
  71532. /**
  71533. * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
  71534. * order of operations.
  71535. *
  71536. * @param binaryOperator The operator for the BinaryExpression.
  71537. * @param operand The operand for the BinaryExpression.
  71538. * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
  71539. * BinaryExpression.
  71540. */
  71541. function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
  71542. var skipped = ts.skipPartiallyEmittedExpressions(operand);
  71543. // If the resulting expression is already parenthesized, we do not need to do any further processing.
  71544. if (skipped.kind === 200 /* ParenthesizedExpression */) {
  71545. return operand;
  71546. }
  71547. return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
  71548. ? ts.createParen(operand)
  71549. : operand;
  71550. }
  71551. ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
  71552. /**
  71553. * Determines whether the operand to a BinaryExpression needs to be parenthesized.
  71554. *
  71555. * @param binaryOperator The operator for the BinaryExpression.
  71556. * @param operand The operand for the BinaryExpression.
  71557. * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
  71558. * BinaryExpression.
  71559. */
  71560. function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
  71561. // If the operand has lower precedence, then it needs to be parenthesized to preserve the
  71562. // intent of the expression. For example, if the operand is `a + b` and the operator is
  71563. // `*`, then we need to parenthesize the operand to preserve the intended order of
  71564. // operations: `(a + b) * x`.
  71565. //
  71566. // If the operand has higher precedence, then it does not need to be parenthesized. For
  71567. // example, if the operand is `a * b` and the operator is `+`, then we do not need to
  71568. // parenthesize to preserve the intended order of operations: `a * b + x`.
  71569. //
  71570. // If the operand has the same precedence, then we need to check the associativity of
  71571. // the operator based on whether this is the left or right operand of the expression.
  71572. //
  71573. // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
  71574. // to preserve the intended order of operations: `x * (a / d)`
  71575. //
  71576. // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
  71577. // the intended order of operations: `(a ** b) ** c`
  71578. var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
  71579. var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
  71580. var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
  71581. if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
  71582. // We need to parenthesize arrow functions on the right side to avoid it being
  71583. // parsed as parenthesized expression: `a && (() => {})`
  71584. return true;
  71585. }
  71586. var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
  71587. switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
  71588. case -1 /* LessThan */:
  71589. // If the operand is the right side of a right-associative binary operation
  71590. // and is a yield expression, then we do not need parentheses.
  71591. if (!isLeftSideOfBinary
  71592. && binaryOperatorAssociativity === 1 /* Right */
  71593. && operand.kind === 212 /* YieldExpression */) {
  71594. return false;
  71595. }
  71596. return true;
  71597. case 1 /* GreaterThan */:
  71598. return false;
  71599. case 0 /* EqualTo */:
  71600. if (isLeftSideOfBinary) {
  71601. // No need to parenthesize the left operand when the binary operator is
  71602. // left associative:
  71603. // (a*b)/x -> a*b/x
  71604. // (a**b)/x -> a**b/x
  71605. //
  71606. // Parentheses are needed for the left operand when the binary operator is
  71607. // right associative:
  71608. // (a/b)**x -> (a/b)**x
  71609. // (a**b)**x -> (a**b)**x
  71610. return binaryOperatorAssociativity === 1 /* Right */;
  71611. }
  71612. else {
  71613. if (ts.isBinaryExpression(emittedOperand)
  71614. && emittedOperand.operatorToken.kind === binaryOperator) {
  71615. // No need to parenthesize the right operand when the binary operator and
  71616. // operand are the same and one of the following:
  71617. // x*(a*b) => x*a*b
  71618. // x|(a|b) => x|a|b
  71619. // x&(a&b) => x&a&b
  71620. // x^(a^b) => x^a^b
  71621. if (operatorHasAssociativeProperty(binaryOperator)) {
  71622. return false;
  71623. }
  71624. // No need to parenthesize the right operand when the binary operator
  71625. // is plus (+) if both the left and right operands consist solely of either
  71626. // literals of the same kind or binary plus (+) expressions for literals of
  71627. // the same kind (recursively).
  71628. // "a"+(1+2) => "a"+(1+2)
  71629. // "a"+("b"+"c") => "a"+"b"+"c"
  71630. if (binaryOperator === 39 /* PlusToken */) {
  71631. var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
  71632. if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
  71633. return false;
  71634. }
  71635. }
  71636. }
  71637. // No need to parenthesize the right operand when the operand is right
  71638. // associative:
  71639. // x/(a**b) -> x/a**b
  71640. // x**(a**b) -> x**a**b
  71641. //
  71642. // Parentheses are needed for the right operand when the operand is left
  71643. // associative:
  71644. // x/(a*b) -> x/(a*b)
  71645. // x**(a/b) -> x**(a/b)
  71646. var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
  71647. return operandAssociativity === 0 /* Left */;
  71648. }
  71649. }
  71650. }
  71651. /**
  71652. * Determines whether a binary operator is mathematically associative.
  71653. *
  71654. * @param binaryOperator The binary operator.
  71655. */
  71656. function operatorHasAssociativeProperty(binaryOperator) {
  71657. // The following operators are associative in JavaScript:
  71658. // (a*b)*c -> a*(b*c) -> a*b*c
  71659. // (a|b)|c -> a|(b|c) -> a|b|c
  71660. // (a&b)&c -> a&(b&c) -> a&b&c
  71661. // (a^b)^c -> a^(b^c) -> a^b^c
  71662. //
  71663. // While addition is associative in mathematics, JavaScript's `+` is not
  71664. // guaranteed to be associative as it is overloaded with string concatenation.
  71665. return binaryOperator === 41 /* AsteriskToken */
  71666. || binaryOperator === 51 /* BarToken */
  71667. || binaryOperator === 50 /* AmpersandToken */
  71668. || binaryOperator === 52 /* CaretToken */;
  71669. }
  71670. /**
  71671. * This function determines whether an expression consists of a homogeneous set of
  71672. * literal expressions or binary plus expressions that all share the same literal kind.
  71673. * It is used to determine whether the right-hand operand of a binary plus expression can be
  71674. * emitted without parentheses.
  71675. */
  71676. function getLiteralKindOfBinaryPlusOperand(node) {
  71677. node = ts.skipPartiallyEmittedExpressions(node);
  71678. if (ts.isLiteralKind(node.kind)) {
  71679. return node.kind;
  71680. }
  71681. if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
  71682. if (node.cachedLiteralKind !== undefined) {
  71683. return node.cachedLiteralKind;
  71684. }
  71685. var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
  71686. var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
  71687. 0 /* Unknown */;
  71688. node.cachedLiteralKind = literalKind;
  71689. return literalKind;
  71690. }
  71691. return 0 /* Unknown */;
  71692. }
  71693. function parenthesizeForConditionalHead(condition) {
  71694. var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
  71695. var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
  71696. var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
  71697. if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
  71698. return ts.createParen(condition);
  71699. }
  71700. return condition;
  71701. }
  71702. ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
  71703. function parenthesizeSubexpressionOfConditionalExpression(e) {
  71704. // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
  71705. // so in case when comma expression is introduced as a part of previous transformations
  71706. // if should be wrapped in parens since comma operator has the lowest precedence
  71707. var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
  71708. return isCommaSequence(emittedExpression)
  71709. ? ts.createParen(e)
  71710. : e;
  71711. }
  71712. ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
  71713. /**
  71714. * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
  71715. * has a lookahead restriction for `function`, `async function`, and `class`.
  71716. *
  71717. * Basically, that means we need to parenthesize in the following cases:
  71718. *
  71719. * - BinaryExpression of CommaToken
  71720. * - CommaList (synthetic list of multiple comma expressions)
  71721. * - FunctionExpression
  71722. * - ClassExpression
  71723. */
  71724. function parenthesizeDefaultExpression(e) {
  71725. var check = ts.skipPartiallyEmittedExpressions(e);
  71726. var needsParens = isCommaSequence(check);
  71727. if (!needsParens) {
  71728. switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
  71729. case 214 /* ClassExpression */:
  71730. case 201 /* FunctionExpression */:
  71731. needsParens = true;
  71732. }
  71733. }
  71734. return needsParens ? ts.createParen(e) : e;
  71735. }
  71736. ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
  71737. /**
  71738. * Wraps an expression in parentheses if it is needed in order to use the expression
  71739. * as the expression of a NewExpression node.
  71740. *
  71741. * @param expression The Expression node.
  71742. */
  71743. function parenthesizeForNew(expression) {
  71744. var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
  71745. switch (leftmostExpr.kind) {
  71746. case 196 /* CallExpression */:
  71747. return ts.createParen(expression);
  71748. case 197 /* NewExpression */:
  71749. return !leftmostExpr.arguments
  71750. ? ts.createParen(expression)
  71751. : expression;
  71752. }
  71753. return parenthesizeForAccess(expression);
  71754. }
  71755. ts.parenthesizeForNew = parenthesizeForNew;
  71756. /**
  71757. * Wraps an expression in parentheses if it is needed in order to use the expression for
  71758. * property or element access.
  71759. *
  71760. * @param expr The expression node.
  71761. */
  71762. function parenthesizeForAccess(expression) {
  71763. // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
  71764. // to parenthesize the expression before a dot. The known exception is:
  71765. //
  71766. // NewExpression:
  71767. // new C.x -> not the same as (new C).x
  71768. //
  71769. var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
  71770. if (ts.isLeftHandSideExpression(emittedExpression)
  71771. && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
  71772. return expression;
  71773. }
  71774. return ts.setTextRange(ts.createParen(expression), expression);
  71775. }
  71776. ts.parenthesizeForAccess = parenthesizeForAccess;
  71777. function parenthesizePostfixOperand(operand) {
  71778. return ts.isLeftHandSideExpression(operand)
  71779. ? operand
  71780. : ts.setTextRange(ts.createParen(operand), operand);
  71781. }
  71782. ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
  71783. function parenthesizePrefixOperand(operand) {
  71784. return ts.isUnaryExpression(operand)
  71785. ? operand
  71786. : ts.setTextRange(ts.createParen(operand), operand);
  71787. }
  71788. ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
  71789. function parenthesizeListElements(elements) {
  71790. var result;
  71791. for (var i = 0; i < elements.length; i++) {
  71792. var element = parenthesizeExpressionForList(elements[i]);
  71793. if (result !== undefined || element !== elements[i]) {
  71794. if (result === undefined) {
  71795. result = elements.slice(0, i);
  71796. }
  71797. result.push(element);
  71798. }
  71799. }
  71800. if (result !== undefined) {
  71801. return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
  71802. }
  71803. return elements;
  71804. }
  71805. ts.parenthesizeListElements = parenthesizeListElements;
  71806. function parenthesizeExpressionForList(expression) {
  71807. var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
  71808. var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
  71809. var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
  71810. return expressionPrecedence > commaPrecedence
  71811. ? expression
  71812. : ts.setTextRange(ts.createParen(expression), expression);
  71813. }
  71814. ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
  71815. function parenthesizeExpressionForExpressionStatement(expression) {
  71816. var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
  71817. if (ts.isCallExpression(emittedExpression)) {
  71818. var callee = emittedExpression.expression;
  71819. var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
  71820. if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
  71821. var mutableCall = ts.getMutableClone(emittedExpression);
  71822. mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
  71823. return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */);
  71824. }
  71825. }
  71826. var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
  71827. if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
  71828. return ts.setTextRange(ts.createParen(expression), expression);
  71829. }
  71830. return expression;
  71831. }
  71832. ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
  71833. function parenthesizeConditionalTypeMember(member) {
  71834. return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
  71835. }
  71836. ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
  71837. function parenthesizeElementTypeMember(member) {
  71838. switch (member.kind) {
  71839. case 178 /* UnionType */:
  71840. case 179 /* IntersectionType */:
  71841. case 170 /* FunctionType */:
  71842. case 171 /* ConstructorType */:
  71843. return ts.createParenthesizedType(member);
  71844. }
  71845. return parenthesizeConditionalTypeMember(member);
  71846. }
  71847. ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
  71848. function parenthesizeArrayTypeMember(member) {
  71849. switch (member.kind) {
  71850. case 172 /* TypeQuery */:
  71851. case 184 /* TypeOperator */:
  71852. case 181 /* InferType */:
  71853. return ts.createParenthesizedType(member);
  71854. }
  71855. return parenthesizeElementTypeMember(member);
  71856. }
  71857. ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
  71858. function parenthesizeElementTypeMembers(members) {
  71859. return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
  71860. }
  71861. ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
  71862. function parenthesizeTypeParameters(typeParameters) {
  71863. if (ts.some(typeParameters)) {
  71864. var params = [];
  71865. for (var i = 0; i < typeParameters.length; ++i) {
  71866. var entry = typeParameters[i];
  71867. params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
  71868. ts.createParenthesizedType(entry) :
  71869. entry);
  71870. }
  71871. return ts.createNodeArray(params);
  71872. }
  71873. }
  71874. ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
  71875. function getLeftmostExpression(node, stopAtCallExpressions) {
  71876. while (true) {
  71877. switch (node.kind) {
  71878. case 208 /* PostfixUnaryExpression */:
  71879. node = node.operand;
  71880. continue;
  71881. case 209 /* BinaryExpression */:
  71882. node = node.left;
  71883. continue;
  71884. case 210 /* ConditionalExpression */:
  71885. node = node.condition;
  71886. continue;
  71887. case 198 /* TaggedTemplateExpression */:
  71888. node = node.tag;
  71889. continue;
  71890. case 196 /* CallExpression */:
  71891. if (stopAtCallExpressions) {
  71892. return node;
  71893. }
  71894. // falls through
  71895. case 217 /* AsExpression */:
  71896. case 195 /* ElementAccessExpression */:
  71897. case 194 /* PropertyAccessExpression */:
  71898. case 218 /* NonNullExpression */:
  71899. case 325 /* PartiallyEmittedExpression */:
  71900. node = node.expression;
  71901. continue;
  71902. }
  71903. return node;
  71904. }
  71905. }
  71906. ts.getLeftmostExpression = getLeftmostExpression;
  71907. function parenthesizeConciseBody(body) {
  71908. if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
  71909. return ts.setTextRange(ts.createParen(body), body);
  71910. }
  71911. return body;
  71912. }
  71913. ts.parenthesizeConciseBody = parenthesizeConciseBody;
  71914. function isCommaSequence(node) {
  71915. return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
  71916. node.kind === 326 /* CommaListExpression */;
  71917. }
  71918. ts.isCommaSequence = isCommaSequence;
  71919. var OuterExpressionKinds;
  71920. (function (OuterExpressionKinds) {
  71921. OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
  71922. OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions";
  71923. OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions";
  71924. OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All";
  71925. })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
  71926. function isOuterExpression(node, kinds) {
  71927. if (kinds === void 0) { kinds = 7 /* All */; }
  71928. switch (node.kind) {
  71929. case 200 /* ParenthesizedExpression */:
  71930. return (kinds & 1 /* Parentheses */) !== 0;
  71931. case 199 /* TypeAssertionExpression */:
  71932. case 217 /* AsExpression */:
  71933. case 218 /* NonNullExpression */:
  71934. return (kinds & 2 /* Assertions */) !== 0;
  71935. case 325 /* PartiallyEmittedExpression */:
  71936. return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
  71937. }
  71938. return false;
  71939. }
  71940. ts.isOuterExpression = isOuterExpression;
  71941. function skipOuterExpressions(node, kinds) {
  71942. if (kinds === void 0) { kinds = 7 /* All */; }
  71943. var previousNode;
  71944. do {
  71945. previousNode = node;
  71946. if (kinds & 1 /* Parentheses */) {
  71947. node = ts.skipParentheses(node);
  71948. }
  71949. if (kinds & 2 /* Assertions */) {
  71950. node = skipAssertions(node);
  71951. }
  71952. if (kinds & 4 /* PartiallyEmittedExpressions */) {
  71953. node = ts.skipPartiallyEmittedExpressions(node);
  71954. }
  71955. } while (previousNode !== node);
  71956. return node;
  71957. }
  71958. ts.skipOuterExpressions = skipOuterExpressions;
  71959. function skipAssertions(node) {
  71960. while (ts.isAssertionExpression(node) || node.kind === 218 /* NonNullExpression */) {
  71961. node = node.expression;
  71962. }
  71963. return node;
  71964. }
  71965. ts.skipAssertions = skipAssertions;
  71966. function updateOuterExpression(outerExpression, expression) {
  71967. switch (outerExpression.kind) {
  71968. case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
  71969. case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
  71970. case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
  71971. case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
  71972. case 325 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
  71973. }
  71974. }
  71975. /**
  71976. * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
  71977. *
  71978. * A parenthesized expression can be ignored when all of the following are true:
  71979. *
  71980. * - It's `pos` and `end` are not -1
  71981. * - It does not have a custom source map range
  71982. * - It does not have a custom comment range
  71983. * - It does not have synthetic leading or trailing comments
  71984. *
  71985. * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
  71986. * the expression to maintain precedence, a new parenthesized expression should be created automatically when
  71987. * the containing expression is created/updated.
  71988. */
  71989. function isIgnorableParen(node) {
  71990. return node.kind === 200 /* ParenthesizedExpression */
  71991. && ts.nodeIsSynthesized(node)
  71992. && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
  71993. && ts.nodeIsSynthesized(ts.getCommentRange(node))
  71994. && !ts.some(ts.getSyntheticLeadingComments(node))
  71995. && !ts.some(ts.getSyntheticTrailingComments(node));
  71996. }
  71997. function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
  71998. if (kinds === void 0) { kinds = 7 /* All */; }
  71999. if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
  72000. return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
  72001. }
  72002. return innerExpression;
  72003. }
  72004. ts.recreateOuterExpressions = recreateOuterExpressions;
  72005. function startOnNewLine(node) {
  72006. return ts.setStartsOnNewLine(node, /*newLine*/ true);
  72007. }
  72008. ts.startOnNewLine = startOnNewLine;
  72009. function getExternalHelpersModuleName(node) {
  72010. var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
  72011. var emitNode = parseNode && parseNode.emitNode;
  72012. return emitNode && emitNode.externalHelpersModuleName;
  72013. }
  72014. ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
  72015. function hasRecordedExternalHelpers(sourceFile) {
  72016. var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
  72017. var emitNode = parseNode && parseNode.emitNode;
  72018. return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
  72019. }
  72020. ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
  72021. function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
  72022. if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
  72023. var namedBindings = void 0;
  72024. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  72025. if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
  72026. // use named imports
  72027. var helpers = ts.getEmitHelpers(sourceFile);
  72028. if (helpers) {
  72029. var helperNames = [];
  72030. for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
  72031. var helper = helpers_2[_i];
  72032. if (!helper.scoped) {
  72033. var importName = helper.importName;
  72034. if (importName) {
  72035. ts.pushIfUnique(helperNames, importName);
  72036. }
  72037. }
  72038. }
  72039. if (ts.some(helperNames)) {
  72040. helperNames.sort(ts.compareStringsCaseSensitive);
  72041. // Alias the imports if the names are used somewhere in the file.
  72042. // NOTE: We don't need to care about global import collisions as this is a module.
  72043. namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
  72044. ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
  72045. : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
  72046. var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
  72047. var emitNode = ts.getOrCreateEmitNode(parseNode);
  72048. emitNode.externalHelpers = true;
  72049. }
  72050. }
  72051. }
  72052. else {
  72053. // use a namespace import
  72054. var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
  72055. if (externalHelpersModuleName) {
  72056. namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
  72057. }
  72058. }
  72059. if (namedBindings) {
  72060. var externalHelpersImportDeclaration = ts.createImportDeclaration(
  72061. /*decorators*/ undefined,
  72062. /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
  72063. ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
  72064. return externalHelpersImportDeclaration;
  72065. }
  72066. }
  72067. }
  72068. ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
  72069. function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
  72070. if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
  72071. var externalHelpersModuleName = getExternalHelpersModuleName(node);
  72072. if (externalHelpersModuleName) {
  72073. return externalHelpersModuleName;
  72074. }
  72075. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  72076. var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
  72077. && moduleKind !== ts.ModuleKind.System
  72078. && moduleKind < ts.ModuleKind.ES2015;
  72079. if (!create) {
  72080. var helpers = ts.getEmitHelpers(node);
  72081. if (helpers) {
  72082. for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
  72083. var helper = helpers_3[_i];
  72084. if (!helper.scoped) {
  72085. create = true;
  72086. break;
  72087. }
  72088. }
  72089. }
  72090. }
  72091. if (create) {
  72092. var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
  72093. var emitNode = ts.getOrCreateEmitNode(parseNode);
  72094. return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
  72095. }
  72096. }
  72097. }
  72098. ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
  72099. /**
  72100. * Get the name of that target module from an import or export declaration
  72101. */
  72102. function getLocalNameForExternalImport(node, sourceFile) {
  72103. var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
  72104. if (namespaceDeclaration && !ts.isDefaultImport(node)) {
  72105. var name = namespaceDeclaration.name;
  72106. return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
  72107. }
  72108. if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
  72109. return ts.getGeneratedNameForNode(node);
  72110. }
  72111. if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
  72112. return ts.getGeneratedNameForNode(node);
  72113. }
  72114. return undefined;
  72115. }
  72116. ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
  72117. /**
  72118. * Get the name of a target module from an import/export declaration as should be written in the emitted output.
  72119. * The emitted output name can be different from the input if:
  72120. * 1. The module has a /// <amd-module name="<new name>" />
  72121. * 2. --out or --outFile is used, making the name relative to the rootDir
  72122. * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
  72123. * Otherwise, a new StringLiteral node representing the module name will be returned.
  72124. */
  72125. function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
  72126. var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
  72127. if (moduleName.kind === 10 /* StringLiteral */) {
  72128. return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
  72129. || tryRenameExternalModule(moduleName, sourceFile)
  72130. || ts.getSynthesizedClone(moduleName);
  72131. }
  72132. return undefined;
  72133. }
  72134. ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
  72135. /**
  72136. * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
  72137. * Here we check if alternative name was provided for a given moduleName and return it if possible.
  72138. */
  72139. function tryRenameExternalModule(moduleName, sourceFile) {
  72140. var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
  72141. return rename && ts.createLiteral(rename);
  72142. }
  72143. /**
  72144. * Get the name of a module as should be written in the emitted output.
  72145. * The emitted output name can be different from the input if:
  72146. * 1. The module has a /// <amd-module name="<new name>" />
  72147. * 2. --out or --outFile is used, making the name relative to the rootDir
  72148. * Otherwise, a new StringLiteral node representing the module name will be returned.
  72149. */
  72150. function tryGetModuleNameFromFile(file, host, options) {
  72151. if (!file) {
  72152. return undefined;
  72153. }
  72154. if (file.moduleName) {
  72155. return ts.createLiteral(file.moduleName);
  72156. }
  72157. if (!file.isDeclarationFile && (options.out || options.outFile)) {
  72158. return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
  72159. }
  72160. return undefined;
  72161. }
  72162. ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
  72163. function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
  72164. return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
  72165. }
  72166. /**
  72167. * Gets the initializer of an BindingOrAssignmentElement.
  72168. */
  72169. function getInitializerOfBindingOrAssignmentElement(bindingElement) {
  72170. if (ts.isDeclarationBindingElement(bindingElement)) {
  72171. // `1` in `let { a = 1 } = ...`
  72172. // `1` in `let { a: b = 1 } = ...`
  72173. // `1` in `let { a: {b} = 1 } = ...`
  72174. // `1` in `let { a: [b] = 1 } = ...`
  72175. // `1` in `let [a = 1] = ...`
  72176. // `1` in `let [{a} = 1] = ...`
  72177. // `1` in `let [[a] = 1] = ...`
  72178. return bindingElement.initializer;
  72179. }
  72180. if (ts.isPropertyAssignment(bindingElement)) {
  72181. // `1` in `({ a: b = 1 } = ...)`
  72182. // `1` in `({ a: {b} = 1 } = ...)`
  72183. // `1` in `({ a: [b] = 1 } = ...)`
  72184. var initializer = bindingElement.initializer;
  72185. return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
  72186. ? initializer.right
  72187. : undefined;
  72188. }
  72189. if (ts.isShorthandPropertyAssignment(bindingElement)) {
  72190. // `1` in `({ a = 1 } = ...)`
  72191. return bindingElement.objectAssignmentInitializer;
  72192. }
  72193. if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
  72194. // `1` in `[a = 1] = ...`
  72195. // `1` in `[{a} = 1] = ...`
  72196. // `1` in `[[a] = 1] = ...`
  72197. return bindingElement.right;
  72198. }
  72199. if (ts.isSpreadElement(bindingElement)) {
  72200. // Recovery consistent with existing emit.
  72201. return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
  72202. }
  72203. }
  72204. ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
  72205. /**
  72206. * Gets the name of an BindingOrAssignmentElement.
  72207. */
  72208. function getTargetOfBindingOrAssignmentElement(bindingElement) {
  72209. if (ts.isDeclarationBindingElement(bindingElement)) {
  72210. // `a` in `let { a } = ...`
  72211. // `a` in `let { a = 1 } = ...`
  72212. // `b` in `let { a: b } = ...`
  72213. // `b` in `let { a: b = 1 } = ...`
  72214. // `a` in `let { ...a } = ...`
  72215. // `{b}` in `let { a: {b} } = ...`
  72216. // `{b}` in `let { a: {b} = 1 } = ...`
  72217. // `[b]` in `let { a: [b] } = ...`
  72218. // `[b]` in `let { a: [b] = 1 } = ...`
  72219. // `a` in `let [a] = ...`
  72220. // `a` in `let [a = 1] = ...`
  72221. // `a` in `let [...a] = ...`
  72222. // `{a}` in `let [{a}] = ...`
  72223. // `{a}` in `let [{a} = 1] = ...`
  72224. // `[a]` in `let [[a]] = ...`
  72225. // `[a]` in `let [[a] = 1] = ...`
  72226. return bindingElement.name;
  72227. }
  72228. if (ts.isObjectLiteralElementLike(bindingElement)) {
  72229. switch (bindingElement.kind) {
  72230. case 281 /* PropertyAssignment */:
  72231. // `b` in `({ a: b } = ...)`
  72232. // `b` in `({ a: b = 1 } = ...)`
  72233. // `{b}` in `({ a: {b} } = ...)`
  72234. // `{b}` in `({ a: {b} = 1 } = ...)`
  72235. // `[b]` in `({ a: [b] } = ...)`
  72236. // `[b]` in `({ a: [b] = 1 } = ...)`
  72237. // `b.c` in `({ a: b.c } = ...)`
  72238. // `b.c` in `({ a: b.c = 1 } = ...)`
  72239. // `b[0]` in `({ a: b[0] } = ...)`
  72240. // `b[0]` in `({ a: b[0] = 1 } = ...)`
  72241. return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
  72242. case 282 /* ShorthandPropertyAssignment */:
  72243. // `a` in `({ a } = ...)`
  72244. // `a` in `({ a = 1 } = ...)`
  72245. return bindingElement.name;
  72246. case 283 /* SpreadAssignment */:
  72247. // `a` in `({ ...a } = ...)`
  72248. return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
  72249. }
  72250. // no target
  72251. return undefined;
  72252. }
  72253. if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
  72254. // `a` in `[a = 1] = ...`
  72255. // `{a}` in `[{a} = 1] = ...`
  72256. // `[a]` in `[[a] = 1] = ...`
  72257. // `a.b` in `[a.b = 1] = ...`
  72258. // `a[0]` in `[a[0] = 1] = ...`
  72259. return getTargetOfBindingOrAssignmentElement(bindingElement.left);
  72260. }
  72261. if (ts.isSpreadElement(bindingElement)) {
  72262. // `a` in `[...a] = ...`
  72263. return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
  72264. }
  72265. // `a` in `[a] = ...`
  72266. // `{a}` in `[{a}] = ...`
  72267. // `[a]` in `[[a]] = ...`
  72268. // `a.b` in `[a.b] = ...`
  72269. // `a[0]` in `[a[0]] = ...`
  72270. return bindingElement;
  72271. }
  72272. ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
  72273. /**
  72274. * Determines whether an BindingOrAssignmentElement is a rest element.
  72275. */
  72276. function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
  72277. switch (bindingElement.kind) {
  72278. case 156 /* Parameter */:
  72279. case 191 /* BindingElement */:
  72280. // `...` in `let [...a] = ...`
  72281. return bindingElement.dotDotDotToken;
  72282. case 213 /* SpreadElement */:
  72283. case 283 /* SpreadAssignment */:
  72284. // `...` in `[...a] = ...`
  72285. return bindingElement;
  72286. }
  72287. return undefined;
  72288. }
  72289. ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
  72290. /**
  72291. * Gets the property name of a BindingOrAssignmentElement
  72292. */
  72293. function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
  72294. var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
  72295. ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
  72296. return propertyName;
  72297. }
  72298. ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
  72299. function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
  72300. switch (bindingElement.kind) {
  72301. case 191 /* BindingElement */:
  72302. // `a` in `let { a: b } = ...`
  72303. // `[a]` in `let { [a]: b } = ...`
  72304. // `"a"` in `let { "a": b } = ...`
  72305. // `1` in `let { 1: b } = ...`
  72306. if (bindingElement.propertyName) {
  72307. var propertyName = bindingElement.propertyName;
  72308. if (ts.isPrivateIdentifier(propertyName)) {
  72309. return ts.Debug.failBadSyntaxKind(propertyName);
  72310. }
  72311. return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
  72312. ? propertyName.expression
  72313. : propertyName;
  72314. }
  72315. break;
  72316. case 281 /* PropertyAssignment */:
  72317. // `a` in `({ a: b } = ...)`
  72318. // `[a]` in `({ [a]: b } = ...)`
  72319. // `"a"` in `({ "a": b } = ...)`
  72320. // `1` in `({ 1: b } = ...)`
  72321. if (bindingElement.name) {
  72322. var propertyName = bindingElement.name;
  72323. if (ts.isPrivateIdentifier(propertyName)) {
  72324. return ts.Debug.failBadSyntaxKind(propertyName);
  72325. }
  72326. return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
  72327. ? propertyName.expression
  72328. : propertyName;
  72329. }
  72330. break;
  72331. case 283 /* SpreadAssignment */:
  72332. // `a` in `({ ...a } = ...)`
  72333. if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
  72334. return ts.Debug.failBadSyntaxKind(bindingElement.name);
  72335. }
  72336. return bindingElement.name;
  72337. }
  72338. var target = getTargetOfBindingOrAssignmentElement(bindingElement);
  72339. if (target && ts.isPropertyName(target)) {
  72340. return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression)
  72341. ? target.expression
  72342. : target;
  72343. }
  72344. }
  72345. ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
  72346. function isStringOrNumericLiteral(node) {
  72347. var kind = node.kind;
  72348. return kind === 10 /* StringLiteral */
  72349. || kind === 8 /* NumericLiteral */;
  72350. }
  72351. /**
  72352. * Gets the elements of a BindingOrAssignmentPattern
  72353. */
  72354. function getElementsOfBindingOrAssignmentPattern(name) {
  72355. switch (name.kind) {
  72356. case 189 /* ObjectBindingPattern */:
  72357. case 190 /* ArrayBindingPattern */:
  72358. case 192 /* ArrayLiteralExpression */:
  72359. // `a` in `{a}`
  72360. // `a` in `[a]`
  72361. return name.elements;
  72362. case 193 /* ObjectLiteralExpression */:
  72363. // `a` in `{a}`
  72364. return name.properties;
  72365. }
  72366. }
  72367. ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
  72368. function convertToArrayAssignmentElement(element) {
  72369. if (ts.isBindingElement(element)) {
  72370. if (element.dotDotDotToken) {
  72371. ts.Debug.assertNode(element.name, ts.isIdentifier);
  72372. return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
  72373. }
  72374. var expression = convertToAssignmentElementTarget(element.name);
  72375. return element.initializer
  72376. ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
  72377. : expression;
  72378. }
  72379. ts.Debug.assertNode(element, ts.isExpression);
  72380. return element;
  72381. }
  72382. ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
  72383. function convertToObjectAssignmentElement(element) {
  72384. if (ts.isBindingElement(element)) {
  72385. if (element.dotDotDotToken) {
  72386. ts.Debug.assertNode(element.name, ts.isIdentifier);
  72387. return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
  72388. }
  72389. if (element.propertyName) {
  72390. var expression = convertToAssignmentElementTarget(element.name);
  72391. return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
  72392. }
  72393. ts.Debug.assertNode(element.name, ts.isIdentifier);
  72394. return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
  72395. }
  72396. ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
  72397. return element;
  72398. }
  72399. ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
  72400. function convertToAssignmentPattern(node) {
  72401. switch (node.kind) {
  72402. case 190 /* ArrayBindingPattern */:
  72403. case 192 /* ArrayLiteralExpression */:
  72404. return convertToArrayAssignmentPattern(node);
  72405. case 189 /* ObjectBindingPattern */:
  72406. case 193 /* ObjectLiteralExpression */:
  72407. return convertToObjectAssignmentPattern(node);
  72408. }
  72409. }
  72410. ts.convertToAssignmentPattern = convertToAssignmentPattern;
  72411. function convertToObjectAssignmentPattern(node) {
  72412. if (ts.isObjectBindingPattern(node)) {
  72413. return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
  72414. }
  72415. ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
  72416. return node;
  72417. }
  72418. ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
  72419. function convertToArrayAssignmentPattern(node) {
  72420. if (ts.isArrayBindingPattern(node)) {
  72421. return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
  72422. }
  72423. ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
  72424. return node;
  72425. }
  72426. ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
  72427. function convertToAssignmentElementTarget(node) {
  72428. if (ts.isBindingPattern(node)) {
  72429. return convertToAssignmentPattern(node);
  72430. }
  72431. ts.Debug.assertNode(node, ts.isExpression);
  72432. return node;
  72433. }
  72434. ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
  72435. })(ts || (ts = {}));
  72436. var ts;
  72437. (function (ts) {
  72438. var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
  72439. function visitNode(node, visitor, test, lift) {
  72440. if (node === undefined || visitor === undefined) {
  72441. return node;
  72442. }
  72443. ts.aggregateTransformFlags(node);
  72444. var visited = visitor(node);
  72445. if (visited === node) {
  72446. return node;
  72447. }
  72448. var visitedNode;
  72449. if (visited === undefined) {
  72450. return undefined;
  72451. }
  72452. else if (ts.isArray(visited)) {
  72453. visitedNode = (lift || extractSingleNode)(visited);
  72454. }
  72455. else {
  72456. visitedNode = visited;
  72457. }
  72458. ts.Debug.assertNode(visitedNode, test);
  72459. ts.aggregateTransformFlags(visitedNode);
  72460. return visitedNode;
  72461. }
  72462. ts.visitNode = visitNode;
  72463. /**
  72464. * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
  72465. *
  72466. * @param nodes The NodeArray to visit.
  72467. * @param visitor The callback used to visit a Node.
  72468. * @param test A node test to execute for each node.
  72469. * @param start An optional value indicating the starting offset at which to start visiting.
  72470. * @param count An optional value indicating the maximum number of nodes to visit.
  72471. */
  72472. function visitNodes(nodes, visitor, test, start, count) {
  72473. if (nodes === undefined || visitor === undefined) {
  72474. return nodes;
  72475. }
  72476. var updated;
  72477. // Ensure start and count have valid values
  72478. var length = nodes.length;
  72479. if (start === undefined || start < 0) {
  72480. start = 0;
  72481. }
  72482. if (count === undefined || count > length - start) {
  72483. count = length - start;
  72484. }
  72485. if (start > 0 || count < length) {
  72486. // If we are not visiting all of the original nodes, we must always create a new array.
  72487. // Since this is a fragment of a node array, we do not copy over the previous location
  72488. // and will only copy over `hasTrailingComma` if we are including the last element.
  72489. updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
  72490. }
  72491. // Visit each original node.
  72492. for (var i = 0; i < count; i++) {
  72493. var node = nodes[i + start];
  72494. ts.aggregateTransformFlags(node);
  72495. var visited = node !== undefined ? visitor(node) : undefined;
  72496. if (updated !== undefined || visited === undefined || visited !== node) {
  72497. if (updated === undefined) {
  72498. // Ensure we have a copy of `nodes`, up to the current index.
  72499. updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
  72500. ts.setTextRange(updated, nodes);
  72501. }
  72502. if (visited) {
  72503. if (ts.isArray(visited)) {
  72504. for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
  72505. var visitedNode = visited_1[_i];
  72506. ts.Debug.assertNode(visitedNode, test);
  72507. ts.aggregateTransformFlags(visitedNode);
  72508. updated.push(visitedNode);
  72509. }
  72510. }
  72511. else {
  72512. ts.Debug.assertNode(visited, test);
  72513. ts.aggregateTransformFlags(visited);
  72514. updated.push(visited);
  72515. }
  72516. }
  72517. }
  72518. }
  72519. return updated || nodes;
  72520. }
  72521. ts.visitNodes = visitNodes;
  72522. /**
  72523. * Starts a new lexical environment and visits a statement list, ending the lexical environment
  72524. * and merging hoisted declarations upon completion.
  72525. */
  72526. function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
  72527. context.startLexicalEnvironment();
  72528. statements = visitNodes(statements, visitor, ts.isStatement, start);
  72529. if (ensureUseStrict)
  72530. statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
  72531. return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
  72532. }
  72533. ts.visitLexicalEnvironment = visitLexicalEnvironment;
  72534. /**
  72535. * Starts a new lexical environment and visits a parameter list, suspending the lexical
  72536. * environment upon completion.
  72537. */
  72538. function visitParameterList(nodes, visitor, context, nodesVisitor) {
  72539. if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
  72540. context.startLexicalEnvironment();
  72541. var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
  72542. context.suspendLexicalEnvironment();
  72543. return updated;
  72544. }
  72545. ts.visitParameterList = visitParameterList;
  72546. function visitFunctionBody(node, visitor, context) {
  72547. context.resumeLexicalEnvironment();
  72548. var updated = visitNode(node, visitor, ts.isConciseBody);
  72549. var declarations = context.endLexicalEnvironment();
  72550. if (ts.some(declarations)) {
  72551. var block = ts.convertToFunctionBody(updated);
  72552. var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
  72553. return ts.updateBlock(block, statements);
  72554. }
  72555. return updated;
  72556. }
  72557. ts.visitFunctionBody = visitFunctionBody;
  72558. function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
  72559. if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
  72560. if (node === undefined) {
  72561. return undefined;
  72562. }
  72563. var kind = node.kind;
  72564. // No need to visit nodes with no children.
  72565. if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
  72566. return node;
  72567. }
  72568. switch (kind) {
  72569. // Names
  72570. case 75 /* Identifier */:
  72571. return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
  72572. case 153 /* QualifiedName */:
  72573. return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
  72574. case 154 /* ComputedPropertyName */:
  72575. return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
  72576. // Signature elements
  72577. case 155 /* TypeParameter */:
  72578. return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
  72579. case 156 /* Parameter */:
  72580. return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
  72581. case 157 /* Decorator */:
  72582. return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
  72583. // Type elements
  72584. case 158 /* PropertySignature */:
  72585. return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
  72586. case 159 /* PropertyDeclaration */:
  72587. return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName),
  72588. // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
  72589. visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
  72590. case 160 /* MethodSignature */:
  72591. return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken));
  72592. case 161 /* MethodDeclaration */:
  72593. return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
  72594. case 162 /* Constructor */:
  72595. return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
  72596. case 163 /* GetAccessor */:
  72597. return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
  72598. case 164 /* SetAccessor */:
  72599. return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
  72600. case 165 /* CallSignature */:
  72601. return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
  72602. case 166 /* ConstructSignature */:
  72603. return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
  72604. case 167 /* IndexSignature */:
  72605. return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
  72606. // Types
  72607. case 168 /* TypePredicate */:
  72608. return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
  72609. case 169 /* TypeReference */:
  72610. return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
  72611. case 170 /* FunctionType */:
  72612. return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
  72613. case 171 /* ConstructorType */:
  72614. return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
  72615. case 172 /* TypeQuery */:
  72616. return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
  72617. case 173 /* TypeLiteral */:
  72618. return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
  72619. case 174 /* ArrayType */:
  72620. return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
  72621. case 175 /* TupleType */:
  72622. return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
  72623. case 176 /* OptionalType */:
  72624. return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
  72625. case 177 /* RestType */:
  72626. return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
  72627. case 178 /* UnionType */:
  72628. return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
  72629. case 179 /* IntersectionType */:
  72630. return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
  72631. case 180 /* ConditionalType */:
  72632. return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode));
  72633. case 181 /* InferType */:
  72634. return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
  72635. case 188 /* ImportType */:
  72636. return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
  72637. case 182 /* ParenthesizedType */:
  72638. return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
  72639. case 184 /* TypeOperator */:
  72640. return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
  72641. case 185 /* IndexedAccessType */:
  72642. return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
  72643. case 186 /* MappedType */:
  72644. return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
  72645. case 187 /* LiteralType */:
  72646. return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
  72647. // Binding patterns
  72648. case 189 /* ObjectBindingPattern */:
  72649. return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
  72650. case 190 /* ArrayBindingPattern */:
  72651. return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
  72652. case 191 /* BindingElement */:
  72653. return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression));
  72654. // Expression
  72655. case 192 /* ArrayLiteralExpression */:
  72656. return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
  72657. case 193 /* ObjectLiteralExpression */:
  72658. return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
  72659. case 194 /* PropertyAccessExpression */:
  72660. if (node.flags & 32 /* OptionalChain */) {
  72661. return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
  72662. }
  72663. return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
  72664. case 195 /* ElementAccessExpression */:
  72665. if (node.flags & 32 /* OptionalChain */) {
  72666. return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, visitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
  72667. }
  72668. return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
  72669. case 196 /* CallExpression */:
  72670. if (node.flags & 32 /* OptionalChain */) {
  72671. return ts.updateCallChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, visitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
  72672. }
  72673. return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
  72674. case 197 /* NewExpression */:
  72675. return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
  72676. case 198 /* TaggedTemplateExpression */:
  72677. return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
  72678. case 199 /* TypeAssertionExpression */:
  72679. return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
  72680. case 200 /* ParenthesizedExpression */:
  72681. return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
  72682. case 201 /* FunctionExpression */:
  72683. return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
  72684. case 202 /* ArrowFunction */:
  72685. return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context));
  72686. case 203 /* DeleteExpression */:
  72687. return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
  72688. case 204 /* TypeOfExpression */:
  72689. return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
  72690. case 205 /* VoidExpression */:
  72691. return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
  72692. case 206 /* AwaitExpression */:
  72693. return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
  72694. case 207 /* PrefixUnaryExpression */:
  72695. return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
  72696. case 208 /* PostfixUnaryExpression */:
  72697. return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
  72698. case 209 /* BinaryExpression */:
  72699. return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken));
  72700. case 210 /* ConditionalExpression */:
  72701. return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression));
  72702. case 211 /* TemplateExpression */:
  72703. return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
  72704. case 212 /* YieldExpression */:
  72705. return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
  72706. case 213 /* SpreadElement */:
  72707. return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
  72708. case 214 /* ClassExpression */:
  72709. return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
  72710. case 216 /* ExpressionWithTypeArguments */:
  72711. return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
  72712. case 217 /* AsExpression */:
  72713. return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
  72714. case 218 /* NonNullExpression */:
  72715. return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
  72716. case 219 /* MetaProperty */:
  72717. return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
  72718. // Misc
  72719. case 221 /* TemplateSpan */:
  72720. return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
  72721. // Element
  72722. case 223 /* Block */:
  72723. return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
  72724. case 225 /* VariableStatement */:
  72725. return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
  72726. case 226 /* ExpressionStatement */:
  72727. return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
  72728. case 227 /* IfStatement */:
  72729. return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock));
  72730. case 228 /* DoStatement */:
  72731. return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
  72732. case 229 /* WhileStatement */:
  72733. return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  72734. case 230 /* ForStatement */:
  72735. return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  72736. case 231 /* ForInStatement */:
  72737. return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  72738. case 232 /* ForOfStatement */:
  72739. return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  72740. case 233 /* ContinueStatement */:
  72741. return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
  72742. case 234 /* BreakStatement */:
  72743. return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
  72744. case 235 /* ReturnStatement */:
  72745. return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
  72746. case 236 /* WithStatement */:
  72747. return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  72748. case 237 /* SwitchStatement */:
  72749. return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
  72750. case 238 /* LabeledStatement */:
  72751. return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  72752. case 239 /* ThrowStatement */:
  72753. return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
  72754. case 240 /* TryStatement */:
  72755. return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
  72756. case 242 /* VariableDeclaration */:
  72757. return ts.updateTypeScriptVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
  72758. case 243 /* VariableDeclarationList */:
  72759. return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
  72760. case 244 /* FunctionDeclaration */:
  72761. return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
  72762. case 245 /* ClassDeclaration */:
  72763. return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
  72764. case 246 /* InterfaceDeclaration */:
  72765. return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
  72766. case 247 /* TypeAliasDeclaration */:
  72767. return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
  72768. case 248 /* EnumDeclaration */:
  72769. return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
  72770. case 249 /* ModuleDeclaration */:
  72771. return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody));
  72772. case 250 /* ModuleBlock */:
  72773. return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
  72774. case 251 /* CaseBlock */:
  72775. return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
  72776. case 252 /* NamespaceExportDeclaration */:
  72777. return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
  72778. case 253 /* ImportEqualsDeclaration */:
  72779. return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference));
  72780. case 254 /* ImportDeclaration */:
  72781. return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
  72782. case 255 /* ImportClause */:
  72783. return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
  72784. case 256 /* NamespaceImport */:
  72785. return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
  72786. case 262 /* NamespaceExport */:
  72787. return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
  72788. case 257 /* NamedImports */:
  72789. return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
  72790. case 258 /* ImportSpecifier */:
  72791. return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
  72792. case 259 /* ExportAssignment */:
  72793. return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
  72794. case 260 /* ExportDeclaration */:
  72795. return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExportBindings), visitNode(node.moduleSpecifier, visitor, ts.isExpression), node.isTypeOnly);
  72796. case 261 /* NamedExports */:
  72797. return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
  72798. case 263 /* ExportSpecifier */:
  72799. return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
  72800. // Module references
  72801. case 265 /* ExternalModuleReference */:
  72802. return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
  72803. // JSX
  72804. case 266 /* JsxElement */:
  72805. return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
  72806. case 267 /* JsxSelfClosingElement */:
  72807. return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
  72808. case 268 /* JsxOpeningElement */:
  72809. return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
  72810. case 269 /* JsxClosingElement */:
  72811. return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
  72812. case 270 /* JsxFragment */:
  72813. return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
  72814. case 273 /* JsxAttribute */:
  72815. return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
  72816. case 274 /* JsxAttributes */:
  72817. return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
  72818. case 275 /* JsxSpreadAttribute */:
  72819. return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
  72820. case 276 /* JsxExpression */:
  72821. return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
  72822. // Clauses
  72823. case 277 /* CaseClause */:
  72824. return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
  72825. case 278 /* DefaultClause */:
  72826. return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
  72827. case 279 /* HeritageClause */:
  72828. return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
  72829. case 280 /* CatchClause */:
  72830. return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
  72831. // Property assignments
  72832. case 281 /* PropertyAssignment */:
  72833. return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
  72834. case 282 /* ShorthandPropertyAssignment */:
  72835. return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
  72836. case 283 /* SpreadAssignment */:
  72837. return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
  72838. // Enum
  72839. case 284 /* EnumMember */:
  72840. return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
  72841. // Top-level nodes
  72842. case 290 /* SourceFile */:
  72843. return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
  72844. // Transformation nodes
  72845. case 325 /* PartiallyEmittedExpression */:
  72846. return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
  72847. case 326 /* CommaListExpression */:
  72848. return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
  72849. default:
  72850. // No need to visit nodes with no children.
  72851. return node;
  72852. }
  72853. }
  72854. ts.visitEachChild = visitEachChild;
  72855. /**
  72856. * Extracts the single node from a NodeArray.
  72857. *
  72858. * @param nodes The NodeArray.
  72859. */
  72860. function extractSingleNode(nodes) {
  72861. ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
  72862. return ts.singleOrUndefined(nodes);
  72863. }
  72864. })(ts || (ts = {}));
  72865. /* @internal */
  72866. var ts;
  72867. (function (ts) {
  72868. function reduceNode(node, f, initial) {
  72869. return node ? f(initial, node) : initial;
  72870. }
  72871. function reduceNodeArray(nodes, f, initial) {
  72872. return nodes ? f(initial, nodes) : initial;
  72873. }
  72874. /**
  72875. * Similar to `reduceLeft`, performs a reduction against each child of a node.
  72876. * NOTE: Unlike `forEachChild`, this does *not* visit every node.
  72877. *
  72878. * @param node The node containing the children to reduce.
  72879. * @param initial The initial value to supply to the reduction.
  72880. * @param f The callback function
  72881. */
  72882. function reduceEachChild(node, initial, cbNode, cbNodeArray) {
  72883. if (node === undefined) {
  72884. return initial;
  72885. }
  72886. var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
  72887. var cbNodes = cbNodeArray || cbNode;
  72888. var kind = node.kind;
  72889. // No need to visit nodes with no children.
  72890. if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
  72891. return initial;
  72892. }
  72893. // We do not yet support types.
  72894. if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
  72895. return initial;
  72896. }
  72897. var result = initial;
  72898. switch (node.kind) {
  72899. // Leaf nodes
  72900. case 222 /* SemicolonClassElement */:
  72901. case 224 /* EmptyStatement */:
  72902. case 215 /* OmittedExpression */:
  72903. case 241 /* DebuggerStatement */:
  72904. case 324 /* NotEmittedStatement */:
  72905. // No need to visit nodes with no children.
  72906. break;
  72907. // Names
  72908. case 153 /* QualifiedName */:
  72909. result = reduceNode(node.left, cbNode, result);
  72910. result = reduceNode(node.right, cbNode, result);
  72911. break;
  72912. case 154 /* ComputedPropertyName */:
  72913. result = reduceNode(node.expression, cbNode, result);
  72914. break;
  72915. // Signature elements
  72916. case 156 /* Parameter */:
  72917. result = reduceNodes(node.decorators, cbNodes, result);
  72918. result = reduceNodes(node.modifiers, cbNodes, result);
  72919. result = reduceNode(node.name, cbNode, result);
  72920. result = reduceNode(node.type, cbNode, result);
  72921. result = reduceNode(node.initializer, cbNode, result);
  72922. break;
  72923. case 157 /* Decorator */:
  72924. result = reduceNode(node.expression, cbNode, result);
  72925. break;
  72926. // Type member
  72927. case 158 /* PropertySignature */:
  72928. result = reduceNodes(node.modifiers, cbNodes, result);
  72929. result = reduceNode(node.name, cbNode, result);
  72930. result = reduceNode(node.questionToken, cbNode, result);
  72931. result = reduceNode(node.type, cbNode, result);
  72932. result = reduceNode(node.initializer, cbNode, result);
  72933. break;
  72934. case 159 /* PropertyDeclaration */:
  72935. result = reduceNodes(node.decorators, cbNodes, result);
  72936. result = reduceNodes(node.modifiers, cbNodes, result);
  72937. result = reduceNode(node.name, cbNode, result);
  72938. result = reduceNode(node.type, cbNode, result);
  72939. result = reduceNode(node.initializer, cbNode, result);
  72940. break;
  72941. case 161 /* MethodDeclaration */:
  72942. result = reduceNodes(node.decorators, cbNodes, result);
  72943. result = reduceNodes(node.modifiers, cbNodes, result);
  72944. result = reduceNode(node.name, cbNode, result);
  72945. result = reduceNodes(node.typeParameters, cbNodes, result);
  72946. result = reduceNodes(node.parameters, cbNodes, result);
  72947. result = reduceNode(node.type, cbNode, result);
  72948. result = reduceNode(node.body, cbNode, result);
  72949. break;
  72950. case 162 /* Constructor */:
  72951. result = reduceNodes(node.modifiers, cbNodes, result);
  72952. result = reduceNodes(node.parameters, cbNodes, result);
  72953. result = reduceNode(node.body, cbNode, result);
  72954. break;
  72955. case 163 /* GetAccessor */:
  72956. result = reduceNodes(node.decorators, cbNodes, result);
  72957. result = reduceNodes(node.modifiers, cbNodes, result);
  72958. result = reduceNode(node.name, cbNode, result);
  72959. result = reduceNodes(node.parameters, cbNodes, result);
  72960. result = reduceNode(node.type, cbNode, result);
  72961. result = reduceNode(node.body, cbNode, result);
  72962. break;
  72963. case 164 /* SetAccessor */:
  72964. result = reduceNodes(node.decorators, cbNodes, result);
  72965. result = reduceNodes(node.modifiers, cbNodes, result);
  72966. result = reduceNode(node.name, cbNode, result);
  72967. result = reduceNodes(node.parameters, cbNodes, result);
  72968. result = reduceNode(node.body, cbNode, result);
  72969. break;
  72970. // Binding patterns
  72971. case 189 /* ObjectBindingPattern */:
  72972. case 190 /* ArrayBindingPattern */:
  72973. result = reduceNodes(node.elements, cbNodes, result);
  72974. break;
  72975. case 191 /* BindingElement */:
  72976. result = reduceNode(node.propertyName, cbNode, result);
  72977. result = reduceNode(node.name, cbNode, result);
  72978. result = reduceNode(node.initializer, cbNode, result);
  72979. break;
  72980. // Expression
  72981. case 192 /* ArrayLiteralExpression */:
  72982. result = reduceNodes(node.elements, cbNodes, result);
  72983. break;
  72984. case 193 /* ObjectLiteralExpression */:
  72985. result = reduceNodes(node.properties, cbNodes, result);
  72986. break;
  72987. case 194 /* PropertyAccessExpression */:
  72988. result = reduceNode(node.expression, cbNode, result);
  72989. result = reduceNode(node.name, cbNode, result);
  72990. break;
  72991. case 195 /* ElementAccessExpression */:
  72992. result = reduceNode(node.expression, cbNode, result);
  72993. result = reduceNode(node.argumentExpression, cbNode, result);
  72994. break;
  72995. case 196 /* CallExpression */:
  72996. result = reduceNode(node.expression, cbNode, result);
  72997. result = reduceNodes(node.typeArguments, cbNodes, result);
  72998. result = reduceNodes(node.arguments, cbNodes, result);
  72999. break;
  73000. case 197 /* NewExpression */:
  73001. result = reduceNode(node.expression, cbNode, result);
  73002. result = reduceNodes(node.typeArguments, cbNodes, result);
  73003. result = reduceNodes(node.arguments, cbNodes, result);
  73004. break;
  73005. case 198 /* TaggedTemplateExpression */:
  73006. result = reduceNode(node.tag, cbNode, result);
  73007. result = reduceNodes(node.typeArguments, cbNodes, result);
  73008. result = reduceNode(node.template, cbNode, result);
  73009. break;
  73010. case 199 /* TypeAssertionExpression */:
  73011. result = reduceNode(node.type, cbNode, result);
  73012. result = reduceNode(node.expression, cbNode, result);
  73013. break;
  73014. case 201 /* FunctionExpression */:
  73015. result = reduceNodes(node.modifiers, cbNodes, result);
  73016. result = reduceNode(node.name, cbNode, result);
  73017. result = reduceNodes(node.typeParameters, cbNodes, result);
  73018. result = reduceNodes(node.parameters, cbNodes, result);
  73019. result = reduceNode(node.type, cbNode, result);
  73020. result = reduceNode(node.body, cbNode, result);
  73021. break;
  73022. case 202 /* ArrowFunction */:
  73023. result = reduceNodes(node.modifiers, cbNodes, result);
  73024. result = reduceNodes(node.typeParameters, cbNodes, result);
  73025. result = reduceNodes(node.parameters, cbNodes, result);
  73026. result = reduceNode(node.type, cbNode, result);
  73027. result = reduceNode(node.body, cbNode, result);
  73028. break;
  73029. case 200 /* ParenthesizedExpression */:
  73030. case 203 /* DeleteExpression */:
  73031. case 204 /* TypeOfExpression */:
  73032. case 205 /* VoidExpression */:
  73033. case 206 /* AwaitExpression */:
  73034. case 212 /* YieldExpression */:
  73035. case 213 /* SpreadElement */:
  73036. case 218 /* NonNullExpression */:
  73037. result = reduceNode(node.expression, cbNode, result);
  73038. break;
  73039. case 207 /* PrefixUnaryExpression */:
  73040. case 208 /* PostfixUnaryExpression */:
  73041. result = reduceNode(node.operand, cbNode, result);
  73042. break;
  73043. case 209 /* BinaryExpression */:
  73044. result = reduceNode(node.left, cbNode, result);
  73045. result = reduceNode(node.right, cbNode, result);
  73046. break;
  73047. case 210 /* ConditionalExpression */:
  73048. result = reduceNode(node.condition, cbNode, result);
  73049. result = reduceNode(node.whenTrue, cbNode, result);
  73050. result = reduceNode(node.whenFalse, cbNode, result);
  73051. break;
  73052. case 211 /* TemplateExpression */:
  73053. result = reduceNode(node.head, cbNode, result);
  73054. result = reduceNodes(node.templateSpans, cbNodes, result);
  73055. break;
  73056. case 214 /* ClassExpression */:
  73057. result = reduceNodes(node.modifiers, cbNodes, result);
  73058. result = reduceNode(node.name, cbNode, result);
  73059. result = reduceNodes(node.typeParameters, cbNodes, result);
  73060. result = reduceNodes(node.heritageClauses, cbNodes, result);
  73061. result = reduceNodes(node.members, cbNodes, result);
  73062. break;
  73063. case 216 /* ExpressionWithTypeArguments */:
  73064. result = reduceNode(node.expression, cbNode, result);
  73065. result = reduceNodes(node.typeArguments, cbNodes, result);
  73066. break;
  73067. case 217 /* AsExpression */:
  73068. result = reduceNode(node.expression, cbNode, result);
  73069. result = reduceNode(node.type, cbNode, result);
  73070. break;
  73071. // Misc
  73072. case 221 /* TemplateSpan */:
  73073. result = reduceNode(node.expression, cbNode, result);
  73074. result = reduceNode(node.literal, cbNode, result);
  73075. break;
  73076. // Element
  73077. case 223 /* Block */:
  73078. result = reduceNodes(node.statements, cbNodes, result);
  73079. break;
  73080. case 225 /* VariableStatement */:
  73081. result = reduceNodes(node.modifiers, cbNodes, result);
  73082. result = reduceNode(node.declarationList, cbNode, result);
  73083. break;
  73084. case 226 /* ExpressionStatement */:
  73085. result = reduceNode(node.expression, cbNode, result);
  73086. break;
  73087. case 227 /* IfStatement */:
  73088. result = reduceNode(node.expression, cbNode, result);
  73089. result = reduceNode(node.thenStatement, cbNode, result);
  73090. result = reduceNode(node.elseStatement, cbNode, result);
  73091. break;
  73092. case 228 /* DoStatement */:
  73093. result = reduceNode(node.statement, cbNode, result);
  73094. result = reduceNode(node.expression, cbNode, result);
  73095. break;
  73096. case 229 /* WhileStatement */:
  73097. case 236 /* WithStatement */:
  73098. result = reduceNode(node.expression, cbNode, result);
  73099. result = reduceNode(node.statement, cbNode, result);
  73100. break;
  73101. case 230 /* ForStatement */:
  73102. result = reduceNode(node.initializer, cbNode, result);
  73103. result = reduceNode(node.condition, cbNode, result);
  73104. result = reduceNode(node.incrementor, cbNode, result);
  73105. result = reduceNode(node.statement, cbNode, result);
  73106. break;
  73107. case 231 /* ForInStatement */:
  73108. case 232 /* ForOfStatement */:
  73109. result = reduceNode(node.initializer, cbNode, result);
  73110. result = reduceNode(node.expression, cbNode, result);
  73111. result = reduceNode(node.statement, cbNode, result);
  73112. break;
  73113. case 235 /* ReturnStatement */:
  73114. case 239 /* ThrowStatement */:
  73115. result = reduceNode(node.expression, cbNode, result);
  73116. break;
  73117. case 237 /* SwitchStatement */:
  73118. result = reduceNode(node.expression, cbNode, result);
  73119. result = reduceNode(node.caseBlock, cbNode, result);
  73120. break;
  73121. case 238 /* LabeledStatement */:
  73122. result = reduceNode(node.label, cbNode, result);
  73123. result = reduceNode(node.statement, cbNode, result);
  73124. break;
  73125. case 240 /* TryStatement */:
  73126. result = reduceNode(node.tryBlock, cbNode, result);
  73127. result = reduceNode(node.catchClause, cbNode, result);
  73128. result = reduceNode(node.finallyBlock, cbNode, result);
  73129. break;
  73130. case 242 /* VariableDeclaration */:
  73131. result = reduceNode(node.name, cbNode, result);
  73132. result = reduceNode(node.type, cbNode, result);
  73133. result = reduceNode(node.initializer, cbNode, result);
  73134. break;
  73135. case 243 /* VariableDeclarationList */:
  73136. result = reduceNodes(node.declarations, cbNodes, result);
  73137. break;
  73138. case 244 /* FunctionDeclaration */:
  73139. result = reduceNodes(node.decorators, cbNodes, result);
  73140. result = reduceNodes(node.modifiers, cbNodes, result);
  73141. result = reduceNode(node.name, cbNode, result);
  73142. result = reduceNodes(node.typeParameters, cbNodes, result);
  73143. result = reduceNodes(node.parameters, cbNodes, result);
  73144. result = reduceNode(node.type, cbNode, result);
  73145. result = reduceNode(node.body, cbNode, result);
  73146. break;
  73147. case 245 /* ClassDeclaration */:
  73148. result = reduceNodes(node.decorators, cbNodes, result);
  73149. result = reduceNodes(node.modifiers, cbNodes, result);
  73150. result = reduceNode(node.name, cbNode, result);
  73151. result = reduceNodes(node.typeParameters, cbNodes, result);
  73152. result = reduceNodes(node.heritageClauses, cbNodes, result);
  73153. result = reduceNodes(node.members, cbNodes, result);
  73154. break;
  73155. case 248 /* EnumDeclaration */:
  73156. result = reduceNodes(node.decorators, cbNodes, result);
  73157. result = reduceNodes(node.modifiers, cbNodes, result);
  73158. result = reduceNode(node.name, cbNode, result);
  73159. result = reduceNodes(node.members, cbNodes, result);
  73160. break;
  73161. case 249 /* ModuleDeclaration */:
  73162. result = reduceNodes(node.decorators, cbNodes, result);
  73163. result = reduceNodes(node.modifiers, cbNodes, result);
  73164. result = reduceNode(node.name, cbNode, result);
  73165. result = reduceNode(node.body, cbNode, result);
  73166. break;
  73167. case 250 /* ModuleBlock */:
  73168. result = reduceNodes(node.statements, cbNodes, result);
  73169. break;
  73170. case 251 /* CaseBlock */:
  73171. result = reduceNodes(node.clauses, cbNodes, result);
  73172. break;
  73173. case 253 /* ImportEqualsDeclaration */:
  73174. result = reduceNodes(node.decorators, cbNodes, result);
  73175. result = reduceNodes(node.modifiers, cbNodes, result);
  73176. result = reduceNode(node.name, cbNode, result);
  73177. result = reduceNode(node.moduleReference, cbNode, result);
  73178. break;
  73179. case 254 /* ImportDeclaration */:
  73180. result = reduceNodes(node.decorators, cbNodes, result);
  73181. result = reduceNodes(node.modifiers, cbNodes, result);
  73182. result = reduceNode(node.importClause, cbNode, result);
  73183. result = reduceNode(node.moduleSpecifier, cbNode, result);
  73184. break;
  73185. case 255 /* ImportClause */:
  73186. result = reduceNode(node.name, cbNode, result);
  73187. result = reduceNode(node.namedBindings, cbNode, result);
  73188. break;
  73189. case 256 /* NamespaceImport */:
  73190. result = reduceNode(node.name, cbNode, result);
  73191. break;
  73192. case 262 /* NamespaceExport */:
  73193. result = reduceNode(node.name, cbNode, result);
  73194. break;
  73195. case 257 /* NamedImports */:
  73196. case 261 /* NamedExports */:
  73197. result = reduceNodes(node.elements, cbNodes, result);
  73198. break;
  73199. case 258 /* ImportSpecifier */:
  73200. case 263 /* ExportSpecifier */:
  73201. result = reduceNode(node.propertyName, cbNode, result);
  73202. result = reduceNode(node.name, cbNode, result);
  73203. break;
  73204. case 259 /* ExportAssignment */:
  73205. result = ts.reduceLeft(node.decorators, cbNode, result);
  73206. result = ts.reduceLeft(node.modifiers, cbNode, result);
  73207. result = reduceNode(node.expression, cbNode, result);
  73208. break;
  73209. case 260 /* ExportDeclaration */:
  73210. result = ts.reduceLeft(node.decorators, cbNode, result);
  73211. result = ts.reduceLeft(node.modifiers, cbNode, result);
  73212. result = reduceNode(node.exportClause, cbNode, result);
  73213. result = reduceNode(node.moduleSpecifier, cbNode, result);
  73214. break;
  73215. // Module references
  73216. case 265 /* ExternalModuleReference */:
  73217. result = reduceNode(node.expression, cbNode, result);
  73218. break;
  73219. // JSX
  73220. case 266 /* JsxElement */:
  73221. result = reduceNode(node.openingElement, cbNode, result);
  73222. result = ts.reduceLeft(node.children, cbNode, result);
  73223. result = reduceNode(node.closingElement, cbNode, result);
  73224. break;
  73225. case 270 /* JsxFragment */:
  73226. result = reduceNode(node.openingFragment, cbNode, result);
  73227. result = ts.reduceLeft(node.children, cbNode, result);
  73228. result = reduceNode(node.closingFragment, cbNode, result);
  73229. break;
  73230. case 267 /* JsxSelfClosingElement */:
  73231. case 268 /* JsxOpeningElement */:
  73232. result = reduceNode(node.tagName, cbNode, result);
  73233. result = reduceNodes(node.typeArguments, cbNode, result);
  73234. result = reduceNode(node.attributes, cbNode, result);
  73235. break;
  73236. case 274 /* JsxAttributes */:
  73237. result = reduceNodes(node.properties, cbNodes, result);
  73238. break;
  73239. case 269 /* JsxClosingElement */:
  73240. result = reduceNode(node.tagName, cbNode, result);
  73241. break;
  73242. case 273 /* JsxAttribute */:
  73243. result = reduceNode(node.name, cbNode, result);
  73244. result = reduceNode(node.initializer, cbNode, result);
  73245. break;
  73246. case 275 /* JsxSpreadAttribute */:
  73247. result = reduceNode(node.expression, cbNode, result);
  73248. break;
  73249. case 276 /* JsxExpression */:
  73250. result = reduceNode(node.expression, cbNode, result);
  73251. break;
  73252. // Clauses
  73253. case 277 /* CaseClause */:
  73254. result = reduceNode(node.expression, cbNode, result);
  73255. // falls through
  73256. case 278 /* DefaultClause */:
  73257. result = reduceNodes(node.statements, cbNodes, result);
  73258. break;
  73259. case 279 /* HeritageClause */:
  73260. result = reduceNodes(node.types, cbNodes, result);
  73261. break;
  73262. case 280 /* CatchClause */:
  73263. result = reduceNode(node.variableDeclaration, cbNode, result);
  73264. result = reduceNode(node.block, cbNode, result);
  73265. break;
  73266. // Property assignments
  73267. case 281 /* PropertyAssignment */:
  73268. result = reduceNode(node.name, cbNode, result);
  73269. result = reduceNode(node.initializer, cbNode, result);
  73270. break;
  73271. case 282 /* ShorthandPropertyAssignment */:
  73272. result = reduceNode(node.name, cbNode, result);
  73273. result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
  73274. break;
  73275. case 283 /* SpreadAssignment */:
  73276. result = reduceNode(node.expression, cbNode, result);
  73277. break;
  73278. // Enum
  73279. case 284 /* EnumMember */:
  73280. result = reduceNode(node.name, cbNode, result);
  73281. result = reduceNode(node.initializer, cbNode, result);
  73282. break;
  73283. // Top-level nodes
  73284. case 290 /* SourceFile */:
  73285. result = reduceNodes(node.statements, cbNodes, result);
  73286. break;
  73287. // Transformation nodes
  73288. case 325 /* PartiallyEmittedExpression */:
  73289. result = reduceNode(node.expression, cbNode, result);
  73290. break;
  73291. case 326 /* CommaListExpression */:
  73292. result = reduceNodes(node.elements, cbNodes, result);
  73293. break;
  73294. default:
  73295. break;
  73296. }
  73297. return result;
  73298. }
  73299. ts.reduceEachChild = reduceEachChild;
  73300. function mergeLexicalEnvironment(statements, declarations) {
  73301. if (!ts.some(declarations)) {
  73302. return statements;
  73303. }
  73304. return ts.isNodeArray(statements)
  73305. ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
  73306. : ts.insertStatementsAfterStandardPrologue(statements, declarations);
  73307. }
  73308. ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
  73309. /**
  73310. * Lifts a NodeArray containing only Statement nodes to a block.
  73311. *
  73312. * @param nodes The NodeArray.
  73313. */
  73314. function liftToBlock(nodes) {
  73315. ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
  73316. return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
  73317. }
  73318. ts.liftToBlock = liftToBlock;
  73319. /**
  73320. * Aggregates the TransformFlags for a Node and its subtree.
  73321. */
  73322. function aggregateTransformFlags(node) {
  73323. aggregateTransformFlagsForNode(node);
  73324. return node;
  73325. }
  73326. ts.aggregateTransformFlags = aggregateTransformFlags;
  73327. /**
  73328. * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
  73329. * computed first, then the transform flags for the current node are computed from the subtree
  73330. * flags and the state of the current node. Finally, the transform flags of the node are
  73331. * returned, excluding any flags that should not be included in its parent node's subtree
  73332. * flags.
  73333. */
  73334. function aggregateTransformFlagsForNode(node) {
  73335. if (node === undefined) {
  73336. return 0 /* None */;
  73337. }
  73338. if (node.transformFlags & 536870912 /* HasComputedFlags */) {
  73339. return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
  73340. }
  73341. var subtreeFlags = aggregateTransformFlagsForSubtree(node);
  73342. return ts.computeTransformFlagsForNode(node, subtreeFlags);
  73343. }
  73344. function aggregateTransformFlagsForNodeArray(nodes) {
  73345. if (nodes === undefined) {
  73346. return 0 /* None */;
  73347. }
  73348. var subtreeFlags = 0 /* None */;
  73349. var nodeArrayFlags = 0 /* None */;
  73350. for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
  73351. var node = nodes_3[_i];
  73352. subtreeFlags |= aggregateTransformFlagsForNode(node);
  73353. nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
  73354. }
  73355. nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
  73356. return subtreeFlags;
  73357. }
  73358. /**
  73359. * Aggregates the transform flags for the subtree of a node.
  73360. */
  73361. function aggregateTransformFlagsForSubtree(node) {
  73362. // We do not transform ambient declarations or types, so there is no need to
  73363. // recursively aggregate transform flags.
  73364. if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
  73365. return 0 /* None */;
  73366. }
  73367. // Aggregate the transform flags of each child.
  73368. return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
  73369. }
  73370. /**
  73371. * Aggregates the TransformFlags of a child node with the TransformFlags of its
  73372. * siblings.
  73373. */
  73374. function aggregateTransformFlagsForChildNode(transformFlags, node) {
  73375. return transformFlags | aggregateTransformFlagsForNode(node);
  73376. }
  73377. function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
  73378. return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
  73379. }
  73380. })(ts || (ts = {}));
  73381. /* @internal */
  73382. var ts;
  73383. (function (ts) {
  73384. function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
  73385. var _a = generatorOptions.extendedDiagnostics
  73386. ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
  73387. : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
  73388. // Current source map file and its index in the sources list
  73389. var rawSources = [];
  73390. var sources = [];
  73391. var sourceToSourceIndexMap = ts.createMap();
  73392. var sourcesContent;
  73393. var names = [];
  73394. var nameToNameIndexMap;
  73395. var mappings = "";
  73396. // Last recorded and encoded mappings
  73397. var lastGeneratedLine = 0;
  73398. var lastGeneratedCharacter = 0;
  73399. var lastSourceIndex = 0;
  73400. var lastSourceLine = 0;
  73401. var lastSourceCharacter = 0;
  73402. var lastNameIndex = 0;
  73403. var hasLast = false;
  73404. var pendingGeneratedLine = 0;
  73405. var pendingGeneratedCharacter = 0;
  73406. var pendingSourceIndex = 0;
  73407. var pendingSourceLine = 0;
  73408. var pendingSourceCharacter = 0;
  73409. var pendingNameIndex = 0;
  73410. var hasPending = false;
  73411. var hasPendingSource = false;
  73412. var hasPendingName = false;
  73413. return {
  73414. getSources: function () { return rawSources; },
  73415. addSource: addSource,
  73416. setSourceContent: setSourceContent,
  73417. addName: addName,
  73418. addMapping: addMapping,
  73419. appendSourceMap: appendSourceMap,
  73420. toJSON: toJSON,
  73421. toString: function () { return JSON.stringify(toJSON()); }
  73422. };
  73423. function addSource(fileName) {
  73424. enter();
  73425. var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName,
  73426. /*isAbsolutePathAnUrl*/ true);
  73427. var sourceIndex = sourceToSourceIndexMap.get(source);
  73428. if (sourceIndex === undefined) {
  73429. sourceIndex = sources.length;
  73430. sources.push(source);
  73431. rawSources.push(fileName);
  73432. sourceToSourceIndexMap.set(source, sourceIndex);
  73433. }
  73434. exit();
  73435. return sourceIndex;
  73436. }
  73437. /* eslint-disable boolean-trivia, no-null/no-null */
  73438. function setSourceContent(sourceIndex, content) {
  73439. enter();
  73440. if (content !== null) {
  73441. if (!sourcesContent)
  73442. sourcesContent = [];
  73443. while (sourcesContent.length < sourceIndex) {
  73444. sourcesContent.push(null);
  73445. }
  73446. sourcesContent[sourceIndex] = content;
  73447. }
  73448. exit();
  73449. }
  73450. /* eslint-enable boolean-trivia, no-null/no-null */
  73451. function addName(name) {
  73452. enter();
  73453. if (!nameToNameIndexMap)
  73454. nameToNameIndexMap = ts.createMap();
  73455. var nameIndex = nameToNameIndexMap.get(name);
  73456. if (nameIndex === undefined) {
  73457. nameIndex = names.length;
  73458. names.push(name);
  73459. nameToNameIndexMap.set(name, nameIndex);
  73460. }
  73461. exit();
  73462. return nameIndex;
  73463. }
  73464. function isNewGeneratedPosition(generatedLine, generatedCharacter) {
  73465. return !hasPending
  73466. || pendingGeneratedLine !== generatedLine
  73467. || pendingGeneratedCharacter !== generatedCharacter;
  73468. }
  73469. function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
  73470. return sourceIndex !== undefined
  73471. && sourceLine !== undefined
  73472. && sourceCharacter !== undefined
  73473. && pendingSourceIndex === sourceIndex
  73474. && (pendingSourceLine > sourceLine
  73475. || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
  73476. }
  73477. function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
  73478. ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
  73479. ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
  73480. ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
  73481. ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
  73482. ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
  73483. enter();
  73484. // If this location wasn't recorded or the location in source is going backwards, record the mapping
  73485. if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
  73486. isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
  73487. commitPendingMapping();
  73488. pendingGeneratedLine = generatedLine;
  73489. pendingGeneratedCharacter = generatedCharacter;
  73490. hasPendingSource = false;
  73491. hasPendingName = false;
  73492. hasPending = true;
  73493. }
  73494. if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
  73495. pendingSourceIndex = sourceIndex;
  73496. pendingSourceLine = sourceLine;
  73497. pendingSourceCharacter = sourceCharacter;
  73498. hasPendingSource = true;
  73499. if (nameIndex !== undefined) {
  73500. pendingNameIndex = nameIndex;
  73501. hasPendingName = true;
  73502. }
  73503. }
  73504. exit();
  73505. }
  73506. function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
  73507. ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
  73508. ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
  73509. enter();
  73510. // First, decode the old component sourcemap
  73511. var sourceIndexToNewSourceIndexMap = [];
  73512. var nameIndexToNewNameIndexMap;
  73513. var mappingIterator = decodeMappings(map.mappings);
  73514. for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
  73515. var raw = iterResult.value;
  73516. if (end && (raw.generatedLine > end.line ||
  73517. (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
  73518. break;
  73519. }
  73520. if (start && (raw.generatedLine < start.line ||
  73521. (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
  73522. continue;
  73523. }
  73524. // Then reencode all the updated mappings into the overall map
  73525. var newSourceIndex = void 0;
  73526. var newSourceLine = void 0;
  73527. var newSourceCharacter = void 0;
  73528. var newNameIndex = void 0;
  73529. if (raw.sourceIndex !== undefined) {
  73530. newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
  73531. if (newSourceIndex === undefined) {
  73532. // Apply offsets to each position and fixup source entries
  73533. var rawPath = map.sources[raw.sourceIndex];
  73534. var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
  73535. var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
  73536. sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
  73537. if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
  73538. setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
  73539. }
  73540. }
  73541. newSourceLine = raw.sourceLine;
  73542. newSourceCharacter = raw.sourceCharacter;
  73543. if (map.names && raw.nameIndex !== undefined) {
  73544. if (!nameIndexToNewNameIndexMap)
  73545. nameIndexToNewNameIndexMap = [];
  73546. newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
  73547. if (newNameIndex === undefined) {
  73548. nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
  73549. }
  73550. }
  73551. }
  73552. var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
  73553. var newGeneratedLine = rawGeneratedLine + generatedLine;
  73554. var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
  73555. var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
  73556. addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
  73557. }
  73558. exit();
  73559. }
  73560. function shouldCommitMapping() {
  73561. return !hasLast
  73562. || lastGeneratedLine !== pendingGeneratedLine
  73563. || lastGeneratedCharacter !== pendingGeneratedCharacter
  73564. || lastSourceIndex !== pendingSourceIndex
  73565. || lastSourceLine !== pendingSourceLine
  73566. || lastSourceCharacter !== pendingSourceCharacter
  73567. || lastNameIndex !== pendingNameIndex;
  73568. }
  73569. function commitPendingMapping() {
  73570. if (!hasPending || !shouldCommitMapping()) {
  73571. return;
  73572. }
  73573. enter();
  73574. // Line/Comma delimiters
  73575. if (lastGeneratedLine < pendingGeneratedLine) {
  73576. // Emit line delimiters
  73577. do {
  73578. mappings += ";";
  73579. lastGeneratedLine++;
  73580. lastGeneratedCharacter = 0;
  73581. } while (lastGeneratedLine < pendingGeneratedLine);
  73582. }
  73583. else {
  73584. ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
  73585. // Emit comma to separate the entry
  73586. if (hasLast) {
  73587. mappings += ",";
  73588. }
  73589. }
  73590. // 1. Relative generated character
  73591. mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
  73592. lastGeneratedCharacter = pendingGeneratedCharacter;
  73593. if (hasPendingSource) {
  73594. // 2. Relative sourceIndex
  73595. mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
  73596. lastSourceIndex = pendingSourceIndex;
  73597. // 3. Relative source line
  73598. mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
  73599. lastSourceLine = pendingSourceLine;
  73600. // 4. Relative source character
  73601. mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
  73602. lastSourceCharacter = pendingSourceCharacter;
  73603. if (hasPendingName) {
  73604. // 5. Relative nameIndex
  73605. mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
  73606. lastNameIndex = pendingNameIndex;
  73607. }
  73608. }
  73609. hasLast = true;
  73610. exit();
  73611. }
  73612. function toJSON() {
  73613. commitPendingMapping();
  73614. return {
  73615. version: 3,
  73616. file: file,
  73617. sourceRoot: sourceRoot,
  73618. sources: sources,
  73619. names: names,
  73620. mappings: mappings,
  73621. sourcesContent: sourcesContent,
  73622. };
  73623. }
  73624. }
  73625. ts.createSourceMapGenerator = createSourceMapGenerator;
  73626. // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
  73627. var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
  73628. var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
  73629. function getLineInfo(text, lineStarts) {
  73630. return {
  73631. getLineCount: function () { return lineStarts.length; },
  73632. getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
  73633. };
  73634. }
  73635. ts.getLineInfo = getLineInfo;
  73636. /**
  73637. * Tries to find the sourceMappingURL comment at the end of a file.
  73638. */
  73639. function tryGetSourceMappingURL(lineInfo) {
  73640. for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
  73641. var line = lineInfo.getLineText(index);
  73642. var comment = sourceMapCommentRegExp.exec(line);
  73643. if (comment) {
  73644. return comment[1];
  73645. }
  73646. // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
  73647. else if (!line.match(whitespaceOrMapCommentRegExp)) {
  73648. break;
  73649. }
  73650. }
  73651. }
  73652. ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
  73653. /* eslint-disable no-null/no-null */
  73654. function isStringOrNull(x) {
  73655. return typeof x === "string" || x === null;
  73656. }
  73657. function isRawSourceMap(x) {
  73658. return x !== null
  73659. && typeof x === "object"
  73660. && x.version === 3
  73661. && typeof x.file === "string"
  73662. && typeof x.mappings === "string"
  73663. && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
  73664. && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
  73665. && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
  73666. && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
  73667. }
  73668. ts.isRawSourceMap = isRawSourceMap;
  73669. /* eslint-enable no-null/no-null */
  73670. function tryParseRawSourceMap(text) {
  73671. try {
  73672. var parsed = JSON.parse(text);
  73673. if (isRawSourceMap(parsed)) {
  73674. return parsed;
  73675. }
  73676. }
  73677. catch (_a) {
  73678. // empty
  73679. }
  73680. return undefined;
  73681. }
  73682. ts.tryParseRawSourceMap = tryParseRawSourceMap;
  73683. function decodeMappings(mappings) {
  73684. var done = false;
  73685. var pos = 0;
  73686. var generatedLine = 0;
  73687. var generatedCharacter = 0;
  73688. var sourceIndex = 0;
  73689. var sourceLine = 0;
  73690. var sourceCharacter = 0;
  73691. var nameIndex = 0;
  73692. var error;
  73693. return {
  73694. get pos() { return pos; },
  73695. get error() { return error; },
  73696. get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
  73697. next: function () {
  73698. while (!done && pos < mappings.length) {
  73699. var ch = mappings.charCodeAt(pos);
  73700. if (ch === 59 /* semicolon */) {
  73701. // new line
  73702. generatedLine++;
  73703. generatedCharacter = 0;
  73704. pos++;
  73705. continue;
  73706. }
  73707. if (ch === 44 /* comma */) {
  73708. // Next entry is on same line - no action needed
  73709. pos++;
  73710. continue;
  73711. }
  73712. var hasSource = false;
  73713. var hasName = false;
  73714. generatedCharacter += base64VLQFormatDecode();
  73715. if (hasReportedError())
  73716. return stopIterating();
  73717. if (generatedCharacter < 0)
  73718. return setErrorAndStopIterating("Invalid generatedCharacter found");
  73719. if (!isSourceMappingSegmentEnd()) {
  73720. hasSource = true;
  73721. sourceIndex += base64VLQFormatDecode();
  73722. if (hasReportedError())
  73723. return stopIterating();
  73724. if (sourceIndex < 0)
  73725. return setErrorAndStopIterating("Invalid sourceIndex found");
  73726. if (isSourceMappingSegmentEnd())
  73727. return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
  73728. sourceLine += base64VLQFormatDecode();
  73729. if (hasReportedError())
  73730. return stopIterating();
  73731. if (sourceLine < 0)
  73732. return setErrorAndStopIterating("Invalid sourceLine found");
  73733. if (isSourceMappingSegmentEnd())
  73734. return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
  73735. sourceCharacter += base64VLQFormatDecode();
  73736. if (hasReportedError())
  73737. return stopIterating();
  73738. if (sourceCharacter < 0)
  73739. return setErrorAndStopIterating("Invalid sourceCharacter found");
  73740. if (!isSourceMappingSegmentEnd()) {
  73741. hasName = true;
  73742. nameIndex += base64VLQFormatDecode();
  73743. if (hasReportedError())
  73744. return stopIterating();
  73745. if (nameIndex < 0)
  73746. return setErrorAndStopIterating("Invalid nameIndex found");
  73747. if (!isSourceMappingSegmentEnd())
  73748. return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
  73749. }
  73750. }
  73751. return { value: captureMapping(hasSource, hasName), done: done };
  73752. }
  73753. return stopIterating();
  73754. }
  73755. };
  73756. function captureMapping(hasSource, hasName) {
  73757. return {
  73758. generatedLine: generatedLine,
  73759. generatedCharacter: generatedCharacter,
  73760. sourceIndex: hasSource ? sourceIndex : undefined,
  73761. sourceLine: hasSource ? sourceLine : undefined,
  73762. sourceCharacter: hasSource ? sourceCharacter : undefined,
  73763. nameIndex: hasName ? nameIndex : undefined
  73764. };
  73765. }
  73766. function stopIterating() {
  73767. done = true;
  73768. return { value: undefined, done: true };
  73769. }
  73770. function setError(message) {
  73771. if (error === undefined) {
  73772. error = message;
  73773. }
  73774. }
  73775. function setErrorAndStopIterating(message) {
  73776. setError(message);
  73777. return stopIterating();
  73778. }
  73779. function hasReportedError() {
  73780. return error !== undefined;
  73781. }
  73782. function isSourceMappingSegmentEnd() {
  73783. return (pos === mappings.length ||
  73784. mappings.charCodeAt(pos) === 44 /* comma */ ||
  73785. mappings.charCodeAt(pos) === 59 /* semicolon */);
  73786. }
  73787. function base64VLQFormatDecode() {
  73788. var moreDigits = true;
  73789. var shiftCount = 0;
  73790. var value = 0;
  73791. for (; moreDigits; pos++) {
  73792. if (pos >= mappings.length)
  73793. return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
  73794. // 6 digit number
  73795. var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
  73796. if (currentByte === -1)
  73797. return setError("Invalid character in VLQ"), -1;
  73798. // If msb is set, we still have more bits to continue
  73799. moreDigits = (currentByte & 32) !== 0;
  73800. // least significant 5 bits are the next msbs in the final value.
  73801. value = value | ((currentByte & 31) << shiftCount);
  73802. shiftCount += 5;
  73803. }
  73804. // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
  73805. if ((value & 1) === 0) {
  73806. // + number
  73807. value = value >> 1;
  73808. }
  73809. else {
  73810. // - number
  73811. value = value >> 1;
  73812. value = -value;
  73813. }
  73814. return value;
  73815. }
  73816. }
  73817. ts.decodeMappings = decodeMappings;
  73818. function sameMapping(left, right) {
  73819. return left === right
  73820. || left.generatedLine === right.generatedLine
  73821. && left.generatedCharacter === right.generatedCharacter
  73822. && left.sourceIndex === right.sourceIndex
  73823. && left.sourceLine === right.sourceLine
  73824. && left.sourceCharacter === right.sourceCharacter
  73825. && left.nameIndex === right.nameIndex;
  73826. }
  73827. ts.sameMapping = sameMapping;
  73828. function isSourceMapping(mapping) {
  73829. return mapping.sourceIndex !== undefined
  73830. && mapping.sourceLine !== undefined
  73831. && mapping.sourceCharacter !== undefined;
  73832. }
  73833. ts.isSourceMapping = isSourceMapping;
  73834. function base64FormatEncode(value) {
  73835. return value >= 0 && value < 26 ? 65 /* A */ + value :
  73836. value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
  73837. value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
  73838. value === 62 ? 43 /* plus */ :
  73839. value === 63 ? 47 /* slash */ :
  73840. ts.Debug.fail(value + ": not a base64 value");
  73841. }
  73842. function base64FormatDecode(ch) {
  73843. return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
  73844. ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
  73845. ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
  73846. ch === 43 /* plus */ ? 62 :
  73847. ch === 47 /* slash */ ? 63 :
  73848. -1;
  73849. }
  73850. function base64VLQFormatEncode(inValue) {
  73851. // Add a new least significant bit that has the sign of the value.
  73852. // if negative number the least significant bit that gets added to the number has value 1
  73853. // else least significant bit value that gets added is 0
  73854. // eg. -1 changes to binary : 01 [1] => 3
  73855. // +1 changes to binary : 01 [0] => 2
  73856. if (inValue < 0) {
  73857. inValue = ((-inValue) << 1) + 1;
  73858. }
  73859. else {
  73860. inValue = inValue << 1;
  73861. }
  73862. // Encode 5 bits at a time starting from least significant bits
  73863. var encodedStr = "";
  73864. do {
  73865. var currentDigit = inValue & 31; // 11111
  73866. inValue = inValue >> 5;
  73867. if (inValue > 0) {
  73868. // There are still more digits to decode, set the msb (6th bit)
  73869. currentDigit = currentDigit | 32;
  73870. }
  73871. encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
  73872. } while (inValue > 0);
  73873. return encodedStr;
  73874. }
  73875. function isSourceMappedPosition(value) {
  73876. return value.sourceIndex !== undefined
  73877. && value.sourcePosition !== undefined;
  73878. }
  73879. function sameMappedPosition(left, right) {
  73880. return left.generatedPosition === right.generatedPosition
  73881. && left.sourceIndex === right.sourceIndex
  73882. && left.sourcePosition === right.sourcePosition;
  73883. }
  73884. function compareSourcePositions(left, right) {
  73885. // Compares sourcePosition without comparing sourceIndex
  73886. // since the mappings are grouped by sourceIndex
  73887. ts.Debug.assert(left.sourceIndex === right.sourceIndex);
  73888. return ts.compareValues(left.sourcePosition, right.sourcePosition);
  73889. }
  73890. function compareGeneratedPositions(left, right) {
  73891. return ts.compareValues(left.generatedPosition, right.generatedPosition);
  73892. }
  73893. function getSourcePositionOfMapping(value) {
  73894. return value.sourcePosition;
  73895. }
  73896. function getGeneratedPositionOfMapping(value) {
  73897. return value.generatedPosition;
  73898. }
  73899. function createDocumentPositionMapper(host, map, mapPath) {
  73900. var mapDirectory = ts.getDirectoryPath(mapPath);
  73901. var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
  73902. var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
  73903. var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
  73904. var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
  73905. var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
  73906. var decodedMappings;
  73907. var generatedMappings;
  73908. var sourceMappings;
  73909. return {
  73910. getSourcePosition: getSourcePosition,
  73911. getGeneratedPosition: getGeneratedPosition
  73912. };
  73913. function processMapping(mapping) {
  73914. var generatedPosition = generatedFile !== undefined
  73915. ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
  73916. : -1;
  73917. var source;
  73918. var sourcePosition;
  73919. if (isSourceMapping(mapping)) {
  73920. var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
  73921. source = map.sources[mapping.sourceIndex];
  73922. sourcePosition = sourceFile !== undefined
  73923. ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
  73924. : -1;
  73925. }
  73926. return {
  73927. generatedPosition: generatedPosition,
  73928. source: source,
  73929. sourceIndex: mapping.sourceIndex,
  73930. sourcePosition: sourcePosition,
  73931. nameIndex: mapping.nameIndex
  73932. };
  73933. }
  73934. function getDecodedMappings() {
  73935. if (decodedMappings === undefined) {
  73936. var decoder = decodeMappings(map.mappings);
  73937. var mappings = ts.arrayFrom(decoder, processMapping);
  73938. if (decoder.error !== undefined) {
  73939. if (host.log) {
  73940. host.log("Encountered error while decoding sourcemap: " + decoder.error);
  73941. }
  73942. decodedMappings = ts.emptyArray;
  73943. }
  73944. else {
  73945. decodedMappings = mappings;
  73946. }
  73947. }
  73948. return decodedMappings;
  73949. }
  73950. function getSourceMappings(sourceIndex) {
  73951. if (sourceMappings === undefined) {
  73952. var lists = [];
  73953. for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
  73954. var mapping = _a[_i];
  73955. if (!isSourceMappedPosition(mapping))
  73956. continue;
  73957. var list = lists[mapping.sourceIndex];
  73958. if (!list)
  73959. lists[mapping.sourceIndex] = list = [];
  73960. list.push(mapping);
  73961. }
  73962. sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
  73963. }
  73964. return sourceMappings[sourceIndex];
  73965. }
  73966. function getGeneratedMappings() {
  73967. if (generatedMappings === undefined) {
  73968. var list = [];
  73969. for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
  73970. var mapping = _a[_i];
  73971. list.push(mapping);
  73972. }
  73973. generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
  73974. }
  73975. return generatedMappings;
  73976. }
  73977. function getGeneratedPosition(loc) {
  73978. var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
  73979. if (sourceIndex === undefined)
  73980. return loc;
  73981. var sourceMappings = getSourceMappings(sourceIndex);
  73982. if (!ts.some(sourceMappings))
  73983. return loc;
  73984. var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
  73985. if (targetIndex < 0) {
  73986. // if no exact match, closest is 2's complement of result
  73987. targetIndex = ~targetIndex;
  73988. }
  73989. var mapping = sourceMappings[targetIndex];
  73990. if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
  73991. return loc;
  73992. }
  73993. return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
  73994. }
  73995. function getSourcePosition(loc) {
  73996. var generatedMappings = getGeneratedMappings();
  73997. if (!ts.some(generatedMappings))
  73998. return loc;
  73999. var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
  74000. if (targetIndex < 0) {
  74001. // if no exact match, closest is 2's complement of result
  74002. targetIndex = ~targetIndex;
  74003. }
  74004. var mapping = generatedMappings[targetIndex];
  74005. if (mapping === undefined || !isSourceMappedPosition(mapping)) {
  74006. return loc;
  74007. }
  74008. return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
  74009. }
  74010. }
  74011. ts.createDocumentPositionMapper = createDocumentPositionMapper;
  74012. ts.identitySourceMapConsumer = {
  74013. getSourcePosition: ts.identity,
  74014. getGeneratedPosition: ts.identity
  74015. };
  74016. })(ts || (ts = {}));
  74017. /* @internal */
  74018. var ts;
  74019. (function (ts) {
  74020. function getOriginalNodeId(node) {
  74021. node = ts.getOriginalNode(node);
  74022. return node ? ts.getNodeId(node) : 0;
  74023. }
  74024. ts.getOriginalNodeId = getOriginalNodeId;
  74025. function containsDefaultReference(node) {
  74026. if (!node)
  74027. return false;
  74028. if (!ts.isNamedImports(node))
  74029. return false;
  74030. return ts.some(node.elements, isNamedDefaultReference);
  74031. }
  74032. function isNamedDefaultReference(e) {
  74033. return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
  74034. }
  74035. function chainBundle(transformSourceFile) {
  74036. return transformSourceFileOrBundle;
  74037. function transformSourceFileOrBundle(node) {
  74038. return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
  74039. }
  74040. function transformBundle(node) {
  74041. return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
  74042. }
  74043. }
  74044. ts.chainBundle = chainBundle;
  74045. function getExportNeedsImportStarHelper(node) {
  74046. return !!ts.getNamespaceDeclarationNode(node);
  74047. }
  74048. ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
  74049. function getImportNeedsImportStarHelper(node) {
  74050. if (!!ts.getNamespaceDeclarationNode(node)) {
  74051. return true;
  74052. }
  74053. var bindings = node.importClause && node.importClause.namedBindings;
  74054. if (!bindings) {
  74055. return false;
  74056. }
  74057. if (!ts.isNamedImports(bindings))
  74058. return false;
  74059. var defaultRefCount = 0;
  74060. for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
  74061. var binding = _a[_i];
  74062. if (isNamedDefaultReference(binding)) {
  74063. defaultRefCount++;
  74064. }
  74065. }
  74066. // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
  74067. return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
  74068. }
  74069. ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
  74070. function getImportNeedsImportDefaultHelper(node) {
  74071. // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
  74072. return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
  74073. }
  74074. ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
  74075. function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
  74076. var externalImports = [];
  74077. var exportSpecifiers = ts.createMultiMap();
  74078. var exportedBindings = [];
  74079. var uniqueExports = ts.createMap();
  74080. var exportedNames;
  74081. var hasExportDefault = false;
  74082. var exportEquals;
  74083. var hasExportStarsToExportValues = false;
  74084. var hasImportStar = false;
  74085. var hasImportDefault = false;
  74086. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  74087. var node = _a[_i];
  74088. switch (node.kind) {
  74089. case 254 /* ImportDeclaration */:
  74090. // import "mod"
  74091. // import x from "mod"
  74092. // import * as x from "mod"
  74093. // import { x, y } from "mod"
  74094. externalImports.push(node);
  74095. if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
  74096. hasImportStar = true;
  74097. }
  74098. if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
  74099. hasImportDefault = true;
  74100. }
  74101. break;
  74102. case 253 /* ImportEqualsDeclaration */:
  74103. if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
  74104. // import x = require("mod")
  74105. externalImports.push(node);
  74106. }
  74107. break;
  74108. case 260 /* ExportDeclaration */:
  74109. if (node.moduleSpecifier) {
  74110. if (!node.exportClause) {
  74111. // export * from "mod"
  74112. externalImports.push(node);
  74113. hasExportStarsToExportValues = true;
  74114. }
  74115. else {
  74116. // export * as ns from "mod"
  74117. // export { x, y } from "mod"
  74118. externalImports.push(node);
  74119. }
  74120. }
  74121. else {
  74122. // export { x, y }
  74123. for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
  74124. var specifier = _c[_b];
  74125. if (!uniqueExports.get(ts.idText(specifier.name))) {
  74126. var name = specifier.propertyName || specifier.name;
  74127. exportSpecifiers.add(ts.idText(name), specifier);
  74128. var decl = resolver.getReferencedImportDeclaration(name)
  74129. || resolver.getReferencedValueDeclaration(name);
  74130. if (decl) {
  74131. multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
  74132. }
  74133. uniqueExports.set(ts.idText(specifier.name), true);
  74134. exportedNames = ts.append(exportedNames, specifier.name);
  74135. }
  74136. }
  74137. }
  74138. break;
  74139. case 259 /* ExportAssignment */:
  74140. if (node.isExportEquals && !exportEquals) {
  74141. // export = x
  74142. exportEquals = node;
  74143. }
  74144. break;
  74145. case 225 /* VariableStatement */:
  74146. if (ts.hasModifier(node, 1 /* Export */)) {
  74147. for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
  74148. var decl = _e[_d];
  74149. exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
  74150. }
  74151. }
  74152. break;
  74153. case 244 /* FunctionDeclaration */:
  74154. if (ts.hasModifier(node, 1 /* Export */)) {
  74155. if (ts.hasModifier(node, 512 /* Default */)) {
  74156. // export default function() { }
  74157. if (!hasExportDefault) {
  74158. multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
  74159. hasExportDefault = true;
  74160. }
  74161. }
  74162. else {
  74163. // export function x() { }
  74164. var name = node.name;
  74165. if (!uniqueExports.get(ts.idText(name))) {
  74166. multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
  74167. uniqueExports.set(ts.idText(name), true);
  74168. exportedNames = ts.append(exportedNames, name);
  74169. }
  74170. }
  74171. }
  74172. break;
  74173. case 245 /* ClassDeclaration */:
  74174. if (ts.hasModifier(node, 1 /* Export */)) {
  74175. if (ts.hasModifier(node, 512 /* Default */)) {
  74176. // export default class { }
  74177. if (!hasExportDefault) {
  74178. multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
  74179. hasExportDefault = true;
  74180. }
  74181. }
  74182. else {
  74183. // export class x { }
  74184. var name = node.name;
  74185. if (name && !uniqueExports.get(ts.idText(name))) {
  74186. multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
  74187. uniqueExports.set(ts.idText(name), true);
  74188. exportedNames = ts.append(exportedNames, name);
  74189. }
  74190. }
  74191. }
  74192. break;
  74193. }
  74194. }
  74195. var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
  74196. if (externalHelpersImportDeclaration) {
  74197. externalImports.unshift(externalHelpersImportDeclaration);
  74198. }
  74199. return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
  74200. }
  74201. ts.collectExternalModuleInfo = collectExternalModuleInfo;
  74202. function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
  74203. if (ts.isBindingPattern(decl.name)) {
  74204. for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
  74205. var element = _a[_i];
  74206. if (!ts.isOmittedExpression(element)) {
  74207. exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
  74208. }
  74209. }
  74210. }
  74211. else if (!ts.isGeneratedIdentifier(decl.name)) {
  74212. var text = ts.idText(decl.name);
  74213. if (!uniqueExports.get(text)) {
  74214. uniqueExports.set(text, true);
  74215. exportedNames = ts.append(exportedNames, decl.name);
  74216. }
  74217. }
  74218. return exportedNames;
  74219. }
  74220. /** Use a sparse array as a multi-map. */
  74221. function multiMapSparseArrayAdd(map, key, value) {
  74222. var values = map[key];
  74223. if (values) {
  74224. values.push(value);
  74225. }
  74226. else {
  74227. map[key] = values = [value];
  74228. }
  74229. return values;
  74230. }
  74231. /**
  74232. * Used in the module transformer to check if an expression is reasonably without sideeffect,
  74233. * and thus better to copy into multiple places rather than to cache in a temporary variable
  74234. * - this is mostly subjective beyond the requirement that the expression not be sideeffecting
  74235. */
  74236. function isSimpleCopiableExpression(expression) {
  74237. return ts.isStringLiteralLike(expression) ||
  74238. expression.kind === 8 /* NumericLiteral */ ||
  74239. ts.isKeyword(expression.kind) ||
  74240. ts.isIdentifier(expression);
  74241. }
  74242. ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
  74243. /**
  74244. * A simple inlinable expression is an expression which can be copied into multiple locations
  74245. * without risk of repeating any sideeffects and whose value could not possibly change between
  74246. * any such locations
  74247. */
  74248. function isSimpleInlineableExpression(expression) {
  74249. return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
  74250. ts.isWellKnownSymbolSyntactically(expression);
  74251. }
  74252. ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
  74253. function isCompoundAssignment(kind) {
  74254. return kind >= 63 /* FirstCompoundAssignment */
  74255. && kind <= 74 /* LastCompoundAssignment */;
  74256. }
  74257. ts.isCompoundAssignment = isCompoundAssignment;
  74258. function getNonAssignmentOperatorForCompoundAssignment(kind) {
  74259. switch (kind) {
  74260. case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
  74261. case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
  74262. case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
  74263. case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
  74264. case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
  74265. case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
  74266. case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
  74267. case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
  74268. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
  74269. case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
  74270. case 73 /* BarEqualsToken */: return 51 /* BarToken */;
  74271. case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
  74272. }
  74273. }
  74274. ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
  74275. /**
  74276. * Adds super call and preceding prologue directives into the list of statements.
  74277. *
  74278. * @param ctor The constructor node.
  74279. * @param result The list of statements.
  74280. * @param visitor The visitor to apply to each node added to the result array.
  74281. * @returns index of the statement that follows super call
  74282. */
  74283. function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
  74284. if (ctor.body) {
  74285. var statements = ctor.body.statements;
  74286. // add prologue directives to the list (if any)
  74287. var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
  74288. if (index === statements.length) {
  74289. // list contains nothing but prologue directives (or empty) - exit
  74290. return index;
  74291. }
  74292. var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
  74293. if (superIndex > -1) {
  74294. for (var i = index; i <= superIndex; i++) {
  74295. result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
  74296. }
  74297. return superIndex + 1;
  74298. }
  74299. return index;
  74300. }
  74301. return 0;
  74302. }
  74303. ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
  74304. /**
  74305. * @param input Template string input strings
  74306. * @param args Names which need to be made file-level unique
  74307. */
  74308. function helperString(input) {
  74309. var args = [];
  74310. for (var _i = 1; _i < arguments.length; _i++) {
  74311. args[_i - 1] = arguments[_i];
  74312. }
  74313. return function (uniqueName) {
  74314. var result = "";
  74315. for (var i = 0; i < args.length; i++) {
  74316. result += input[i];
  74317. result += uniqueName(args[i]);
  74318. }
  74319. result += input[input.length - 1];
  74320. return result;
  74321. };
  74322. }
  74323. ts.helperString = helperString;
  74324. /**
  74325. * Gets all the static or all the instance property declarations of a class
  74326. *
  74327. * @param node The class node.
  74328. * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
  74329. */
  74330. function getProperties(node, requireInitializer, isStatic) {
  74331. return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
  74332. }
  74333. ts.getProperties = getProperties;
  74334. /**
  74335. * Is a class element either a static or an instance property declaration with an initializer?
  74336. *
  74337. * @param member The class element node.
  74338. * @param isStatic A value indicating whether the member should be a static or instance member.
  74339. */
  74340. function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
  74341. return ts.isPropertyDeclaration(member)
  74342. && (!!member.initializer || !requireInitializer)
  74343. && ts.hasStaticModifier(member) === isStatic;
  74344. }
  74345. /**
  74346. * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
  74347. *
  74348. * @param member The class element node.
  74349. * @param isStatic A value indicating whether the member should be a static or instance member.
  74350. */
  74351. function isInitializedProperty(member) {
  74352. return member.kind === 159 /* PropertyDeclaration */
  74353. && member.initializer !== undefined;
  74354. }
  74355. ts.isInitializedProperty = isInitializedProperty;
  74356. })(ts || (ts = {}));
  74357. /*@internal*/
  74358. var ts;
  74359. (function (ts) {
  74360. var FlattenLevel;
  74361. (function (FlattenLevel) {
  74362. FlattenLevel[FlattenLevel["All"] = 0] = "All";
  74363. FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
  74364. })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
  74365. /**
  74366. * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
  74367. *
  74368. * @param node The node to flatten.
  74369. * @param visitor An optional visitor used to visit initializers.
  74370. * @param context The transformation context.
  74371. * @param level Indicates the extent to which flattening should occur.
  74372. * @param needsValue An optional value indicating whether the value from the right-hand-side of
  74373. * the destructuring assignment is needed as part of a larger expression.
  74374. * @param createAssignmentCallback An optional callback used to create the assignment expression.
  74375. */
  74376. function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
  74377. var location = node;
  74378. var value;
  74379. if (ts.isDestructuringAssignment(node)) {
  74380. value = node.right;
  74381. while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
  74382. if (ts.isDestructuringAssignment(value)) {
  74383. location = node = value;
  74384. value = node.right;
  74385. }
  74386. else {
  74387. return ts.visitNode(value, visitor, ts.isExpression);
  74388. }
  74389. }
  74390. }
  74391. var expressions;
  74392. var flattenContext = {
  74393. context: context,
  74394. level: level,
  74395. downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
  74396. hoistTempVariables: true,
  74397. emitExpression: emitExpression,
  74398. emitBindingOrAssignment: emitBindingOrAssignment,
  74399. createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
  74400. createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
  74401. createArrayBindingOrAssignmentElement: makeAssignmentElement,
  74402. visitor: visitor
  74403. };
  74404. if (value) {
  74405. value = ts.visitNode(value, visitor, ts.isExpression);
  74406. if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
  74407. bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
  74408. // If the right-hand value of the assignment is also an assignment target then
  74409. // we need to cache the right-hand value.
  74410. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
  74411. }
  74412. else if (needsValue) {
  74413. // If the right-hand value of the destructuring assignment needs to be preserved (as
  74414. // is the case when the destructuring assignment is part of a larger expression),
  74415. // then we need to cache the right-hand value.
  74416. //
  74417. // The source map location for the assignment should point to the entire binary
  74418. // expression.
  74419. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
  74420. }
  74421. else if (ts.nodeIsSynthesized(node)) {
  74422. // Generally, the source map location for a destructuring assignment is the root
  74423. // expression.
  74424. //
  74425. // However, if the root expression is synthesized (as in the case
  74426. // of the initializer when transforming a ForOfStatement), then the source map
  74427. // location should point to the right-hand value of the expression.
  74428. location = value;
  74429. }
  74430. }
  74431. flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
  74432. if (value && needsValue) {
  74433. if (!ts.some(expressions)) {
  74434. return value;
  74435. }
  74436. expressions.push(value);
  74437. }
  74438. return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
  74439. function emitExpression(expression) {
  74440. // NOTE: this completely disables source maps, but aligns with the behavior of
  74441. // `emitAssignment` in the old emitter.
  74442. ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */);
  74443. ts.aggregateTransformFlags(expression);
  74444. expressions = ts.append(expressions, expression);
  74445. }
  74446. function emitBindingOrAssignment(target, value, location, original) {
  74447. ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
  74448. var expression = createAssignmentCallback
  74449. ? createAssignmentCallback(target, value, location)
  74450. : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
  74451. expression.original = original;
  74452. emitExpression(expression);
  74453. }
  74454. }
  74455. ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
  74456. function bindingOrAssignmentElementAssignsToName(element, escapedName) {
  74457. var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
  74458. if (ts.isBindingOrAssignmentPattern(target)) {
  74459. return bindingOrAssignmentPatternAssignsToName(target, escapedName);
  74460. }
  74461. else if (ts.isIdentifier(target)) {
  74462. return target.escapedText === escapedName;
  74463. }
  74464. return false;
  74465. }
  74466. function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
  74467. var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
  74468. for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
  74469. var element = elements_3[_i];
  74470. if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
  74471. return true;
  74472. }
  74473. }
  74474. return false;
  74475. }
  74476. function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
  74477. var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
  74478. if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
  74479. return true;
  74480. }
  74481. var target = ts.getTargetOfBindingOrAssignmentElement(element);
  74482. return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
  74483. }
  74484. function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
  74485. return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
  74486. }
  74487. /**
  74488. * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
  74489. *
  74490. * @param node The node to flatten.
  74491. * @param visitor An optional visitor used to visit initializers.
  74492. * @param context The transformation context.
  74493. * @param boundValue The value bound to the declaration.
  74494. * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
  74495. * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
  74496. * @param level Indicates the extent to which flattening should occur.
  74497. */
  74498. function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
  74499. if (hoistTempVariables === void 0) { hoistTempVariables = false; }
  74500. var pendingExpressions;
  74501. var pendingDeclarations = [];
  74502. var declarations = [];
  74503. var flattenContext = {
  74504. context: context,
  74505. level: level,
  74506. downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
  74507. hoistTempVariables: hoistTempVariables,
  74508. emitExpression: emitExpression,
  74509. emitBindingOrAssignment: emitBindingOrAssignment,
  74510. createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
  74511. createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
  74512. createArrayBindingOrAssignmentElement: makeBindingElement,
  74513. visitor: visitor
  74514. };
  74515. if (ts.isVariableDeclaration(node)) {
  74516. var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
  74517. if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
  74518. bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
  74519. // If the right-hand value of the assignment is also an assignment target then
  74520. // we need to cache the right-hand value.
  74521. initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
  74522. node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
  74523. }
  74524. }
  74525. flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
  74526. if (pendingExpressions) {
  74527. var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
  74528. if (hoistTempVariables) {
  74529. var value = ts.inlineExpressions(pendingExpressions);
  74530. pendingExpressions = undefined;
  74531. emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
  74532. }
  74533. else {
  74534. context.hoistVariableDeclaration(temp);
  74535. var pendingDeclaration = ts.last(pendingDeclarations);
  74536. pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
  74537. ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
  74538. pendingDeclaration.value = temp;
  74539. }
  74540. }
  74541. for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
  74542. var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
  74543. var variable = ts.createVariableDeclaration(name,
  74544. /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
  74545. variable.original = original;
  74546. ts.setTextRange(variable, location);
  74547. if (ts.isIdentifier(name)) {
  74548. ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */);
  74549. }
  74550. ts.aggregateTransformFlags(variable);
  74551. declarations.push(variable);
  74552. }
  74553. return declarations;
  74554. function emitExpression(value) {
  74555. pendingExpressions = ts.append(pendingExpressions, value);
  74556. }
  74557. function emitBindingOrAssignment(target, value, location, original) {
  74558. ts.Debug.assertNode(target, ts.isBindingName);
  74559. if (pendingExpressions) {
  74560. value = ts.inlineExpressions(ts.append(pendingExpressions, value));
  74561. pendingExpressions = undefined;
  74562. }
  74563. pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
  74564. }
  74565. }
  74566. ts.flattenDestructuringBinding = flattenDestructuringBinding;
  74567. /**
  74568. * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
  74569. *
  74570. * @param flattenContext Options used to control flattening.
  74571. * @param element The element to flatten.
  74572. * @param value The current RHS value to assign to the element.
  74573. * @param location The location to use for source maps and comments.
  74574. * @param skipInitializer An optional value indicating whether to include the initializer
  74575. * for the element.
  74576. */
  74577. function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
  74578. if (!skipInitializer) {
  74579. var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
  74580. if (initializer) {
  74581. // Combine value and initializer
  74582. value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
  74583. }
  74584. else if (!value) {
  74585. // Use 'void 0' in absence of value and initializer
  74586. value = ts.createVoidZero();
  74587. }
  74588. }
  74589. var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
  74590. if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
  74591. flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
  74592. }
  74593. else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
  74594. flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
  74595. }
  74596. else {
  74597. flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
  74598. }
  74599. }
  74600. /**
  74601. * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
  74602. *
  74603. * @param flattenContext Options used to control flattening.
  74604. * @param parent The parent element of the pattern.
  74605. * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
  74606. * @param value The current RHS value to assign to the element.
  74607. * @param location The location to use for source maps and comments.
  74608. */
  74609. function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
  74610. var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
  74611. var numElements = elements.length;
  74612. if (numElements !== 1) {
  74613. // For anything other than a single-element destructuring we need to generate a temporary
  74614. // to ensure value is evaluated exactly once. Additionally, if we have zero elements
  74615. // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
  74616. // so in that case, we'll intentionally create that temporary.
  74617. var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
  74618. value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
  74619. }
  74620. var bindingElements;
  74621. var computedTempVariables;
  74622. for (var i = 0; i < numElements; i++) {
  74623. var element = elements[i];
  74624. if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
  74625. var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
  74626. if (flattenContext.level >= 1 /* ObjectRest */
  74627. && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
  74628. && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
  74629. && !ts.isComputedPropertyName(propertyName)) {
  74630. bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
  74631. }
  74632. else {
  74633. if (bindingElements) {
  74634. flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
  74635. bindingElements = undefined;
  74636. }
  74637. var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
  74638. if (ts.isComputedPropertyName(propertyName)) {
  74639. computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
  74640. }
  74641. flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
  74642. }
  74643. }
  74644. else if (i === numElements - 1) {
  74645. if (bindingElements) {
  74646. flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
  74647. bindingElements = undefined;
  74648. }
  74649. var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
  74650. flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
  74651. }
  74652. }
  74653. if (bindingElements) {
  74654. flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
  74655. }
  74656. }
  74657. /**
  74658. * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
  74659. *
  74660. * @param flattenContext Options used to control flattening.
  74661. * @param parent The parent element of the pattern.
  74662. * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
  74663. * @param value The current RHS value to assign to the element.
  74664. * @param location The location to use for source maps and comments.
  74665. */
  74666. function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
  74667. var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
  74668. var numElements = elements.length;
  74669. if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
  74670. // Read the elements of the iterable into an array
  74671. value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
  74672. ? undefined
  74673. : numElements, location),
  74674. /*reuseIdentifierExpressions*/ false, location);
  74675. }
  74676. else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
  74677. || ts.every(elements, ts.isOmittedExpression)) {
  74678. // For anything other than a single-element destructuring we need to generate a temporary
  74679. // to ensure value is evaluated exactly once. Additionally, if we have zero elements
  74680. // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
  74681. // so in that case, we'll intentionally create that temporary.
  74682. // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
  74683. // then we will create temporary variable.
  74684. var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
  74685. value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
  74686. }
  74687. var bindingElements;
  74688. var restContainingElements;
  74689. for (var i = 0; i < numElements; i++) {
  74690. var element = elements[i];
  74691. if (flattenContext.level >= 1 /* ObjectRest */) {
  74692. // If an array pattern contains an ObjectRest, we must cache the result so that we
  74693. // can perform the ObjectRest destructuring in a different declaration
  74694. if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  74695. var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
  74696. if (flattenContext.hoistTempVariables) {
  74697. flattenContext.context.hoistVariableDeclaration(temp);
  74698. }
  74699. restContainingElements = ts.append(restContainingElements, [temp, element]);
  74700. bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
  74701. }
  74702. else {
  74703. bindingElements = ts.append(bindingElements, element);
  74704. }
  74705. }
  74706. else if (ts.isOmittedExpression(element)) {
  74707. continue;
  74708. }
  74709. else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
  74710. var rhsValue = ts.createElementAccess(value, i);
  74711. flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
  74712. }
  74713. else if (i === numElements - 1) {
  74714. var rhsValue = ts.createArraySlice(value, i);
  74715. flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
  74716. }
  74717. }
  74718. if (bindingElements) {
  74719. flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
  74720. }
  74721. if (restContainingElements) {
  74722. for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
  74723. var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
  74724. flattenBindingOrAssignmentElement(flattenContext, element, id, element);
  74725. }
  74726. }
  74727. }
  74728. /**
  74729. * Creates an expression used to provide a default value if a value is `undefined` at runtime.
  74730. *
  74731. * @param flattenContext Options used to control flattening.
  74732. * @param value The RHS value to test.
  74733. * @param defaultValue The default value to use if `value` is `undefined` at runtime.
  74734. * @param location The location to use for source maps and comments.
  74735. */
  74736. function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
  74737. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
  74738. return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
  74739. }
  74740. /**
  74741. * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
  74742. * right-hand side of a transformed destructuring assignment.
  74743. *
  74744. * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
  74745. *
  74746. * @param flattenContext Options used to control flattening.
  74747. * @param value The RHS value that is the source of the property.
  74748. * @param propertyName The destructuring property name.
  74749. */
  74750. function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
  74751. if (ts.isComputedPropertyName(propertyName)) {
  74752. var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
  74753. return ts.createElementAccess(value, argumentExpression);
  74754. }
  74755. else if (ts.isStringOrNumericLiteralLike(propertyName)) {
  74756. var argumentExpression = ts.getSynthesizedClone(propertyName);
  74757. argumentExpression.text = argumentExpression.text;
  74758. return ts.createElementAccess(value, argumentExpression);
  74759. }
  74760. else {
  74761. var name = ts.createIdentifier(ts.idText(propertyName));
  74762. return ts.createPropertyAccess(value, name);
  74763. }
  74764. }
  74765. /**
  74766. * Ensures that there exists a declared identifier whose value holds the given expression.
  74767. * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
  74768. * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
  74769. *
  74770. * @param flattenContext Options used to control flattening.
  74771. * @param value the expression whose value needs to be bound.
  74772. * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
  74773. * false if it is necessary to always emit an identifier.
  74774. * @param location The location to use for source maps and comments.
  74775. */
  74776. function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
  74777. if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
  74778. return value;
  74779. }
  74780. else {
  74781. var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
  74782. if (flattenContext.hoistTempVariables) {
  74783. flattenContext.context.hoistVariableDeclaration(temp);
  74784. flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
  74785. }
  74786. else {
  74787. flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
  74788. }
  74789. return temp;
  74790. }
  74791. }
  74792. function makeArrayBindingPattern(elements) {
  74793. ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
  74794. return ts.createArrayBindingPattern(elements);
  74795. }
  74796. function makeArrayAssignmentPattern(elements) {
  74797. return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
  74798. }
  74799. function makeObjectBindingPattern(elements) {
  74800. ts.Debug.assertEachNode(elements, ts.isBindingElement);
  74801. return ts.createObjectBindingPattern(elements);
  74802. }
  74803. function makeObjectAssignmentPattern(elements) {
  74804. return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
  74805. }
  74806. function makeBindingElement(name) {
  74807. return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
  74808. }
  74809. function makeAssignmentElement(name) {
  74810. return name;
  74811. }
  74812. ts.restHelper = {
  74813. name: "typescript:rest",
  74814. importName: "__rest",
  74815. scoped: false,
  74816. text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n };"
  74817. };
  74818. /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
  74819. * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
  74820. */
  74821. function createRestCall(context, value, elements, computedTempVariables, location) {
  74822. context.requestEmitHelper(ts.restHelper);
  74823. var propertyNames = [];
  74824. var computedTempVariableOffset = 0;
  74825. for (var i = 0; i < elements.length - 1; i++) {
  74826. var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
  74827. if (propertyName) {
  74828. if (ts.isComputedPropertyName(propertyName)) {
  74829. var temp = computedTempVariables[computedTempVariableOffset];
  74830. computedTempVariableOffset++;
  74831. // typeof _tmp === "symbol" ? _tmp : _tmp + ""
  74832. propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
  74833. }
  74834. else {
  74835. propertyNames.push(ts.createLiteral(propertyName));
  74836. }
  74837. }
  74838. }
  74839. return ts.createCall(ts.getUnscopedHelperName("__rest"),
  74840. /*typeArguments*/ undefined, [
  74841. value,
  74842. ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
  74843. ]);
  74844. }
  74845. })(ts || (ts = {}));
  74846. /*@internal*/
  74847. var ts;
  74848. (function (ts) {
  74849. /**
  74850. * Indicates whether to emit type metadata in the new format.
  74851. */
  74852. var USE_NEW_TYPE_METADATA_FORMAT = false;
  74853. var TypeScriptSubstitutionFlags;
  74854. (function (TypeScriptSubstitutionFlags) {
  74855. /** Enables substitutions for decorated classes. */
  74856. TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
  74857. /** Enables substitutions for namespace exports. */
  74858. TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
  74859. /* Enables substitutions for unqualified enum members */
  74860. TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
  74861. })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
  74862. var ClassFacts;
  74863. (function (ClassFacts) {
  74864. ClassFacts[ClassFacts["None"] = 0] = "None";
  74865. ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
  74866. ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
  74867. ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
  74868. ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
  74869. ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
  74870. ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
  74871. ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
  74872. ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
  74873. ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
  74874. ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
  74875. ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
  74876. ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
  74877. })(ClassFacts || (ClassFacts = {}));
  74878. function transformTypeScript(context) {
  74879. var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
  74880. var resolver = context.getEmitResolver();
  74881. var compilerOptions = context.getCompilerOptions();
  74882. var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
  74883. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  74884. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  74885. // Save the previous transformation hooks.
  74886. var previousOnEmitNode = context.onEmitNode;
  74887. var previousOnSubstituteNode = context.onSubstituteNode;
  74888. // Set new transformation hooks.
  74889. context.onEmitNode = onEmitNode;
  74890. context.onSubstituteNode = onSubstituteNode;
  74891. // Enable substitution for property/element access to emit const enum values.
  74892. context.enableSubstitution(194 /* PropertyAccessExpression */);
  74893. context.enableSubstitution(195 /* ElementAccessExpression */);
  74894. // These variables contain state that changes as we descend into the tree.
  74895. var currentSourceFile;
  74896. var currentNamespace;
  74897. var currentNamespaceContainerName;
  74898. var currentLexicalScope;
  74899. var currentNameScope;
  74900. var currentScopeFirstDeclarationsOfName;
  74901. var currentClassHasParameterProperties;
  74902. /**
  74903. * Keeps track of whether expression substitution has been enabled for specific edge cases.
  74904. * They are persisted between each SourceFile transformation and should not be reset.
  74905. */
  74906. var enabledSubstitutions;
  74907. /**
  74908. * A map that keeps track of aliases created for classes with decorators to avoid issues
  74909. * with the double-binding behavior of classes.
  74910. */
  74911. var classAliases;
  74912. /**
  74913. * Keeps track of whether we are within any containing namespaces when performing
  74914. * just-in-time substitution while printing an expression identifier.
  74915. */
  74916. var applicableSubstitutions;
  74917. return transformSourceFileOrBundle;
  74918. function transformSourceFileOrBundle(node) {
  74919. if (node.kind === 291 /* Bundle */) {
  74920. return transformBundle(node);
  74921. }
  74922. return transformSourceFile(node);
  74923. }
  74924. function transformBundle(node) {
  74925. return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
  74926. if (prepend.kind === 293 /* InputFiles */) {
  74927. return ts.createUnparsedSourceFile(prepend, "js");
  74928. }
  74929. return prepend;
  74930. }));
  74931. }
  74932. /**
  74933. * Transform TypeScript-specific syntax in a SourceFile.
  74934. *
  74935. * @param node A SourceFile node.
  74936. */
  74937. function transformSourceFile(node) {
  74938. if (node.isDeclarationFile) {
  74939. return node;
  74940. }
  74941. currentSourceFile = node;
  74942. var visited = saveStateAndInvoke(node, visitSourceFile);
  74943. ts.addEmitHelpers(visited, context.readEmitHelpers());
  74944. currentSourceFile = undefined;
  74945. return visited;
  74946. }
  74947. /**
  74948. * Visits a node, saving and restoring state variables on the stack.
  74949. *
  74950. * @param node The node to visit.
  74951. */
  74952. function saveStateAndInvoke(node, f) {
  74953. // Save state
  74954. var savedCurrentScope = currentLexicalScope;
  74955. var savedCurrentNameScope = currentNameScope;
  74956. var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
  74957. var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
  74958. // Handle state changes before visiting a node.
  74959. onBeforeVisitNode(node);
  74960. var visited = f(node);
  74961. // Restore state
  74962. if (currentLexicalScope !== savedCurrentScope) {
  74963. currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
  74964. }
  74965. currentLexicalScope = savedCurrentScope;
  74966. currentNameScope = savedCurrentNameScope;
  74967. currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
  74968. return visited;
  74969. }
  74970. /**
  74971. * Performs actions that should always occur immediately before visiting a node.
  74972. *
  74973. * @param node The node to visit.
  74974. */
  74975. function onBeforeVisitNode(node) {
  74976. switch (node.kind) {
  74977. case 290 /* SourceFile */:
  74978. case 251 /* CaseBlock */:
  74979. case 250 /* ModuleBlock */:
  74980. case 223 /* Block */:
  74981. currentLexicalScope = node;
  74982. currentNameScope = undefined;
  74983. currentScopeFirstDeclarationsOfName = undefined;
  74984. break;
  74985. case 245 /* ClassDeclaration */:
  74986. case 244 /* FunctionDeclaration */:
  74987. if (ts.hasModifier(node, 2 /* Ambient */)) {
  74988. break;
  74989. }
  74990. // Record these declarations provided that they have a name.
  74991. if (node.name) {
  74992. recordEmittedDeclarationInScope(node);
  74993. }
  74994. else {
  74995. // These nodes should always have names unless they are default-exports;
  74996. // however, class declaration parsing allows for undefined names, so syntactically invalid
  74997. // programs may also have an undefined name.
  74998. ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
  74999. }
  75000. if (ts.isClassDeclaration(node)) {
  75001. // XXX: should probably also cover interfaces and type aliases that can have type variables?
  75002. currentNameScope = node;
  75003. }
  75004. break;
  75005. }
  75006. }
  75007. /**
  75008. * General-purpose node visitor.
  75009. *
  75010. * @param node The node to visit.
  75011. */
  75012. function visitor(node) {
  75013. return saveStateAndInvoke(node, visitorWorker);
  75014. }
  75015. /**
  75016. * Visits and possibly transforms any node.
  75017. *
  75018. * @param node The node to visit.
  75019. */
  75020. function visitorWorker(node) {
  75021. if (node.transformFlags & 1 /* ContainsTypeScript */) {
  75022. return visitTypeScript(node);
  75023. }
  75024. return node;
  75025. }
  75026. /**
  75027. * Specialized visitor that visits the immediate children of a SourceFile.
  75028. *
  75029. * @param node The node to visit.
  75030. */
  75031. function sourceElementVisitor(node) {
  75032. return saveStateAndInvoke(node, sourceElementVisitorWorker);
  75033. }
  75034. /**
  75035. * Specialized visitor that visits the immediate children of a SourceFile.
  75036. *
  75037. * @param node The node to visit.
  75038. */
  75039. function sourceElementVisitorWorker(node) {
  75040. switch (node.kind) {
  75041. case 254 /* ImportDeclaration */:
  75042. case 253 /* ImportEqualsDeclaration */:
  75043. case 259 /* ExportAssignment */:
  75044. case 260 /* ExportDeclaration */:
  75045. return visitEllidableStatement(node);
  75046. default:
  75047. return visitorWorker(node);
  75048. }
  75049. }
  75050. function visitEllidableStatement(node) {
  75051. var parsed = ts.getParseTreeNode(node);
  75052. if (parsed !== node) {
  75053. // If the node has been transformed by a `before` transformer, perform no ellision on it
  75054. // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
  75055. // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
  75056. // and will trigger debug failures when debug verbosity is turned up
  75057. if (node.transformFlags & 1 /* ContainsTypeScript */) {
  75058. // This node contains TypeScript, so we should visit its children.
  75059. return ts.visitEachChild(node, visitor, context);
  75060. }
  75061. // Otherwise, we can just return the node
  75062. return node;
  75063. }
  75064. switch (node.kind) {
  75065. case 254 /* ImportDeclaration */:
  75066. return visitImportDeclaration(node);
  75067. case 253 /* ImportEqualsDeclaration */:
  75068. return visitImportEqualsDeclaration(node);
  75069. case 259 /* ExportAssignment */:
  75070. return visitExportAssignment(node);
  75071. case 260 /* ExportDeclaration */:
  75072. return visitExportDeclaration(node);
  75073. default:
  75074. ts.Debug.fail("Unhandled ellided statement");
  75075. }
  75076. }
  75077. /**
  75078. * Specialized visitor that visits the immediate children of a namespace.
  75079. *
  75080. * @param node The node to visit.
  75081. */
  75082. function namespaceElementVisitor(node) {
  75083. return saveStateAndInvoke(node, namespaceElementVisitorWorker);
  75084. }
  75085. /**
  75086. * Specialized visitor that visits the immediate children of a namespace.
  75087. *
  75088. * @param node The node to visit.
  75089. */
  75090. function namespaceElementVisitorWorker(node) {
  75091. if (node.kind === 260 /* ExportDeclaration */ ||
  75092. node.kind === 254 /* ImportDeclaration */ ||
  75093. node.kind === 255 /* ImportClause */ ||
  75094. (node.kind === 253 /* ImportEqualsDeclaration */ &&
  75095. node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
  75096. // do not emit ES6 imports and exports since they are illegal inside a namespace
  75097. return undefined;
  75098. }
  75099. else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
  75100. return visitTypeScript(node);
  75101. }
  75102. return node;
  75103. }
  75104. /**
  75105. * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
  75106. *
  75107. * @param node The node to visit.
  75108. */
  75109. function classElementVisitor(node) {
  75110. return saveStateAndInvoke(node, classElementVisitorWorker);
  75111. }
  75112. /**
  75113. * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
  75114. *
  75115. * @param node The node to visit.
  75116. */
  75117. function classElementVisitorWorker(node) {
  75118. switch (node.kind) {
  75119. case 162 /* Constructor */:
  75120. return visitConstructor(node);
  75121. case 159 /* PropertyDeclaration */:
  75122. // Property declarations are not TypeScript syntax, but they must be visited
  75123. // for the decorator transformation.
  75124. return visitPropertyDeclaration(node);
  75125. case 167 /* IndexSignature */:
  75126. case 163 /* GetAccessor */:
  75127. case 164 /* SetAccessor */:
  75128. case 161 /* MethodDeclaration */:
  75129. // Fallback to the default visit behavior.
  75130. return visitorWorker(node);
  75131. case 222 /* SemicolonClassElement */:
  75132. return node;
  75133. default:
  75134. return ts.Debug.failBadSyntaxKind(node);
  75135. }
  75136. }
  75137. function modifierVisitor(node) {
  75138. if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
  75139. return undefined;
  75140. }
  75141. else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
  75142. return undefined;
  75143. }
  75144. return node;
  75145. }
  75146. /**
  75147. * Branching visitor, visits a TypeScript syntax node.
  75148. *
  75149. * @param node The node to visit.
  75150. */
  75151. function visitTypeScript(node) {
  75152. if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
  75153. // TypeScript ambient declarations are elided, but some comments may be preserved.
  75154. // See the implementation of `getLeadingComments` in comments.ts for more details.
  75155. return ts.createNotEmittedStatement(node);
  75156. }
  75157. switch (node.kind) {
  75158. case 89 /* ExportKeyword */:
  75159. case 84 /* DefaultKeyword */:
  75160. // ES6 export and default modifiers are elided when inside a namespace.
  75161. return currentNamespace ? undefined : node;
  75162. case 119 /* PublicKeyword */:
  75163. case 117 /* PrivateKeyword */:
  75164. case 118 /* ProtectedKeyword */:
  75165. case 122 /* AbstractKeyword */:
  75166. case 81 /* ConstKeyword */:
  75167. case 130 /* DeclareKeyword */:
  75168. case 138 /* ReadonlyKeyword */:
  75169. // TypeScript accessibility and readonly modifiers are elided
  75170. // falls through
  75171. case 174 /* ArrayType */:
  75172. case 175 /* TupleType */:
  75173. case 176 /* OptionalType */:
  75174. case 177 /* RestType */:
  75175. case 173 /* TypeLiteral */:
  75176. case 168 /* TypePredicate */:
  75177. case 155 /* TypeParameter */:
  75178. case 125 /* AnyKeyword */:
  75179. case 148 /* UnknownKeyword */:
  75180. case 128 /* BooleanKeyword */:
  75181. case 143 /* StringKeyword */:
  75182. case 140 /* NumberKeyword */:
  75183. case 137 /* NeverKeyword */:
  75184. case 110 /* VoidKeyword */:
  75185. case 144 /* SymbolKeyword */:
  75186. case 171 /* ConstructorType */:
  75187. case 170 /* FunctionType */:
  75188. case 172 /* TypeQuery */:
  75189. case 169 /* TypeReference */:
  75190. case 178 /* UnionType */:
  75191. case 179 /* IntersectionType */:
  75192. case 180 /* ConditionalType */:
  75193. case 182 /* ParenthesizedType */:
  75194. case 183 /* ThisType */:
  75195. case 184 /* TypeOperator */:
  75196. case 185 /* IndexedAccessType */:
  75197. case 186 /* MappedType */:
  75198. case 187 /* LiteralType */:
  75199. // TypeScript type nodes are elided.
  75200. // falls through
  75201. case 167 /* IndexSignature */:
  75202. // TypeScript index signatures are elided.
  75203. // falls through
  75204. case 157 /* Decorator */:
  75205. // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
  75206. // falls through
  75207. case 247 /* TypeAliasDeclaration */:
  75208. // TypeScript type-only declarations are elided.
  75209. return undefined;
  75210. case 159 /* PropertyDeclaration */:
  75211. // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
  75212. return visitPropertyDeclaration(node);
  75213. case 252 /* NamespaceExportDeclaration */:
  75214. // TypeScript namespace export declarations are elided.
  75215. return undefined;
  75216. case 162 /* Constructor */:
  75217. return visitConstructor(node);
  75218. case 246 /* InterfaceDeclaration */:
  75219. // TypeScript interfaces are elided, but some comments may be preserved.
  75220. // See the implementation of `getLeadingComments` in comments.ts for more details.
  75221. return ts.createNotEmittedStatement(node);
  75222. case 245 /* ClassDeclaration */:
  75223. // This may be a class declaration with TypeScript syntax extensions.
  75224. //
  75225. // TypeScript class syntax extensions include:
  75226. // - decorators
  75227. // - optional `implements` heritage clause
  75228. // - parameter property assignments in the constructor
  75229. // - index signatures
  75230. // - method overload signatures
  75231. return visitClassDeclaration(node);
  75232. case 214 /* ClassExpression */:
  75233. // This may be a class expression with TypeScript syntax extensions.
  75234. //
  75235. // TypeScript class syntax extensions include:
  75236. // - decorators
  75237. // - optional `implements` heritage clause
  75238. // - parameter property assignments in the constructor
  75239. // - index signatures
  75240. // - method overload signatures
  75241. return visitClassExpression(node);
  75242. case 279 /* HeritageClause */:
  75243. // This may be a heritage clause with TypeScript syntax extensions.
  75244. //
  75245. // TypeScript heritage clause extensions include:
  75246. // - `implements` clause
  75247. return visitHeritageClause(node);
  75248. case 216 /* ExpressionWithTypeArguments */:
  75249. // TypeScript supports type arguments on an expression in an `extends` heritage clause.
  75250. return visitExpressionWithTypeArguments(node);
  75251. case 161 /* MethodDeclaration */:
  75252. // TypeScript method declarations may have decorators, modifiers
  75253. // or type annotations.
  75254. return visitMethodDeclaration(node);
  75255. case 163 /* GetAccessor */:
  75256. // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
  75257. return visitGetAccessor(node);
  75258. case 164 /* SetAccessor */:
  75259. // Set Accessors can have TypeScript modifiers and type annotations.
  75260. return visitSetAccessor(node);
  75261. case 244 /* FunctionDeclaration */:
  75262. // Typescript function declarations can have modifiers, decorators, and type annotations.
  75263. return visitFunctionDeclaration(node);
  75264. case 201 /* FunctionExpression */:
  75265. // TypeScript function expressions can have modifiers and type annotations.
  75266. return visitFunctionExpression(node);
  75267. case 202 /* ArrowFunction */:
  75268. // TypeScript arrow functions can have modifiers and type annotations.
  75269. return visitArrowFunction(node);
  75270. case 156 /* Parameter */:
  75271. // This may be a parameter declaration with TypeScript syntax extensions.
  75272. //
  75273. // TypeScript parameter declaration syntax extensions include:
  75274. // - decorators
  75275. // - accessibility modifiers
  75276. // - the question mark (?) token for optional parameters
  75277. // - type annotations
  75278. // - this parameters
  75279. return visitParameter(node);
  75280. case 200 /* ParenthesizedExpression */:
  75281. // ParenthesizedExpressions are TypeScript if their expression is a
  75282. // TypeAssertion or AsExpression
  75283. return visitParenthesizedExpression(node);
  75284. case 199 /* TypeAssertionExpression */:
  75285. case 217 /* AsExpression */:
  75286. // TypeScript type assertions are removed, but their subtrees are preserved.
  75287. return visitAssertionExpression(node);
  75288. case 196 /* CallExpression */:
  75289. return visitCallExpression(node);
  75290. case 197 /* NewExpression */:
  75291. return visitNewExpression(node);
  75292. case 198 /* TaggedTemplateExpression */:
  75293. return visitTaggedTemplateExpression(node);
  75294. case 218 /* NonNullExpression */:
  75295. // TypeScript non-null expressions are removed, but their subtrees are preserved.
  75296. return visitNonNullExpression(node);
  75297. case 248 /* EnumDeclaration */:
  75298. // TypeScript enum declarations do not exist in ES6 and must be rewritten.
  75299. return visitEnumDeclaration(node);
  75300. case 225 /* VariableStatement */:
  75301. // TypeScript namespace exports for variable statements must be transformed.
  75302. return visitVariableStatement(node);
  75303. case 242 /* VariableDeclaration */:
  75304. return visitVariableDeclaration(node);
  75305. case 249 /* ModuleDeclaration */:
  75306. // TypeScript namespace declarations must be transformed.
  75307. return visitModuleDeclaration(node);
  75308. case 253 /* ImportEqualsDeclaration */:
  75309. // TypeScript namespace or external module import.
  75310. return visitImportEqualsDeclaration(node);
  75311. default:
  75312. // node contains some other TypeScript syntax
  75313. return ts.visitEachChild(node, visitor, context);
  75314. }
  75315. }
  75316. function visitSourceFile(node) {
  75317. var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
  75318. !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
  75319. !ts.isJsonSourceFile(node);
  75320. return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
  75321. }
  75322. /**
  75323. * Tests whether we should emit a __decorate call for a class declaration.
  75324. */
  75325. function shouldEmitDecorateCallForClass(node) {
  75326. if (node.decorators && node.decorators.length > 0) {
  75327. return true;
  75328. }
  75329. var constructor = ts.getFirstConstructorWithBody(node);
  75330. if (constructor) {
  75331. return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
  75332. }
  75333. return false;
  75334. }
  75335. /**
  75336. * Tests whether we should emit a __decorate call for a parameter declaration.
  75337. */
  75338. function shouldEmitDecorateCallForParameter(parameter) {
  75339. return parameter.decorators !== undefined && parameter.decorators.length > 0;
  75340. }
  75341. function getClassFacts(node, staticProperties) {
  75342. var facts = 0 /* None */;
  75343. if (ts.some(staticProperties))
  75344. facts |= 1 /* HasStaticInitializedProperties */;
  75345. var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
  75346. if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
  75347. facts |= 64 /* IsDerivedClass */;
  75348. if (shouldEmitDecorateCallForClass(node))
  75349. facts |= 2 /* HasConstructorDecorators */;
  75350. if (ts.childIsDecorated(node))
  75351. facts |= 4 /* HasMemberDecorators */;
  75352. if (isExportOfNamespace(node))
  75353. facts |= 8 /* IsExportOfNamespace */;
  75354. else if (isDefaultExternalModuleExport(node))
  75355. facts |= 32 /* IsDefaultExternalExport */;
  75356. else if (isNamedExternalModuleExport(node))
  75357. facts |= 16 /* IsNamedExternalExport */;
  75358. if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
  75359. facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
  75360. return facts;
  75361. }
  75362. function hasTypeScriptClassSyntax(node) {
  75363. return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
  75364. }
  75365. function isClassLikeDeclarationWithTypeScriptSyntax(node) {
  75366. return ts.some(node.decorators)
  75367. || ts.some(node.typeParameters)
  75368. || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
  75369. || ts.some(node.members, hasTypeScriptClassSyntax);
  75370. }
  75371. function visitClassDeclaration(node) {
  75372. if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
  75373. return ts.visitEachChild(node, visitor, context);
  75374. }
  75375. var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
  75376. var facts = getClassFacts(node, staticProperties);
  75377. if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
  75378. context.startLexicalEnvironment();
  75379. }
  75380. var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
  75381. var classStatement = facts & 2 /* HasConstructorDecorators */
  75382. ? createClassDeclarationHeadWithDecorators(node, name)
  75383. : createClassDeclarationHeadWithoutDecorators(node, name, facts);
  75384. var statements = [classStatement];
  75385. // Write any decorators of the node.
  75386. addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
  75387. addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
  75388. addConstructorDecorationStatement(statements, node);
  75389. if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
  75390. // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
  75391. // 'es2015' transformer can properly nest static initializers and decorators. The result
  75392. // looks something like:
  75393. //
  75394. // var C = function () {
  75395. // class C {
  75396. // }
  75397. // C.static_prop = 1;
  75398. // return C;
  75399. // }();
  75400. //
  75401. var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
  75402. var localName = ts.getInternalName(node);
  75403. // The following partially-emitted expression exists purely to align our sourcemap
  75404. // emit with the original emitter.
  75405. var outer = ts.createPartiallyEmittedExpression(localName);
  75406. outer.end = closingBraceLocation.end;
  75407. ts.setEmitFlags(outer, 1536 /* NoComments */);
  75408. var statement = ts.createReturn(outer);
  75409. statement.pos = closingBraceLocation.pos;
  75410. ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
  75411. statements.push(statement);
  75412. ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
  75413. var iife = ts.createImmediatelyInvokedArrowFunction(statements);
  75414. ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
  75415. var varStatement = ts.createVariableStatement(
  75416. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  75417. ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false),
  75418. /*type*/ undefined, iife)
  75419. ]));
  75420. ts.setOriginalNode(varStatement, node);
  75421. ts.setCommentRange(varStatement, node);
  75422. ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
  75423. ts.startOnNewLine(varStatement);
  75424. statements = [varStatement];
  75425. }
  75426. // If the class is exported as part of a TypeScript namespace, emit the namespace export.
  75427. // Otherwise, if the class was exported at the top level and was decorated, emit an export
  75428. // declaration or export default for the class.
  75429. if (facts & 8 /* IsExportOfNamespace */) {
  75430. addExportMemberAssignment(statements, node);
  75431. }
  75432. else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
  75433. if (facts & 32 /* IsDefaultExternalExport */) {
  75434. statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
  75435. }
  75436. else if (facts & 16 /* IsNamedExternalExport */) {
  75437. statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
  75438. }
  75439. }
  75440. if (statements.length > 1) {
  75441. // Add a DeclarationMarker as a marker for the end of the declaration
  75442. statements.push(ts.createEndOfDeclarationMarker(node));
  75443. ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
  75444. }
  75445. return ts.singleOrMany(statements);
  75446. }
  75447. /**
  75448. * Transforms a non-decorated class declaration and appends the resulting statements.
  75449. *
  75450. * @param node A ClassDeclaration node.
  75451. * @param name The name of the class.
  75452. * @param facts Precomputed facts about the class.
  75453. */
  75454. function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
  75455. // ${modifiers} class ${name} ${heritageClauses} {
  75456. // ${members}
  75457. // }
  75458. // we do not emit modifiers on the declaration if we are emitting an IIFE
  75459. var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
  75460. ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
  75461. : undefined;
  75462. var classDeclaration = ts.createClassDeclaration(
  75463. /*decorators*/ undefined, modifiers, name,
  75464. /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
  75465. // To better align with the old emitter, we should not emit a trailing source map
  75466. // entry if the class has static properties.
  75467. var emitFlags = ts.getEmitFlags(node);
  75468. if (facts & 1 /* HasStaticInitializedProperties */) {
  75469. emitFlags |= 32 /* NoTrailingSourceMap */;
  75470. }
  75471. ts.aggregateTransformFlags(classDeclaration);
  75472. ts.setTextRange(classDeclaration, node);
  75473. ts.setOriginalNode(classDeclaration, node);
  75474. ts.setEmitFlags(classDeclaration, emitFlags);
  75475. return classDeclaration;
  75476. }
  75477. /**
  75478. * Transforms a decorated class declaration and appends the resulting statements. If
  75479. * the class requires an alias to avoid issues with double-binding, the alias is returned.
  75480. */
  75481. function createClassDeclarationHeadWithDecorators(node, name) {
  75482. // When we emit an ES6 class that has a class decorator, we must tailor the
  75483. // emit to certain specific cases.
  75484. //
  75485. // In the simplest case, we emit the class declaration as a let declaration, and
  75486. // evaluate decorators after the close of the class body:
  75487. //
  75488. // [Example 1]
  75489. // ---------------------------------------------------------------------
  75490. // TypeScript | Javascript
  75491. // ---------------------------------------------------------------------
  75492. // @dec | let C = class C {
  75493. // class C { | }
  75494. // } | C = __decorate([dec], C);
  75495. // ---------------------------------------------------------------------
  75496. // @dec | let C = class C {
  75497. // export class C { | }
  75498. // } | C = __decorate([dec], C);
  75499. // | export { C };
  75500. // ---------------------------------------------------------------------
  75501. //
  75502. // If a class declaration contains a reference to itself *inside* of the class body,
  75503. // this introduces two bindings to the class: One outside of the class body, and one
  75504. // inside of the class body. If we apply decorators as in [Example 1] above, there
  75505. // is the possibility that the decorator `dec` will return a new value for the
  75506. // constructor, which would result in the binding inside of the class no longer
  75507. // pointing to the same reference as the binding outside of the class.
  75508. //
  75509. // As a result, we must instead rewrite all references to the class *inside* of the
  75510. // class body to instead point to a local temporary alias for the class:
  75511. //
  75512. // [Example 2]
  75513. // ---------------------------------------------------------------------
  75514. // TypeScript | Javascript
  75515. // ---------------------------------------------------------------------
  75516. // @dec | let C = C_1 = class C {
  75517. // class C { | static x() { return C_1.y; }
  75518. // static x() { return C.y; } | }
  75519. // static y = 1; | C.y = 1;
  75520. // } | C = C_1 = __decorate([dec], C);
  75521. // | var C_1;
  75522. // ---------------------------------------------------------------------
  75523. // @dec | let C = class C {
  75524. // export class C { | static x() { return C_1.y; }
  75525. // static x() { return C.y; } | }
  75526. // static y = 1; | C.y = 1;
  75527. // } | C = C_1 = __decorate([dec], C);
  75528. // | export { C };
  75529. // | var C_1;
  75530. // ---------------------------------------------------------------------
  75531. //
  75532. // If a class declaration is the default export of a module, we instead emit
  75533. // the export after the decorated declaration:
  75534. //
  75535. // [Example 3]
  75536. // ---------------------------------------------------------------------
  75537. // TypeScript | Javascript
  75538. // ---------------------------------------------------------------------
  75539. // @dec | let default_1 = class {
  75540. // export default class { | }
  75541. // } | default_1 = __decorate([dec], default_1);
  75542. // | export default default_1;
  75543. // ---------------------------------------------------------------------
  75544. // @dec | let C = class C {
  75545. // export default class C { | }
  75546. // } | C = __decorate([dec], C);
  75547. // | export default C;
  75548. // ---------------------------------------------------------------------
  75549. //
  75550. // If the class declaration is the default export and a reference to itself
  75551. // inside of the class body, we must emit both an alias for the class *and*
  75552. // move the export after the declaration:
  75553. //
  75554. // [Example 4]
  75555. // ---------------------------------------------------------------------
  75556. // TypeScript | Javascript
  75557. // ---------------------------------------------------------------------
  75558. // @dec | let C = class C {
  75559. // export default class C { | static x() { return C_1.y; }
  75560. // static x() { return C.y; } | }
  75561. // static y = 1; | C.y = 1;
  75562. // } | C = C_1 = __decorate([dec], C);
  75563. // | export default C;
  75564. // | var C_1;
  75565. // ---------------------------------------------------------------------
  75566. //
  75567. var location = ts.moveRangePastDecorators(node);
  75568. var classAlias = getClassAliasIfNeeded(node);
  75569. var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
  75570. // ... = class ${name} ${heritageClauses} {
  75571. // ${members}
  75572. // }
  75573. var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
  75574. var members = transformClassMembers(node);
  75575. var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
  75576. ts.aggregateTransformFlags(classExpression);
  75577. ts.setOriginalNode(classExpression, node);
  75578. ts.setTextRange(classExpression, location);
  75579. // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
  75580. // or decoratedClassAlias if the class contain self-reference.
  75581. var statement = ts.createVariableStatement(
  75582. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  75583. ts.createVariableDeclaration(declName,
  75584. /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
  75585. ], 1 /* Let */));
  75586. ts.setOriginalNode(statement, node);
  75587. ts.setTextRange(statement, location);
  75588. ts.setCommentRange(statement, node);
  75589. return statement;
  75590. }
  75591. function visitClassExpression(node) {
  75592. if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
  75593. return ts.visitEachChild(node, visitor, context);
  75594. }
  75595. var classExpression = ts.createClassExpression(
  75596. /*modifiers*/ undefined, node.name,
  75597. /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
  75598. ts.aggregateTransformFlags(classExpression);
  75599. ts.setOriginalNode(classExpression, node);
  75600. ts.setTextRange(classExpression, node);
  75601. return classExpression;
  75602. }
  75603. /**
  75604. * Transforms the members of a class.
  75605. *
  75606. * @param node The current class.
  75607. */
  75608. function transformClassMembers(node) {
  75609. var members = [];
  75610. var constructor = ts.getFirstConstructorWithBody(node);
  75611. var parametersWithPropertyAssignments = constructor &&
  75612. ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
  75613. if (parametersWithPropertyAssignments) {
  75614. for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
  75615. var parameter = parametersWithPropertyAssignments_1[_i];
  75616. if (ts.isIdentifier(parameter.name)) {
  75617. members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
  75618. /*decorators*/ undefined,
  75619. /*modifiers*/ undefined, parameter.name,
  75620. /*questionOrExclamationToken*/ undefined,
  75621. /*type*/ undefined,
  75622. /*initializer*/ undefined)), parameter));
  75623. }
  75624. }
  75625. }
  75626. ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
  75627. return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
  75628. }
  75629. /**
  75630. * Gets either the static or instance members of a class that are decorated, or have
  75631. * parameters that are decorated.
  75632. *
  75633. * @param node The class containing the member.
  75634. * @param isStatic A value indicating whether to retrieve static or instance members of
  75635. * the class.
  75636. */
  75637. function getDecoratedClassElements(node, isStatic) {
  75638. return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
  75639. }
  75640. /**
  75641. * Determines whether a class member is a static member of a class that is decorated, or
  75642. * has parameters that are decorated.
  75643. *
  75644. * @param member The class member.
  75645. */
  75646. function isStaticDecoratedClassElement(member, parent) {
  75647. return isDecoratedClassElement(member, /*isStatic*/ true, parent);
  75648. }
  75649. /**
  75650. * Determines whether a class member is an instance member of a class that is decorated,
  75651. * or has parameters that are decorated.
  75652. *
  75653. * @param member The class member.
  75654. */
  75655. function isInstanceDecoratedClassElement(member, parent) {
  75656. return isDecoratedClassElement(member, /*isStatic*/ false, parent);
  75657. }
  75658. /**
  75659. * Determines whether a class member is either a static or an instance member of a class
  75660. * that is decorated, or has parameters that are decorated.
  75661. *
  75662. * @param member The class member.
  75663. */
  75664. function isDecoratedClassElement(member, isStatic, parent) {
  75665. return ts.nodeOrChildIsDecorated(member, parent)
  75666. && isStatic === ts.hasModifier(member, 32 /* Static */);
  75667. }
  75668. /**
  75669. * Gets an array of arrays of decorators for the parameters of a function-like node.
  75670. * The offset into the result array should correspond to the offset of the parameter.
  75671. *
  75672. * @param node The function-like node.
  75673. */
  75674. function getDecoratorsOfParameters(node) {
  75675. var decorators;
  75676. if (node) {
  75677. var parameters = node.parameters;
  75678. var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
  75679. var firstParameterOffset = firstParameterIsThis ? 1 : 0;
  75680. var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
  75681. for (var i = 0; i < numParameters; i++) {
  75682. var parameter = parameters[i + firstParameterOffset];
  75683. if (decorators || parameter.decorators) {
  75684. if (!decorators) {
  75685. decorators = new Array(numParameters);
  75686. }
  75687. decorators[i] = parameter.decorators;
  75688. }
  75689. }
  75690. }
  75691. return decorators;
  75692. }
  75693. /**
  75694. * Gets an AllDecorators object containing the decorators for the class and the decorators for the
  75695. * parameters of the constructor of the class.
  75696. *
  75697. * @param node The class node.
  75698. */
  75699. function getAllDecoratorsOfConstructor(node) {
  75700. var decorators = node.decorators;
  75701. var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
  75702. if (!decorators && !parameters) {
  75703. return undefined;
  75704. }
  75705. return {
  75706. decorators: decorators,
  75707. parameters: parameters
  75708. };
  75709. }
  75710. /**
  75711. * Gets an AllDecorators object containing the decorators for the member and its parameters.
  75712. *
  75713. * @param node The class node that contains the member.
  75714. * @param member The class member.
  75715. */
  75716. function getAllDecoratorsOfClassElement(node, member) {
  75717. switch (member.kind) {
  75718. case 163 /* GetAccessor */:
  75719. case 164 /* SetAccessor */:
  75720. return getAllDecoratorsOfAccessors(node, member);
  75721. case 161 /* MethodDeclaration */:
  75722. return getAllDecoratorsOfMethod(member);
  75723. case 159 /* PropertyDeclaration */:
  75724. return getAllDecoratorsOfProperty(member);
  75725. default:
  75726. return undefined;
  75727. }
  75728. }
  75729. /**
  75730. * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
  75731. *
  75732. * @param node The class node that contains the accessor.
  75733. * @param accessor The class accessor member.
  75734. */
  75735. function getAllDecoratorsOfAccessors(node, accessor) {
  75736. if (!accessor.body) {
  75737. return undefined;
  75738. }
  75739. var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
  75740. var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
  75741. if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
  75742. return undefined;
  75743. }
  75744. var decorators = firstAccessorWithDecorators.decorators;
  75745. var parameters = getDecoratorsOfParameters(setAccessor);
  75746. if (!decorators && !parameters) {
  75747. return undefined;
  75748. }
  75749. return { decorators: decorators, parameters: parameters };
  75750. }
  75751. /**
  75752. * Gets an AllDecorators object containing the decorators for the method and its parameters.
  75753. *
  75754. * @param method The class method member.
  75755. */
  75756. function getAllDecoratorsOfMethod(method) {
  75757. if (!method.body) {
  75758. return undefined;
  75759. }
  75760. var decorators = method.decorators;
  75761. var parameters = getDecoratorsOfParameters(method);
  75762. if (!decorators && !parameters) {
  75763. return undefined;
  75764. }
  75765. return { decorators: decorators, parameters: parameters };
  75766. }
  75767. /**
  75768. * Gets an AllDecorators object containing the decorators for the property.
  75769. *
  75770. * @param property The class property member.
  75771. */
  75772. function getAllDecoratorsOfProperty(property) {
  75773. var decorators = property.decorators;
  75774. if (!decorators) {
  75775. return undefined;
  75776. }
  75777. return { decorators: decorators };
  75778. }
  75779. /**
  75780. * Transforms all of the decorators for a declaration into an array of expressions.
  75781. *
  75782. * @param node The declaration node.
  75783. * @param allDecorators An object containing all of the decorators for the declaration.
  75784. */
  75785. function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
  75786. if (!allDecorators) {
  75787. return undefined;
  75788. }
  75789. var decoratorExpressions = [];
  75790. ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
  75791. ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
  75792. addTypeMetadata(node, container, decoratorExpressions);
  75793. return decoratorExpressions;
  75794. }
  75795. /**
  75796. * Generates statements used to apply decorators to either the static or instance members
  75797. * of a class.
  75798. *
  75799. * @param node The class node.
  75800. * @param isStatic A value indicating whether to generate statements for static or
  75801. * instance members.
  75802. */
  75803. function addClassElementDecorationStatements(statements, node, isStatic) {
  75804. ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
  75805. }
  75806. /**
  75807. * Generates expressions used to apply decorators to either the static or instance members
  75808. * of a class.
  75809. *
  75810. * @param node The class node.
  75811. * @param isStatic A value indicating whether to generate expressions for static or
  75812. * instance members.
  75813. */
  75814. function generateClassElementDecorationExpressions(node, isStatic) {
  75815. var members = getDecoratedClassElements(node, isStatic);
  75816. var expressions;
  75817. for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
  75818. var member = members_6[_i];
  75819. var expression = generateClassElementDecorationExpression(node, member);
  75820. if (expression) {
  75821. if (!expressions) {
  75822. expressions = [expression];
  75823. }
  75824. else {
  75825. expressions.push(expression);
  75826. }
  75827. }
  75828. }
  75829. return expressions;
  75830. }
  75831. /**
  75832. * Generates an expression used to evaluate class element decorators at runtime.
  75833. *
  75834. * @param node The class node that contains the member.
  75835. * @param member The class member.
  75836. */
  75837. function generateClassElementDecorationExpression(node, member) {
  75838. var allDecorators = getAllDecoratorsOfClassElement(node, member);
  75839. var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
  75840. if (!decoratorExpressions) {
  75841. return undefined;
  75842. }
  75843. // Emit the call to __decorate. Given the following:
  75844. //
  75845. // class C {
  75846. // @dec method(@dec2 x) {}
  75847. // @dec get accessor() {}
  75848. // @dec prop;
  75849. // }
  75850. //
  75851. // The emit for a method is:
  75852. //
  75853. // __decorate([
  75854. // dec,
  75855. // __param(0, dec2),
  75856. // __metadata("design:type", Function),
  75857. // __metadata("design:paramtypes", [Object]),
  75858. // __metadata("design:returntype", void 0)
  75859. // ], C.prototype, "method", null);
  75860. //
  75861. // The emit for an accessor is:
  75862. //
  75863. // __decorate([
  75864. // dec
  75865. // ], C.prototype, "accessor", null);
  75866. //
  75867. // The emit for a property is:
  75868. //
  75869. // __decorate([
  75870. // dec
  75871. // ], C.prototype, "prop");
  75872. //
  75873. var prefix = getClassMemberPrefix(node, member);
  75874. var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
  75875. var descriptor = languageVersion > 0 /* ES3 */
  75876. ? member.kind === 159 /* PropertyDeclaration */
  75877. // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
  75878. // should not invoke `Object.getOwnPropertyDescriptor`.
  75879. ? ts.createVoidZero()
  75880. // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
  75881. // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
  75882. : ts.createNull()
  75883. : undefined;
  75884. var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
  75885. ts.setEmitFlags(helper, 1536 /* NoComments */);
  75886. return helper;
  75887. }
  75888. /**
  75889. * Generates a __decorate helper call for a class constructor.
  75890. *
  75891. * @param node The class node.
  75892. */
  75893. function addConstructorDecorationStatement(statements, node) {
  75894. var expression = generateConstructorDecorationExpression(node);
  75895. if (expression) {
  75896. statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
  75897. }
  75898. }
  75899. /**
  75900. * Generates a __decorate helper call for a class constructor.
  75901. *
  75902. * @param node The class node.
  75903. */
  75904. function generateConstructorDecorationExpression(node) {
  75905. var allDecorators = getAllDecoratorsOfConstructor(node);
  75906. var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
  75907. if (!decoratorExpressions) {
  75908. return undefined;
  75909. }
  75910. var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
  75911. var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
  75912. var decorate = createDecorateHelper(context, decoratorExpressions, localName);
  75913. var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
  75914. ts.setEmitFlags(expression, 1536 /* NoComments */);
  75915. ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
  75916. return expression;
  75917. }
  75918. /**
  75919. * Transforms a decorator into an expression.
  75920. *
  75921. * @param decorator The decorator node.
  75922. */
  75923. function transformDecorator(decorator) {
  75924. return ts.visitNode(decorator.expression, visitor, ts.isExpression);
  75925. }
  75926. /**
  75927. * Transforms the decorators of a parameter.
  75928. *
  75929. * @param decorators The decorators for the parameter at the provided offset.
  75930. * @param parameterOffset The offset of the parameter.
  75931. */
  75932. function transformDecoratorsOfParameter(decorators, parameterOffset) {
  75933. var expressions;
  75934. if (decorators) {
  75935. expressions = [];
  75936. for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
  75937. var decorator = decorators_1[_i];
  75938. var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset,
  75939. /*location*/ decorator.expression);
  75940. ts.setEmitFlags(helper, 1536 /* NoComments */);
  75941. expressions.push(helper);
  75942. }
  75943. }
  75944. return expressions;
  75945. }
  75946. /**
  75947. * Adds optional type metadata for a declaration.
  75948. *
  75949. * @param node The declaration node.
  75950. * @param decoratorExpressions The destination array to which to add new decorator expressions.
  75951. */
  75952. function addTypeMetadata(node, container, decoratorExpressions) {
  75953. if (USE_NEW_TYPE_METADATA_FORMAT) {
  75954. addNewTypeMetadata(node, container, decoratorExpressions);
  75955. }
  75956. else {
  75957. addOldTypeMetadata(node, container, decoratorExpressions);
  75958. }
  75959. }
  75960. function addOldTypeMetadata(node, container, decoratorExpressions) {
  75961. if (compilerOptions.emitDecoratorMetadata) {
  75962. if (shouldAddTypeMetadata(node)) {
  75963. decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
  75964. }
  75965. if (shouldAddParamTypesMetadata(node)) {
  75966. decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
  75967. }
  75968. if (shouldAddReturnTypeMetadata(node)) {
  75969. decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
  75970. }
  75971. }
  75972. }
  75973. function addNewTypeMetadata(node, container, decoratorExpressions) {
  75974. if (compilerOptions.emitDecoratorMetadata) {
  75975. var properties = void 0;
  75976. if (shouldAddTypeMetadata(node)) {
  75977. (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
  75978. }
  75979. if (shouldAddParamTypesMetadata(node)) {
  75980. (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
  75981. }
  75982. if (shouldAddReturnTypeMetadata(node)) {
  75983. (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
  75984. }
  75985. if (properties) {
  75986. decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
  75987. }
  75988. }
  75989. }
  75990. /**
  75991. * Determines whether to emit the "design:type" metadata based on the node's kind.
  75992. * The caller should have already tested whether the node has decorators and whether the
  75993. * emitDecoratorMetadata compiler option is set.
  75994. *
  75995. * @param node The node to test.
  75996. */
  75997. function shouldAddTypeMetadata(node) {
  75998. var kind = node.kind;
  75999. return kind === 161 /* MethodDeclaration */
  76000. || kind === 163 /* GetAccessor */
  76001. || kind === 164 /* SetAccessor */
  76002. || kind === 159 /* PropertyDeclaration */;
  76003. }
  76004. /**
  76005. * Determines whether to emit the "design:returntype" metadata based on the node's kind.
  76006. * The caller should have already tested whether the node has decorators and whether the
  76007. * emitDecoratorMetadata compiler option is set.
  76008. *
  76009. * @param node The node to test.
  76010. */
  76011. function shouldAddReturnTypeMetadata(node) {
  76012. return node.kind === 161 /* MethodDeclaration */;
  76013. }
  76014. /**
  76015. * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
  76016. * The caller should have already tested whether the node has decorators and whether the
  76017. * emitDecoratorMetadata compiler option is set.
  76018. *
  76019. * @param node The node to test.
  76020. */
  76021. function shouldAddParamTypesMetadata(node) {
  76022. switch (node.kind) {
  76023. case 245 /* ClassDeclaration */:
  76024. case 214 /* ClassExpression */:
  76025. return ts.getFirstConstructorWithBody(node) !== undefined;
  76026. case 161 /* MethodDeclaration */:
  76027. case 163 /* GetAccessor */:
  76028. case 164 /* SetAccessor */:
  76029. return true;
  76030. }
  76031. return false;
  76032. }
  76033. function getAccessorTypeNode(node) {
  76034. var accessors = resolver.getAllAccessorDeclarations(node);
  76035. return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
  76036. || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
  76037. }
  76038. /**
  76039. * Serializes the type of a node for use with decorator type metadata.
  76040. *
  76041. * @param node The node that should have its type serialized.
  76042. */
  76043. function serializeTypeOfNode(node) {
  76044. switch (node.kind) {
  76045. case 159 /* PropertyDeclaration */:
  76046. case 156 /* Parameter */:
  76047. return serializeTypeNode(node.type);
  76048. case 164 /* SetAccessor */:
  76049. case 163 /* GetAccessor */:
  76050. return serializeTypeNode(getAccessorTypeNode(node));
  76051. case 245 /* ClassDeclaration */:
  76052. case 214 /* ClassExpression */:
  76053. case 161 /* MethodDeclaration */:
  76054. return ts.createIdentifier("Function");
  76055. default:
  76056. return ts.createVoidZero();
  76057. }
  76058. }
  76059. /**
  76060. * Serializes the types of the parameters of a node for use with decorator type metadata.
  76061. *
  76062. * @param node The node that should have its parameter types serialized.
  76063. */
  76064. function serializeParameterTypesOfNode(node, container) {
  76065. var valueDeclaration = ts.isClassLike(node)
  76066. ? ts.getFirstConstructorWithBody(node)
  76067. : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
  76068. ? node
  76069. : undefined;
  76070. var expressions = [];
  76071. if (valueDeclaration) {
  76072. var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
  76073. var numParameters = parameters.length;
  76074. for (var i = 0; i < numParameters; i++) {
  76075. var parameter = parameters[i];
  76076. if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
  76077. continue;
  76078. }
  76079. if (parameter.dotDotDotToken) {
  76080. expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
  76081. }
  76082. else {
  76083. expressions.push(serializeTypeOfNode(parameter));
  76084. }
  76085. }
  76086. }
  76087. return ts.createArrayLiteral(expressions);
  76088. }
  76089. function getParametersOfDecoratedDeclaration(node, container) {
  76090. if (container && node.kind === 163 /* GetAccessor */) {
  76091. var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
  76092. if (setAccessor) {
  76093. return setAccessor.parameters;
  76094. }
  76095. }
  76096. return node.parameters;
  76097. }
  76098. /**
  76099. * Serializes the return type of a node for use with decorator type metadata.
  76100. *
  76101. * @param node The node that should have its return type serialized.
  76102. */
  76103. function serializeReturnTypeOfNode(node) {
  76104. if (ts.isFunctionLike(node) && node.type) {
  76105. return serializeTypeNode(node.type);
  76106. }
  76107. else if (ts.isAsyncFunction(node)) {
  76108. return ts.createIdentifier("Promise");
  76109. }
  76110. return ts.createVoidZero();
  76111. }
  76112. /**
  76113. * Serializes a type node for use with decorator type metadata.
  76114. *
  76115. * Types are serialized in the following fashion:
  76116. * - Void types point to "undefined" (e.g. "void 0")
  76117. * - Function and Constructor types point to the global "Function" constructor.
  76118. * - Interface types with a call or construct signature types point to the global
  76119. * "Function" constructor.
  76120. * - Array and Tuple types point to the global "Array" constructor.
  76121. * - Type predicates and booleans point to the global "Boolean" constructor.
  76122. * - String literal types and strings point to the global "String" constructor.
  76123. * - Enum and number types point to the global "Number" constructor.
  76124. * - Symbol types point to the global "Symbol" constructor.
  76125. * - Type references to classes (or class-like variables) point to the constructor for the class.
  76126. * - Anything else points to the global "Object" constructor.
  76127. *
  76128. * @param node The type node to serialize.
  76129. */
  76130. function serializeTypeNode(node) {
  76131. if (node === undefined) {
  76132. return ts.createIdentifier("Object");
  76133. }
  76134. switch (node.kind) {
  76135. case 110 /* VoidKeyword */:
  76136. case 146 /* UndefinedKeyword */:
  76137. case 100 /* NullKeyword */:
  76138. case 137 /* NeverKeyword */:
  76139. return ts.createVoidZero();
  76140. case 182 /* ParenthesizedType */:
  76141. return serializeTypeNode(node.type);
  76142. case 170 /* FunctionType */:
  76143. case 171 /* ConstructorType */:
  76144. return ts.createIdentifier("Function");
  76145. case 174 /* ArrayType */:
  76146. case 175 /* TupleType */:
  76147. return ts.createIdentifier("Array");
  76148. case 168 /* TypePredicate */:
  76149. case 128 /* BooleanKeyword */:
  76150. return ts.createIdentifier("Boolean");
  76151. case 143 /* StringKeyword */:
  76152. return ts.createIdentifier("String");
  76153. case 141 /* ObjectKeyword */:
  76154. return ts.createIdentifier("Object");
  76155. case 187 /* LiteralType */:
  76156. switch (node.literal.kind) {
  76157. case 10 /* StringLiteral */:
  76158. return ts.createIdentifier("String");
  76159. case 207 /* PrefixUnaryExpression */:
  76160. case 8 /* NumericLiteral */:
  76161. return ts.createIdentifier("Number");
  76162. case 9 /* BigIntLiteral */:
  76163. return getGlobalBigIntNameWithFallback();
  76164. case 106 /* TrueKeyword */:
  76165. case 91 /* FalseKeyword */:
  76166. return ts.createIdentifier("Boolean");
  76167. default:
  76168. return ts.Debug.failBadSyntaxKind(node.literal);
  76169. }
  76170. case 140 /* NumberKeyword */:
  76171. return ts.createIdentifier("Number");
  76172. case 151 /* BigIntKeyword */:
  76173. return getGlobalBigIntNameWithFallback();
  76174. case 144 /* SymbolKeyword */:
  76175. return languageVersion < 2 /* ES2015 */
  76176. ? getGlobalSymbolNameWithFallback()
  76177. : ts.createIdentifier("Symbol");
  76178. case 169 /* TypeReference */:
  76179. return serializeTypeReferenceNode(node);
  76180. case 179 /* IntersectionType */:
  76181. case 178 /* UnionType */:
  76182. return serializeTypeList(node.types);
  76183. case 180 /* ConditionalType */:
  76184. return serializeTypeList([node.trueType, node.falseType]);
  76185. case 184 /* TypeOperator */:
  76186. if (node.operator === 138 /* ReadonlyKeyword */) {
  76187. return serializeTypeNode(node.type);
  76188. }
  76189. break;
  76190. case 172 /* TypeQuery */:
  76191. case 185 /* IndexedAccessType */:
  76192. case 186 /* MappedType */:
  76193. case 173 /* TypeLiteral */:
  76194. case 125 /* AnyKeyword */:
  76195. case 148 /* UnknownKeyword */:
  76196. case 183 /* ThisType */:
  76197. case 188 /* ImportType */:
  76198. break;
  76199. default:
  76200. return ts.Debug.failBadSyntaxKind(node);
  76201. }
  76202. return ts.createIdentifier("Object");
  76203. }
  76204. function serializeTypeList(types) {
  76205. // Note when updating logic here also update getEntityNameForDecoratorMetadata
  76206. // so that aliases can be marked as referenced
  76207. var serializedUnion;
  76208. for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
  76209. var typeNode = types_20[_i];
  76210. while (typeNode.kind === 182 /* ParenthesizedType */) {
  76211. typeNode = typeNode.type; // Skip parens if need be
  76212. }
  76213. if (typeNode.kind === 137 /* NeverKeyword */) {
  76214. continue; // Always elide `never` from the union/intersection if possible
  76215. }
  76216. if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
  76217. continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
  76218. }
  76219. var serializedIndividual = serializeTypeNode(typeNode);
  76220. if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
  76221. // One of the individual is global object, return immediately
  76222. return serializedIndividual;
  76223. }
  76224. // If there exists union that is not void 0 expression, check if the the common type is identifier.
  76225. // anything more complex and we will just default to Object
  76226. else if (serializedUnion) {
  76227. // Different types
  76228. if (!ts.isIdentifier(serializedUnion) ||
  76229. !ts.isIdentifier(serializedIndividual) ||
  76230. serializedUnion.escapedText !== serializedIndividual.escapedText) {
  76231. return ts.createIdentifier("Object");
  76232. }
  76233. }
  76234. else {
  76235. // Initialize the union type
  76236. serializedUnion = serializedIndividual;
  76237. }
  76238. }
  76239. // If we were able to find common type, use it
  76240. return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
  76241. }
  76242. /**
  76243. * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
  76244. * decorator type metadata.
  76245. *
  76246. * @param node The type reference node.
  76247. */
  76248. function serializeTypeReferenceNode(node) {
  76249. var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
  76250. switch (kind) {
  76251. case ts.TypeReferenceSerializationKind.Unknown:
  76252. // From conditional type type reference that cannot be resolved is Similar to any or unknown
  76253. if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
  76254. return ts.createIdentifier("Object");
  76255. }
  76256. var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
  76257. var temp = ts.createTempVariable(hoistVariableDeclaration);
  76258. return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
  76259. case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
  76260. return serializeEntityNameAsExpression(node.typeName);
  76261. case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
  76262. return ts.createVoidZero();
  76263. case ts.TypeReferenceSerializationKind.BigIntLikeType:
  76264. return getGlobalBigIntNameWithFallback();
  76265. case ts.TypeReferenceSerializationKind.BooleanType:
  76266. return ts.createIdentifier("Boolean");
  76267. case ts.TypeReferenceSerializationKind.NumberLikeType:
  76268. return ts.createIdentifier("Number");
  76269. case ts.TypeReferenceSerializationKind.StringLikeType:
  76270. return ts.createIdentifier("String");
  76271. case ts.TypeReferenceSerializationKind.ArrayLikeType:
  76272. return ts.createIdentifier("Array");
  76273. case ts.TypeReferenceSerializationKind.ESSymbolType:
  76274. return languageVersion < 2 /* ES2015 */
  76275. ? getGlobalSymbolNameWithFallback()
  76276. : ts.createIdentifier("Symbol");
  76277. case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
  76278. return ts.createIdentifier("Function");
  76279. case ts.TypeReferenceSerializationKind.Promise:
  76280. return ts.createIdentifier("Promise");
  76281. case ts.TypeReferenceSerializationKind.ObjectType:
  76282. return ts.createIdentifier("Object");
  76283. default:
  76284. return ts.Debug.assertNever(kind);
  76285. }
  76286. }
  76287. function createCheckedValue(left, right) {
  76288. return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
  76289. }
  76290. /**
  76291. * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
  76292. *
  76293. * @param node The entity name to serialize.
  76294. */
  76295. function serializeEntityNameAsExpressionFallback(node) {
  76296. if (node.kind === 75 /* Identifier */) {
  76297. // A -> typeof A !== undefined && A
  76298. var copied = serializeEntityNameAsExpression(node);
  76299. return createCheckedValue(copied, copied);
  76300. }
  76301. if (node.left.kind === 75 /* Identifier */) {
  76302. // A.B -> typeof A !== undefined && A.B
  76303. return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
  76304. }
  76305. // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
  76306. var left = serializeEntityNameAsExpressionFallback(node.left);
  76307. var temp = ts.createTempVariable(hoistVariableDeclaration);
  76308. return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
  76309. }
  76310. /**
  76311. * Serializes an entity name as an expression for decorator type metadata.
  76312. *
  76313. * @param node The entity name to serialize.
  76314. */
  76315. function serializeEntityNameAsExpression(node) {
  76316. switch (node.kind) {
  76317. case 75 /* Identifier */:
  76318. // Create a clone of the name with a new parent, and treat it as if it were
  76319. // a source tree node for the purposes of the checker.
  76320. var name = ts.getMutableClone(node);
  76321. name.flags &= ~8 /* Synthesized */;
  76322. name.original = undefined;
  76323. name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
  76324. return name;
  76325. case 153 /* QualifiedName */:
  76326. return serializeQualifiedNameAsExpression(node);
  76327. }
  76328. }
  76329. /**
  76330. * Serializes an qualified name as an expression for decorator type metadata.
  76331. *
  76332. * @param node The qualified name to serialize.
  76333. * @param useFallback A value indicating whether to use logical operators to test for the
  76334. * qualified name at runtime.
  76335. */
  76336. function serializeQualifiedNameAsExpression(node) {
  76337. return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
  76338. }
  76339. /**
  76340. * Gets an expression that points to the global "Symbol" constructor at runtime if it is
  76341. * available.
  76342. */
  76343. function getGlobalSymbolNameWithFallback() {
  76344. return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
  76345. }
  76346. /**
  76347. * Gets an expression that points to the global "BigInt" constructor at runtime if it is
  76348. * available.
  76349. */
  76350. function getGlobalBigIntNameWithFallback() {
  76351. return languageVersion < 99 /* ESNext */
  76352. ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
  76353. : ts.createIdentifier("BigInt");
  76354. }
  76355. /**
  76356. * Gets an expression that represents a property name (for decorated properties or enums).
  76357. * For a computed property, a name is generated for the node.
  76358. *
  76359. * @param member The member whose name should be converted into an expression.
  76360. */
  76361. function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
  76362. var name = member.name;
  76363. if (ts.isPrivateIdentifier(name)) {
  76364. return ts.createIdentifier("");
  76365. }
  76366. else if (ts.isComputedPropertyName(name)) {
  76367. return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
  76368. ? ts.getGeneratedNameForNode(name)
  76369. : name.expression;
  76370. }
  76371. else if (ts.isIdentifier(name)) {
  76372. return ts.createLiteral(ts.idText(name));
  76373. }
  76374. else {
  76375. return ts.getSynthesizedClone(name);
  76376. }
  76377. }
  76378. /**
  76379. * Visits the property name of a class element, for use when emitting property
  76380. * initializers. For a computed property on a node with decorators, a temporary
  76381. * value is stored for later use.
  76382. *
  76383. * @param member The member whose name should be visited.
  76384. */
  76385. function visitPropertyNameOfClassElement(member) {
  76386. var name = member.name;
  76387. // Computed property names need to be transformed into a hoisted variable when they are used more than once.
  76388. // The names are used more than once when:
  76389. // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
  76390. // - the property has a decorator.
  76391. if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
  76392. var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
  76393. var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
  76394. if (!ts.isSimpleInlineableExpression(innerExpression)) {
  76395. var generatedName = ts.getGeneratedNameForNode(name);
  76396. hoistVariableDeclaration(generatedName);
  76397. return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
  76398. }
  76399. }
  76400. return ts.visitNode(name, visitor, ts.isPropertyName);
  76401. }
  76402. /**
  76403. * Transforms a HeritageClause with TypeScript syntax.
  76404. *
  76405. * This function will only be called when one of the following conditions are met:
  76406. * - The node is a non-`extends` heritage clause that should be elided.
  76407. * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
  76408. *
  76409. * @param node The HeritageClause to transform.
  76410. */
  76411. function visitHeritageClause(node) {
  76412. if (node.token === 113 /* ImplementsKeyword */) {
  76413. // implements clauses are elided
  76414. return undefined;
  76415. }
  76416. return ts.visitEachChild(node, visitor, context);
  76417. }
  76418. /**
  76419. * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
  76420. *
  76421. * This function will only be called when one of the following conditions are met:
  76422. * - The node contains type arguments that should be elided.
  76423. *
  76424. * @param node The ExpressionWithTypeArguments to transform.
  76425. */
  76426. function visitExpressionWithTypeArguments(node) {
  76427. return ts.updateExpressionWithTypeArguments(node,
  76428. /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
  76429. }
  76430. /**
  76431. * Determines whether to emit a function-like declaration. We should not emit the
  76432. * declaration if it does not have a body.
  76433. *
  76434. * @param node The declaration node.
  76435. */
  76436. function shouldEmitFunctionLikeDeclaration(node) {
  76437. return !ts.nodeIsMissing(node.body);
  76438. }
  76439. function visitPropertyDeclaration(node) {
  76440. if (node.flags & 8388608 /* Ambient */) {
  76441. return undefined;
  76442. }
  76443. var updated = ts.updateProperty(node,
  76444. /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node),
  76445. /*questionOrExclamationToken*/ undefined,
  76446. /*type*/ undefined, ts.visitNode(node.initializer, visitor));
  76447. if (updated !== node) {
  76448. // While we emit the source map for the node after skipping decorators and modifiers,
  76449. // we need to emit the comments for the original range.
  76450. ts.setCommentRange(updated, node);
  76451. ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
  76452. }
  76453. return updated;
  76454. }
  76455. function visitConstructor(node) {
  76456. if (!shouldEmitFunctionLikeDeclaration(node)) {
  76457. return undefined;
  76458. }
  76459. return ts.updateConstructor(node,
  76460. /*decorators*/ undefined,
  76461. /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
  76462. }
  76463. function transformConstructorBody(body, constructor) {
  76464. var parametersWithPropertyAssignments = constructor &&
  76465. ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
  76466. if (!ts.some(parametersWithPropertyAssignments)) {
  76467. return ts.visitFunctionBody(body, visitor, context);
  76468. }
  76469. var statements = [];
  76470. var indexOfFirstStatement = 0;
  76471. resumeLexicalEnvironment();
  76472. indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
  76473. // Add parameters with property assignments. Transforms this:
  76474. //
  76475. // constructor (public x, public y) {
  76476. // }
  76477. //
  76478. // Into this:
  76479. //
  76480. // constructor (x, y) {
  76481. // this.x = x;
  76482. // this.y = y;
  76483. // }
  76484. //
  76485. ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
  76486. // Add the existing statements, skipping the initial super call.
  76487. ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
  76488. // End the lexical environment.
  76489. statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
  76490. var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
  76491. ts.setTextRange(block, /*location*/ body);
  76492. ts.setOriginalNode(block, body);
  76493. return block;
  76494. }
  76495. /**
  76496. * Transforms a parameter into a property assignment statement.
  76497. *
  76498. * @param node The parameter declaration.
  76499. */
  76500. function transformParameterWithPropertyAssignment(node) {
  76501. var name = node.name;
  76502. if (!ts.isIdentifier(name)) {
  76503. return undefined;
  76504. }
  76505. var propertyName = ts.getMutableClone(name);
  76506. ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
  76507. var localName = ts.getMutableClone(name);
  76508. ts.setEmitFlags(localName, 1536 /* NoComments */);
  76509. return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1))));
  76510. }
  76511. function visitMethodDeclaration(node) {
  76512. if (!shouldEmitFunctionLikeDeclaration(node)) {
  76513. return undefined;
  76514. }
  76515. var updated = ts.updateMethod(node,
  76516. /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node),
  76517. /*questionToken*/ undefined,
  76518. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  76519. /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
  76520. if (updated !== node) {
  76521. // While we emit the source map for the node after skipping decorators and modifiers,
  76522. // we need to emit the comments for the original range.
  76523. ts.setCommentRange(updated, node);
  76524. ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
  76525. }
  76526. return updated;
  76527. }
  76528. /**
  76529. * Determines whether to emit an accessor declaration. We should not emit the
  76530. * declaration if it does not have a body and is abstract.
  76531. *
  76532. * @param node The declaration node.
  76533. */
  76534. function shouldEmitAccessorDeclaration(node) {
  76535. return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
  76536. }
  76537. function visitGetAccessor(node) {
  76538. if (!shouldEmitAccessorDeclaration(node)) {
  76539. return undefined;
  76540. }
  76541. var updated = ts.updateGetAccessor(node,
  76542. /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context),
  76543. /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
  76544. if (updated !== node) {
  76545. // While we emit the source map for the node after skipping decorators and modifiers,
  76546. // we need to emit the comments for the original range.
  76547. ts.setCommentRange(updated, node);
  76548. ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
  76549. }
  76550. return updated;
  76551. }
  76552. function visitSetAccessor(node) {
  76553. if (!shouldEmitAccessorDeclaration(node)) {
  76554. return undefined;
  76555. }
  76556. var updated = ts.updateSetAccessor(node,
  76557. /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
  76558. if (updated !== node) {
  76559. // While we emit the source map for the node after skipping decorators and modifiers,
  76560. // we need to emit the comments for the original range.
  76561. ts.setCommentRange(updated, node);
  76562. ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
  76563. }
  76564. return updated;
  76565. }
  76566. function visitFunctionDeclaration(node) {
  76567. if (!shouldEmitFunctionLikeDeclaration(node)) {
  76568. return ts.createNotEmittedStatement(node);
  76569. }
  76570. var updated = ts.updateFunctionDeclaration(node,
  76571. /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
  76572. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  76573. /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
  76574. if (isExportOfNamespace(node)) {
  76575. var statements = [updated];
  76576. addExportMemberAssignment(statements, node);
  76577. return statements;
  76578. }
  76579. return updated;
  76580. }
  76581. function visitFunctionExpression(node) {
  76582. if (!shouldEmitFunctionLikeDeclaration(node)) {
  76583. return ts.createOmittedExpression();
  76584. }
  76585. var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
  76586. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  76587. /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
  76588. return updated;
  76589. }
  76590. function visitArrowFunction(node) {
  76591. var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
  76592. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  76593. /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
  76594. return updated;
  76595. }
  76596. function visitParameter(node) {
  76597. if (ts.parameterIsThisKeyword(node)) {
  76598. return undefined;
  76599. }
  76600. var updated = ts.updateParameter(node,
  76601. /*decorators*/ undefined,
  76602. /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
  76603. /*questionToken*/ undefined,
  76604. /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
  76605. if (updated !== node) {
  76606. // While we emit the source map for the node after skipping decorators and modifiers,
  76607. // we need to emit the comments for the original range.
  76608. ts.setCommentRange(updated, node);
  76609. ts.setTextRange(updated, ts.moveRangePastModifiers(node));
  76610. ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
  76611. ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
  76612. }
  76613. return updated;
  76614. }
  76615. function visitVariableStatement(node) {
  76616. if (isExportOfNamespace(node)) {
  76617. var variables = ts.getInitializedVariables(node.declarationList);
  76618. if (variables.length === 0) {
  76619. // elide statement if there are no initialized variables.
  76620. return undefined;
  76621. }
  76622. return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
  76623. }
  76624. else {
  76625. return ts.visitEachChild(node, visitor, context);
  76626. }
  76627. }
  76628. function transformInitializedVariable(node) {
  76629. var name = node.name;
  76630. if (ts.isBindingPattern(name)) {
  76631. return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */,
  76632. /*needsValue*/ false, createNamespaceExportExpression);
  76633. }
  76634. else {
  76635. return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)),
  76636. /*location*/ node);
  76637. }
  76638. }
  76639. function visitVariableDeclaration(node) {
  76640. return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
  76641. /*exclaimationToken*/ undefined,
  76642. /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
  76643. }
  76644. function visitParenthesizedExpression(node) {
  76645. var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
  76646. if (ts.isAssertionExpression(innerExpression)) {
  76647. // Make sure we consider all nested cast expressions, e.g.:
  76648. // (<any><number><any>-A).x;
  76649. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  76650. // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
  76651. // is really not desirable. We would like to emit the subexpression as-is. Omitting
  76652. // the parentheses, however, could cause change in the semantics of the generated
  76653. // code if the casted expression has a lower precedence than the rest of the
  76654. // expression.
  76655. //
  76656. // To preserve comments, we return a "PartiallyEmittedExpression" here which will
  76657. // preserve the position information of the original expression.
  76658. //
  76659. // Due to the auto-parenthesization rules used by the visitor and factory functions
  76660. // we can safely elide the parentheses here, as a new synthetic
  76661. // ParenthesizedExpression will be inserted if we remove parentheses too
  76662. // aggressively.
  76663. // HOWEVER - if there are leading comments on the expression itself, to handle ASI
  76664. // correctly for return and throw, we must keep the parenthesis
  76665. if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
  76666. return ts.updateParen(node, expression);
  76667. }
  76668. return ts.createPartiallyEmittedExpression(expression, node);
  76669. }
  76670. return ts.visitEachChild(node, visitor, context);
  76671. }
  76672. function visitAssertionExpression(node) {
  76673. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  76674. return ts.createPartiallyEmittedExpression(expression, node);
  76675. }
  76676. function visitNonNullExpression(node) {
  76677. var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
  76678. return ts.createPartiallyEmittedExpression(expression, node);
  76679. }
  76680. function visitCallExpression(node) {
  76681. return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression),
  76682. /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
  76683. }
  76684. function visitNewExpression(node) {
  76685. return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression),
  76686. /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
  76687. }
  76688. function visitTaggedTemplateExpression(node) {
  76689. return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression),
  76690. /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
  76691. }
  76692. /**
  76693. * Determines whether to emit an enum declaration.
  76694. *
  76695. * @param node The enum declaration node.
  76696. */
  76697. function shouldEmitEnumDeclaration(node) {
  76698. return !ts.isEnumConst(node)
  76699. || compilerOptions.preserveConstEnums
  76700. || compilerOptions.isolatedModules;
  76701. }
  76702. /**
  76703. * Visits an enum declaration.
  76704. *
  76705. * This function will be called any time a TypeScript enum is encountered.
  76706. *
  76707. * @param node The enum declaration node.
  76708. */
  76709. function visitEnumDeclaration(node) {
  76710. if (!shouldEmitEnumDeclaration(node)) {
  76711. return ts.createNotEmittedStatement(node);
  76712. }
  76713. var statements = [];
  76714. // We request to be advised when the printer is about to print this node. This allows
  76715. // us to set up the correct state for later substitutions.
  76716. var emitFlags = 2 /* AdviseOnEmitNode */;
  76717. // If needed, we should emit a variable declaration for the enum. If we emit
  76718. // a leading variable declaration, we should not emit leading comments for the
  76719. // enum body.
  76720. var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
  76721. if (varAdded) {
  76722. // We should still emit the comments if we are emitting a system module.
  76723. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
  76724. emitFlags |= 512 /* NoLeadingComments */;
  76725. }
  76726. }
  76727. // `parameterName` is the declaration name used inside of the enum.
  76728. var parameterName = getNamespaceParameterName(node);
  76729. // `containerName` is the expression used inside of the enum for assignments.
  76730. var containerName = getNamespaceContainerName(node);
  76731. // `exportName` is the expression used within this node's container for any exported references.
  76732. var exportName = ts.hasModifier(node, 1 /* Export */)
  76733. ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
  76734. : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
  76735. // x || (x = {})
  76736. // exports.x || (exports.x = {})
  76737. var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
  76738. if (hasNamespaceQualifiedExportName(node)) {
  76739. // `localName` is the expression used within this node's containing scope for any local references.
  76740. var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
  76741. // x = (exports.x || (exports.x = {}))
  76742. moduleArg = ts.createAssignment(localName, moduleArg);
  76743. }
  76744. // (function (x) {
  76745. // x[x["y"] = 0] = "y";
  76746. // ...
  76747. // })(x || (x = {}));
  76748. var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
  76749. /*modifiers*/ undefined,
  76750. /*asteriskToken*/ undefined,
  76751. /*name*/ undefined,
  76752. /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
  76753. /*type*/ undefined, transformEnumBody(node, containerName)),
  76754. /*typeArguments*/ undefined, [moduleArg]));
  76755. ts.setOriginalNode(enumStatement, node);
  76756. if (varAdded) {
  76757. // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
  76758. ts.setSyntheticLeadingComments(enumStatement, undefined);
  76759. ts.setSyntheticTrailingComments(enumStatement, undefined);
  76760. }
  76761. ts.setTextRange(enumStatement, node);
  76762. ts.addEmitFlags(enumStatement, emitFlags);
  76763. statements.push(enumStatement);
  76764. // Add a DeclarationMarker for the enum to preserve trailing comments and mark
  76765. // the end of the declaration.
  76766. statements.push(ts.createEndOfDeclarationMarker(node));
  76767. return statements;
  76768. }
  76769. /**
  76770. * Transforms the body of an enum declaration.
  76771. *
  76772. * @param node The enum declaration node.
  76773. */
  76774. function transformEnumBody(node, localName) {
  76775. var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
  76776. currentNamespaceContainerName = localName;
  76777. var statements = [];
  76778. startLexicalEnvironment();
  76779. var members = ts.map(node.members, transformEnumMember);
  76780. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  76781. ts.addRange(statements, members);
  76782. currentNamespaceContainerName = savedCurrentNamespaceLocalName;
  76783. return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
  76784. /*multiLine*/ true);
  76785. }
  76786. /**
  76787. * Transforms an enum member into a statement.
  76788. *
  76789. * @param member The enum member node.
  76790. */
  76791. function transformEnumMember(member) {
  76792. // enums don't support computed properties
  76793. // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
  76794. // old emitter always generate 'expression' part of the name as-is.
  76795. var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
  76796. var valueExpression = transformEnumMemberDeclarationValue(member);
  76797. var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
  76798. var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
  76799. innerAssignment :
  76800. ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
  76801. return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
  76802. }
  76803. /**
  76804. * Transforms the value of an enum member.
  76805. *
  76806. * @param member The enum member node.
  76807. */
  76808. function transformEnumMemberDeclarationValue(member) {
  76809. var value = resolver.getConstantValue(member);
  76810. if (value !== undefined) {
  76811. return ts.createLiteral(value);
  76812. }
  76813. else {
  76814. enableSubstitutionForNonQualifiedEnumMembers();
  76815. if (member.initializer) {
  76816. return ts.visitNode(member.initializer, visitor, ts.isExpression);
  76817. }
  76818. else {
  76819. return ts.createVoidZero();
  76820. }
  76821. }
  76822. }
  76823. /**
  76824. * Determines whether to elide a module declaration.
  76825. *
  76826. * @param node The module declaration node.
  76827. */
  76828. function shouldEmitModuleDeclaration(nodeIn) {
  76829. var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
  76830. if (!node) {
  76831. // If we can't find a parse tree node, assume the node is instantiated.
  76832. return true;
  76833. }
  76834. return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
  76835. }
  76836. /**
  76837. * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
  76838. * or `exports.x`).
  76839. */
  76840. function hasNamespaceQualifiedExportName(node) {
  76841. return isExportOfNamespace(node)
  76842. || (isExternalModuleExport(node)
  76843. && moduleKind !== ts.ModuleKind.ES2015
  76844. && moduleKind !== ts.ModuleKind.ES2020
  76845. && moduleKind !== ts.ModuleKind.ESNext
  76846. && moduleKind !== ts.ModuleKind.System);
  76847. }
  76848. /**
  76849. * Records that a declaration was emitted in the current scope, if it was the first
  76850. * declaration for the provided symbol.
  76851. */
  76852. function recordEmittedDeclarationInScope(node) {
  76853. if (!currentScopeFirstDeclarationsOfName) {
  76854. currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
  76855. }
  76856. var name = declaredNameInScope(node);
  76857. if (!currentScopeFirstDeclarationsOfName.has(name)) {
  76858. currentScopeFirstDeclarationsOfName.set(name, node);
  76859. }
  76860. }
  76861. /**
  76862. * Determines whether a declaration is the first declaration with
  76863. * the same name emitted in the current scope.
  76864. */
  76865. function isFirstEmittedDeclarationInScope(node) {
  76866. if (currentScopeFirstDeclarationsOfName) {
  76867. var name = declaredNameInScope(node);
  76868. return currentScopeFirstDeclarationsOfName.get(name) === node;
  76869. }
  76870. return true;
  76871. }
  76872. function declaredNameInScope(node) {
  76873. ts.Debug.assertNode(node.name, ts.isIdentifier);
  76874. return node.name.escapedText;
  76875. }
  76876. /**
  76877. * Adds a leading VariableStatement for a enum or module declaration.
  76878. */
  76879. function addVarForEnumOrModuleDeclaration(statements, node) {
  76880. // Emit a variable statement for the module. We emit top-level enums as a `var`
  76881. // declaration to avoid static errors in global scripts scripts due to redeclaration.
  76882. // enums in any other scope are emitted as a `let` declaration.
  76883. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
  76884. ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
  76885. ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
  76886. ts.setOriginalNode(statement, node);
  76887. recordEmittedDeclarationInScope(node);
  76888. if (isFirstEmittedDeclarationInScope(node)) {
  76889. // Adjust the source map emit to match the old emitter.
  76890. if (node.kind === 248 /* EnumDeclaration */) {
  76891. ts.setSourceMapRange(statement.declarationList, node);
  76892. }
  76893. else {
  76894. ts.setSourceMapRange(statement, node);
  76895. }
  76896. // Trailing comments for module declaration should be emitted after the function closure
  76897. // instead of the variable statement:
  76898. //
  76899. // /** Module comment*/
  76900. // module m1 {
  76901. // function foo4Export() {
  76902. // }
  76903. // } // trailing comment module
  76904. //
  76905. // Should emit:
  76906. //
  76907. // /** Module comment*/
  76908. // var m1;
  76909. // (function (m1) {
  76910. // function foo4Export() {
  76911. // }
  76912. // })(m1 || (m1 = {})); // trailing comment module
  76913. //
  76914. ts.setCommentRange(statement, node);
  76915. ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
  76916. statements.push(statement);
  76917. return true;
  76918. }
  76919. else {
  76920. // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
  76921. // declaration we do not emit a leading variable declaration. To preserve the
  76922. // begin/end semantics of the declararation and to properly handle exports
  76923. // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
  76924. var mergeMarker = ts.createMergeDeclarationMarker(statement);
  76925. ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
  76926. statements.push(mergeMarker);
  76927. return false;
  76928. }
  76929. }
  76930. /**
  76931. * Visits a module declaration node.
  76932. *
  76933. * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
  76934. *
  76935. * @param node The module declaration node.
  76936. */
  76937. function visitModuleDeclaration(node) {
  76938. if (!shouldEmitModuleDeclaration(node)) {
  76939. return ts.createNotEmittedStatement(node);
  76940. }
  76941. ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
  76942. enableSubstitutionForNamespaceExports();
  76943. var statements = [];
  76944. // We request to be advised when the printer is about to print this node. This allows
  76945. // us to set up the correct state for later substitutions.
  76946. var emitFlags = 2 /* AdviseOnEmitNode */;
  76947. // If needed, we should emit a variable declaration for the module. If we emit
  76948. // a leading variable declaration, we should not emit leading comments for the
  76949. // module body.
  76950. var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
  76951. if (varAdded) {
  76952. // We should still emit the comments if we are emitting a system module.
  76953. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
  76954. emitFlags |= 512 /* NoLeadingComments */;
  76955. }
  76956. }
  76957. // `parameterName` is the declaration name used inside of the namespace.
  76958. var parameterName = getNamespaceParameterName(node);
  76959. // `containerName` is the expression used inside of the namespace for exports.
  76960. var containerName = getNamespaceContainerName(node);
  76961. // `exportName` is the expression used within this node's container for any exported references.
  76962. var exportName = ts.hasModifier(node, 1 /* Export */)
  76963. ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
  76964. : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
  76965. // x || (x = {})
  76966. // exports.x || (exports.x = {})
  76967. var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
  76968. if (hasNamespaceQualifiedExportName(node)) {
  76969. // `localName` is the expression used within this node's containing scope for any local references.
  76970. var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
  76971. // x = (exports.x || (exports.x = {}))
  76972. moduleArg = ts.createAssignment(localName, moduleArg);
  76973. }
  76974. // (function (x_1) {
  76975. // x_1.y = ...;
  76976. // })(x || (x = {}));
  76977. var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
  76978. /*modifiers*/ undefined,
  76979. /*asteriskToken*/ undefined,
  76980. /*name*/ undefined,
  76981. /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
  76982. /*type*/ undefined, transformModuleBody(node, containerName)),
  76983. /*typeArguments*/ undefined, [moduleArg]));
  76984. ts.setOriginalNode(moduleStatement, node);
  76985. if (varAdded) {
  76986. // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
  76987. ts.setSyntheticLeadingComments(moduleStatement, undefined);
  76988. ts.setSyntheticTrailingComments(moduleStatement, undefined);
  76989. }
  76990. ts.setTextRange(moduleStatement, node);
  76991. ts.addEmitFlags(moduleStatement, emitFlags);
  76992. statements.push(moduleStatement);
  76993. // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
  76994. // the end of the declaration.
  76995. statements.push(ts.createEndOfDeclarationMarker(node));
  76996. return statements;
  76997. }
  76998. /**
  76999. * Transforms the body of a module declaration.
  77000. *
  77001. * @param node The module declaration node.
  77002. */
  77003. function transformModuleBody(node, namespaceLocalName) {
  77004. var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
  77005. var savedCurrentNamespace = currentNamespace;
  77006. var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
  77007. currentNamespaceContainerName = namespaceLocalName;
  77008. currentNamespace = node;
  77009. currentScopeFirstDeclarationsOfName = undefined;
  77010. var statements = [];
  77011. startLexicalEnvironment();
  77012. var statementsLocation;
  77013. var blockLocation;
  77014. var body = node.body;
  77015. if (body.kind === 250 /* ModuleBlock */) {
  77016. saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
  77017. statementsLocation = body.statements;
  77018. blockLocation = body;
  77019. }
  77020. else {
  77021. var result = visitModuleDeclaration(body);
  77022. if (result) {
  77023. if (ts.isArray(result)) {
  77024. ts.addRange(statements, result);
  77025. }
  77026. else {
  77027. statements.push(result);
  77028. }
  77029. }
  77030. var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
  77031. statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
  77032. }
  77033. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  77034. currentNamespaceContainerName = savedCurrentNamespaceContainerName;
  77035. currentNamespace = savedCurrentNamespace;
  77036. currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
  77037. var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
  77038. /*location*/ statementsLocation),
  77039. /*multiLine*/ true);
  77040. ts.setTextRange(block, blockLocation);
  77041. // namespace hello.hi.world {
  77042. // function foo() {}
  77043. //
  77044. // // TODO, blah
  77045. // }
  77046. //
  77047. // should be emitted as
  77048. //
  77049. // var hello;
  77050. // (function (hello) {
  77051. // var hi;
  77052. // (function (hi) {
  77053. // var world;
  77054. // (function (world) {
  77055. // function foo() { }
  77056. // // TODO, blah
  77057. // })(world = hi.world || (hi.world = {}));
  77058. // })(hi = hello.hi || (hello.hi = {}));
  77059. // })(hello || (hello = {}));
  77060. // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
  77061. if (body.kind !== 250 /* ModuleBlock */) {
  77062. ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
  77063. }
  77064. return block;
  77065. }
  77066. function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
  77067. if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
  77068. var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
  77069. return recursiveInnerModule || moduleDeclaration.body;
  77070. }
  77071. }
  77072. /**
  77073. * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
  77074. *
  77075. * @param node The import declaration node.
  77076. */
  77077. function visitImportDeclaration(node) {
  77078. if (!node.importClause) {
  77079. // Do not elide a side-effect only import declaration.
  77080. // import "foo";
  77081. return node;
  77082. }
  77083. if (node.importClause.isTypeOnly) {
  77084. // Always elide type-only imports
  77085. return undefined;
  77086. }
  77087. // Elide the declaration if the import clause was elided.
  77088. var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
  77089. return importClause ||
  77090. compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
  77091. compilerOptions.importsNotUsedAsValues === 2 /* Error */
  77092. ? ts.updateImportDeclaration(node,
  77093. /*decorators*/ undefined,
  77094. /*modifiers*/ undefined, importClause, node.moduleSpecifier)
  77095. : undefined;
  77096. }
  77097. /**
  77098. * Visits an import clause, eliding it if it is not referenced.
  77099. *
  77100. * @param node The import clause node.
  77101. */
  77102. function visitImportClause(node) {
  77103. if (node.isTypeOnly) {
  77104. return undefined;
  77105. }
  77106. // Elide the import clause if we elide both its name and its named bindings.
  77107. var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
  77108. var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
  77109. return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
  77110. }
  77111. /**
  77112. * Visits named import bindings, eliding it if it is not referenced.
  77113. *
  77114. * @param node The named import bindings node.
  77115. */
  77116. function visitNamedImportBindings(node) {
  77117. if (node.kind === 256 /* NamespaceImport */) {
  77118. // Elide a namespace import if it is not referenced.
  77119. return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
  77120. }
  77121. else {
  77122. // Elide named imports if all of its import specifiers are elided.
  77123. var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
  77124. return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
  77125. }
  77126. }
  77127. /**
  77128. * Visits an import specifier, eliding it if it is not referenced.
  77129. *
  77130. * @param node The import specifier node.
  77131. */
  77132. function visitImportSpecifier(node) {
  77133. // Elide an import specifier if it is not referenced.
  77134. return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
  77135. }
  77136. /**
  77137. * Visits an export assignment, eliding it if it does not contain a clause that resolves
  77138. * to a value.
  77139. *
  77140. * @param node The export assignment node.
  77141. */
  77142. function visitExportAssignment(node) {
  77143. // Elide the export assignment if it does not reference a value.
  77144. return resolver.isValueAliasDeclaration(node)
  77145. ? ts.visitEachChild(node, visitor, context)
  77146. : undefined;
  77147. }
  77148. /**
  77149. * Visits an export declaration, eliding it if it does not contain a clause that resolves
  77150. * to a value.
  77151. *
  77152. * @param node The export declaration node.
  77153. */
  77154. function visitExportDeclaration(node) {
  77155. if (node.isTypeOnly) {
  77156. return undefined;
  77157. }
  77158. if (!node.exportClause) {
  77159. // Elide a star export if the module it references does not export a value.
  77160. return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
  77161. }
  77162. if (!resolver.isValueAliasDeclaration(node)) {
  77163. // Elide the export declaration if it does not export a value.
  77164. return undefined;
  77165. }
  77166. // Elide the export declaration if all of its named exports are elided.
  77167. var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedImportBindings);
  77168. return exportClause
  77169. ? ts.updateExportDeclaration(node,
  77170. /*decorators*/ undefined,
  77171. /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
  77172. : undefined;
  77173. }
  77174. /**
  77175. * Visits named exports, eliding it if it does not contain an export specifier that
  77176. * resolves to a value.
  77177. *
  77178. * @param node The named exports node.
  77179. */
  77180. function visitNamedExports(node) {
  77181. // Elide the named exports if all of its export specifiers were elided.
  77182. var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
  77183. return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
  77184. }
  77185. function visitNamespaceExports(node) {
  77186. return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
  77187. }
  77188. function visitNamedExportBindings(node) {
  77189. return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
  77190. }
  77191. /**
  77192. * Visits an export specifier, eliding it if it does not resolve to a value.
  77193. *
  77194. * @param node The export specifier node.
  77195. */
  77196. function visitExportSpecifier(node) {
  77197. // Elide an export specifier if it does not reference a value.
  77198. return resolver.isValueAliasDeclaration(node) ? node : undefined;
  77199. }
  77200. /**
  77201. * Determines whether to emit an import equals declaration.
  77202. *
  77203. * @param node The import equals declaration node.
  77204. */
  77205. function shouldEmitImportEqualsDeclaration(node) {
  77206. // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
  77207. // - current file is not external module
  77208. // - import declaration is top level and target is value imported by entity name
  77209. return resolver.isReferencedAliasDeclaration(node)
  77210. || (!ts.isExternalModule(currentSourceFile)
  77211. && resolver.isTopLevelValueImportEqualsWithEntityName(node));
  77212. }
  77213. /**
  77214. * Visits an import equals declaration.
  77215. *
  77216. * @param node The import equals declaration node.
  77217. */
  77218. function visitImportEqualsDeclaration(node) {
  77219. if (ts.isExternalModuleImportEqualsDeclaration(node)) {
  77220. var isReferenced = resolver.isReferencedAliasDeclaration(node);
  77221. // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
  77222. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
  77223. return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
  77224. /*decorators*/ undefined,
  77225. /*modifiers*/ undefined,
  77226. /*importClause*/ undefined, node.moduleReference.expression), node), node);
  77227. }
  77228. return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
  77229. }
  77230. if (!shouldEmitImportEqualsDeclaration(node)) {
  77231. return undefined;
  77232. }
  77233. var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
  77234. ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
  77235. if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
  77236. // export var ${name} = ${moduleReference};
  77237. // var ${name} = ${moduleReference};
  77238. return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
  77239. ts.setOriginalNode(ts.createVariableDeclaration(node.name,
  77240. /*type*/ undefined, moduleReference), node)
  77241. ])), node), node);
  77242. }
  77243. else {
  77244. // exports.${name} = ${moduleReference};
  77245. return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
  77246. }
  77247. }
  77248. /**
  77249. * Gets a value indicating whether the node is exported from a namespace.
  77250. *
  77251. * @param node The node to test.
  77252. */
  77253. function isExportOfNamespace(node) {
  77254. return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
  77255. }
  77256. /**
  77257. * Gets a value indicating whether the node is exported from an external module.
  77258. *
  77259. * @param node The node to test.
  77260. */
  77261. function isExternalModuleExport(node) {
  77262. return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
  77263. }
  77264. /**
  77265. * Gets a value indicating whether the node is a named export from an external module.
  77266. *
  77267. * @param node The node to test.
  77268. */
  77269. function isNamedExternalModuleExport(node) {
  77270. return isExternalModuleExport(node)
  77271. && !ts.hasModifier(node, 512 /* Default */);
  77272. }
  77273. /**
  77274. * Gets a value indicating whether the node is the default export of an external module.
  77275. *
  77276. * @param node The node to test.
  77277. */
  77278. function isDefaultExternalModuleExport(node) {
  77279. return isExternalModuleExport(node)
  77280. && ts.hasModifier(node, 512 /* Default */);
  77281. }
  77282. /**
  77283. * Creates a statement for the provided expression. This is used in calls to `map`.
  77284. */
  77285. function expressionToStatement(expression) {
  77286. return ts.createExpressionStatement(expression);
  77287. }
  77288. function addExportMemberAssignment(statements, node) {
  77289. var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
  77290. ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
  77291. var statement = ts.createExpressionStatement(expression);
  77292. ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
  77293. statements.push(statement);
  77294. }
  77295. function createNamespaceExport(exportName, exportValue, location) {
  77296. return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
  77297. }
  77298. function createNamespaceExportExpression(exportName, exportValue, location) {
  77299. return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
  77300. }
  77301. function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
  77302. return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
  77303. }
  77304. /**
  77305. * Gets the declaration name used inside of a namespace or enum.
  77306. */
  77307. function getNamespaceParameterName(node) {
  77308. var name = ts.getGeneratedNameForNode(node);
  77309. ts.setSourceMapRange(name, node.name);
  77310. return name;
  77311. }
  77312. /**
  77313. * Gets the expression used to refer to a namespace or enum within the body
  77314. * of its declaration.
  77315. */
  77316. function getNamespaceContainerName(node) {
  77317. return ts.getGeneratedNameForNode(node);
  77318. }
  77319. /**
  77320. * Gets a local alias for a class declaration if it is a decorated class with an internal
  77321. * reference to the static side of the class. This is necessary to avoid issues with
  77322. * double-binding semantics for the class name.
  77323. */
  77324. function getClassAliasIfNeeded(node) {
  77325. if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
  77326. enableSubstitutionForClassAliases();
  77327. var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
  77328. classAliases[ts.getOriginalNodeId(node)] = classAlias;
  77329. hoistVariableDeclaration(classAlias);
  77330. return classAlias;
  77331. }
  77332. }
  77333. function getClassPrototype(node) {
  77334. return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
  77335. }
  77336. function getClassMemberPrefix(node, member) {
  77337. return ts.hasModifier(member, 32 /* Static */)
  77338. ? ts.getDeclarationName(node)
  77339. : getClassPrototype(node);
  77340. }
  77341. function enableSubstitutionForNonQualifiedEnumMembers() {
  77342. if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
  77343. enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
  77344. context.enableSubstitution(75 /* Identifier */);
  77345. }
  77346. }
  77347. function enableSubstitutionForClassAliases() {
  77348. if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
  77349. enabledSubstitutions |= 1 /* ClassAliases */;
  77350. // We need to enable substitutions for identifiers. This allows us to
  77351. // substitute class names inside of a class declaration.
  77352. context.enableSubstitution(75 /* Identifier */);
  77353. // Keep track of class aliases.
  77354. classAliases = [];
  77355. }
  77356. }
  77357. function enableSubstitutionForNamespaceExports() {
  77358. if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
  77359. enabledSubstitutions |= 2 /* NamespaceExports */;
  77360. // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
  77361. // substitute the names of exported members of a namespace.
  77362. context.enableSubstitution(75 /* Identifier */);
  77363. context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
  77364. // We need to be notified when entering and exiting namespaces.
  77365. context.enableEmitNotification(249 /* ModuleDeclaration */);
  77366. }
  77367. }
  77368. function isTransformedModuleDeclaration(node) {
  77369. return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
  77370. }
  77371. function isTransformedEnumDeclaration(node) {
  77372. return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
  77373. }
  77374. /**
  77375. * Hook for node emit.
  77376. *
  77377. * @param hint A hint as to the intended usage of the node.
  77378. * @param node The node to emit.
  77379. * @param emit A callback used to emit the node in the printer.
  77380. */
  77381. function onEmitNode(hint, node, emitCallback) {
  77382. var savedApplicableSubstitutions = applicableSubstitutions;
  77383. var savedCurrentSourceFile = currentSourceFile;
  77384. if (ts.isSourceFile(node)) {
  77385. currentSourceFile = node;
  77386. }
  77387. if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
  77388. applicableSubstitutions |= 2 /* NamespaceExports */;
  77389. }
  77390. if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
  77391. applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
  77392. }
  77393. previousOnEmitNode(hint, node, emitCallback);
  77394. applicableSubstitutions = savedApplicableSubstitutions;
  77395. currentSourceFile = savedCurrentSourceFile;
  77396. }
  77397. /**
  77398. * Hooks node substitutions.
  77399. *
  77400. * @param hint A hint as to the intended usage of the node.
  77401. * @param node The node to substitute.
  77402. */
  77403. function onSubstituteNode(hint, node) {
  77404. node = previousOnSubstituteNode(hint, node);
  77405. if (hint === 1 /* Expression */) {
  77406. return substituteExpression(node);
  77407. }
  77408. else if (ts.isShorthandPropertyAssignment(node)) {
  77409. return substituteShorthandPropertyAssignment(node);
  77410. }
  77411. return node;
  77412. }
  77413. function substituteShorthandPropertyAssignment(node) {
  77414. if (enabledSubstitutions & 2 /* NamespaceExports */) {
  77415. var name = node.name;
  77416. var exportedName = trySubstituteNamespaceExportedName(name);
  77417. if (exportedName) {
  77418. // A shorthand property with an assignment initializer is probably part of a
  77419. // destructuring assignment
  77420. if (node.objectAssignmentInitializer) {
  77421. var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
  77422. return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
  77423. }
  77424. return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
  77425. }
  77426. }
  77427. return node;
  77428. }
  77429. function substituteExpression(node) {
  77430. switch (node.kind) {
  77431. case 75 /* Identifier */:
  77432. return substituteExpressionIdentifier(node);
  77433. case 194 /* PropertyAccessExpression */:
  77434. return substitutePropertyAccessExpression(node);
  77435. case 195 /* ElementAccessExpression */:
  77436. return substituteElementAccessExpression(node);
  77437. }
  77438. return node;
  77439. }
  77440. function substituteExpressionIdentifier(node) {
  77441. return trySubstituteClassAlias(node)
  77442. || trySubstituteNamespaceExportedName(node)
  77443. || node;
  77444. }
  77445. function trySubstituteClassAlias(node) {
  77446. if (enabledSubstitutions & 1 /* ClassAliases */) {
  77447. if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
  77448. // Due to the emit for class decorators, any reference to the class from inside of the class body
  77449. // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
  77450. // behavior of class names in ES6.
  77451. // Also, when emitting statics for class expressions, we must substitute a class alias for
  77452. // constructor references in static property initializers.
  77453. var declaration = resolver.getReferencedValueDeclaration(node);
  77454. if (declaration) {
  77455. var classAlias = classAliases[declaration.id]; // TODO: GH#18217
  77456. if (classAlias) {
  77457. var clone_1 = ts.getSynthesizedClone(classAlias);
  77458. ts.setSourceMapRange(clone_1, node);
  77459. ts.setCommentRange(clone_1, node);
  77460. return clone_1;
  77461. }
  77462. }
  77463. }
  77464. }
  77465. return undefined;
  77466. }
  77467. function trySubstituteNamespaceExportedName(node) {
  77468. // If this is explicitly a local name, do not substitute.
  77469. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
  77470. // If we are nested within a namespace declaration, we may need to qualifiy
  77471. // an identifier that is exported from a merged namespace.
  77472. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
  77473. if (container && container.kind !== 290 /* SourceFile */) {
  77474. var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
  77475. (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
  77476. if (substitute) {
  77477. return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node),
  77478. /*location*/ node);
  77479. }
  77480. }
  77481. }
  77482. return undefined;
  77483. }
  77484. function substitutePropertyAccessExpression(node) {
  77485. return substituteConstantValue(node);
  77486. }
  77487. function substituteElementAccessExpression(node) {
  77488. return substituteConstantValue(node);
  77489. }
  77490. function substituteConstantValue(node) {
  77491. var constantValue = tryGetConstEnumValue(node);
  77492. if (constantValue !== undefined) {
  77493. // track the constant value on the node for the printer in needsDotDotForPropertyAccess
  77494. ts.setConstantValue(node, constantValue);
  77495. var substitute = ts.createLiteral(constantValue);
  77496. if (!compilerOptions.removeComments) {
  77497. var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
  77498. var propertyName = ts.isPropertyAccessExpression(originalNode)
  77499. ? ts.declarationNameToString(originalNode.name)
  77500. : ts.getTextOfNode(originalNode.argumentExpression);
  77501. ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
  77502. }
  77503. return substitute;
  77504. }
  77505. return node;
  77506. }
  77507. function tryGetConstEnumValue(node) {
  77508. if (compilerOptions.isolatedModules) {
  77509. return undefined;
  77510. }
  77511. return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
  77512. }
  77513. }
  77514. ts.transformTypeScript = transformTypeScript;
  77515. function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
  77516. var argumentsArray = [];
  77517. argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
  77518. argumentsArray.push(target);
  77519. if (memberName) {
  77520. argumentsArray.push(memberName);
  77521. if (descriptor) {
  77522. argumentsArray.push(descriptor);
  77523. }
  77524. }
  77525. context.requestEmitHelper(ts.decorateHelper);
  77526. return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"),
  77527. /*typeArguments*/ undefined, argumentsArray), location);
  77528. }
  77529. ts.decorateHelper = {
  77530. name: "typescript:decorate",
  77531. importName: "__decorate",
  77532. scoped: false,
  77533. priority: 2,
  77534. text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
  77535. };
  77536. function createMetadataHelper(context, metadataKey, metadataValue) {
  77537. context.requestEmitHelper(ts.metadataHelper);
  77538. return ts.createCall(ts.getUnscopedHelperName("__metadata"),
  77539. /*typeArguments*/ undefined, [
  77540. ts.createLiteral(metadataKey),
  77541. metadataValue
  77542. ]);
  77543. }
  77544. ts.metadataHelper = {
  77545. name: "typescript:metadata",
  77546. importName: "__metadata",
  77547. scoped: false,
  77548. priority: 3,
  77549. text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
  77550. };
  77551. function createParamHelper(context, expression, parameterOffset, location) {
  77552. context.requestEmitHelper(ts.paramHelper);
  77553. return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"),
  77554. /*typeArguments*/ undefined, [
  77555. ts.createLiteral(parameterOffset),
  77556. expression
  77557. ]), location);
  77558. }
  77559. ts.paramHelper = {
  77560. name: "typescript:param",
  77561. importName: "__param",
  77562. scoped: false,
  77563. priority: 4,
  77564. text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
  77565. };
  77566. })(ts || (ts = {}));
  77567. /*@internal*/
  77568. var ts;
  77569. (function (ts) {
  77570. var ClassPropertySubstitutionFlags;
  77571. (function (ClassPropertySubstitutionFlags) {
  77572. /**
  77573. * Enables substitutions for class expressions with static fields
  77574. * which have initializers that reference the class name.
  77575. */
  77576. ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
  77577. })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
  77578. var PrivateIdentifierPlacement;
  77579. (function (PrivateIdentifierPlacement) {
  77580. PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
  77581. })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
  77582. /**
  77583. * Transforms ECMAScript Class Syntax.
  77584. * TypeScript parameter property syntax is transformed in the TypeScript transformer.
  77585. * For now, this transforms public field declarations using TypeScript class semantics,
  77586. * where declarations are elided and initializers are transformed as assignments in the constructor.
  77587. * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
  77588. */
  77589. function transformClassFields(context) {
  77590. var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
  77591. var resolver = context.getEmitResolver();
  77592. var compilerOptions = context.getCompilerOptions();
  77593. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  77594. var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
  77595. var previousOnSubstituteNode = context.onSubstituteNode;
  77596. context.onSubstituteNode = onSubstituteNode;
  77597. var enabledSubstitutions;
  77598. var classAliases;
  77599. /**
  77600. * Tracks what computed name expressions originating from elided names must be inlined
  77601. * at the next execution site, in document order
  77602. */
  77603. var pendingExpressions;
  77604. /**
  77605. * Tracks what computed name expression statements and static property initializers must be
  77606. * emitted at the next execution site, in document order (for decorated classes).
  77607. */
  77608. var pendingStatements;
  77609. var privateIdentifierEnvironmentStack = [];
  77610. var currentPrivateIdentifierEnvironment;
  77611. return ts.chainBundle(transformSourceFile);
  77612. function transformSourceFile(node) {
  77613. var options = context.getCompilerOptions();
  77614. if (node.isDeclarationFile
  77615. || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
  77616. return node;
  77617. }
  77618. var visited = ts.visitEachChild(node, visitor, context);
  77619. ts.addEmitHelpers(visited, context.readEmitHelpers());
  77620. return visited;
  77621. }
  77622. function visitor(node) {
  77623. if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
  77624. return node;
  77625. switch (node.kind) {
  77626. case 214 /* ClassExpression */:
  77627. case 245 /* ClassDeclaration */:
  77628. return visitClassLike(node);
  77629. case 159 /* PropertyDeclaration */:
  77630. return visitPropertyDeclaration(node);
  77631. case 225 /* VariableStatement */:
  77632. return visitVariableStatement(node);
  77633. case 154 /* ComputedPropertyName */:
  77634. return visitComputedPropertyName(node);
  77635. case 194 /* PropertyAccessExpression */:
  77636. return visitPropertyAccessExpression(node);
  77637. case 207 /* PrefixUnaryExpression */:
  77638. return visitPrefixUnaryExpression(node);
  77639. case 208 /* PostfixUnaryExpression */:
  77640. return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
  77641. case 196 /* CallExpression */:
  77642. return visitCallExpression(node);
  77643. case 209 /* BinaryExpression */:
  77644. return visitBinaryExpression(node);
  77645. case 76 /* PrivateIdentifier */:
  77646. return visitPrivateIdentifier(node);
  77647. case 226 /* ExpressionStatement */:
  77648. return visitExpressionStatement(node);
  77649. case 230 /* ForStatement */:
  77650. return visitForStatement(node);
  77651. case 198 /* TaggedTemplateExpression */:
  77652. return visitTaggedTemplateExpression(node);
  77653. }
  77654. return ts.visitEachChild(node, visitor, context);
  77655. }
  77656. function visitorDestructuringTarget(node) {
  77657. switch (node.kind) {
  77658. case 193 /* ObjectLiteralExpression */:
  77659. case 192 /* ArrayLiteralExpression */:
  77660. return visitAssignmentPattern(node);
  77661. default:
  77662. return visitor(node);
  77663. }
  77664. }
  77665. /**
  77666. * If we visit a private name, this means it is an undeclared private name.
  77667. * Replace it with an empty identifier to indicate a problem with the code.
  77668. */
  77669. function visitPrivateIdentifier(node) {
  77670. if (!shouldTransformPrivateFields) {
  77671. return node;
  77672. }
  77673. return ts.setOriginalNode(ts.createIdentifier(""), node);
  77674. }
  77675. /**
  77676. * Visits the members of a class that has fields.
  77677. *
  77678. * @param node The node to visit.
  77679. */
  77680. function classElementVisitor(node) {
  77681. switch (node.kind) {
  77682. case 162 /* Constructor */:
  77683. // Constructors for classes using class fields are transformed in
  77684. // `visitClassDeclaration` or `visitClassExpression`.
  77685. return undefined;
  77686. case 163 /* GetAccessor */:
  77687. case 164 /* SetAccessor */:
  77688. case 161 /* MethodDeclaration */:
  77689. // Visit the name of the member (if it's a computed property name).
  77690. return ts.visitEachChild(node, classElementVisitor, context);
  77691. case 159 /* PropertyDeclaration */:
  77692. return visitPropertyDeclaration(node);
  77693. case 154 /* ComputedPropertyName */:
  77694. return visitComputedPropertyName(node);
  77695. case 222 /* SemicolonClassElement */:
  77696. return node;
  77697. default:
  77698. return visitor(node);
  77699. }
  77700. }
  77701. function visitVariableStatement(node) {
  77702. var savedPendingStatements = pendingStatements;
  77703. pendingStatements = [];
  77704. var visitedNode = ts.visitEachChild(node, visitor, context);
  77705. var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
  77706. visitedNode;
  77707. pendingStatements = savedPendingStatements;
  77708. return statement;
  77709. }
  77710. function visitComputedPropertyName(name) {
  77711. var node = ts.visitEachChild(name, visitor, context);
  77712. if (ts.some(pendingExpressions)) {
  77713. var expressions = pendingExpressions;
  77714. expressions.push(name.expression);
  77715. pendingExpressions = [];
  77716. node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
  77717. }
  77718. return node;
  77719. }
  77720. function visitPropertyDeclaration(node) {
  77721. ts.Debug.assert(!ts.some(node.decorators));
  77722. if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
  77723. // Initializer is elided as the field is initialized in transformConstructor.
  77724. return ts.updateProperty(node,
  77725. /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name,
  77726. /*questionOrExclamationToken*/ undefined,
  77727. /*type*/ undefined,
  77728. /*initializer*/ undefined);
  77729. }
  77730. // Create a temporary variable to store a computed property name (if necessary).
  77731. // If it's not inlineable, then we emit an expression after the class which assigns
  77732. // the property name to the temporary variable.
  77733. var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
  77734. if (expr && !ts.isSimpleInlineableExpression(expr)) {
  77735. (pendingExpressions || (pendingExpressions = [])).push(expr);
  77736. }
  77737. return undefined;
  77738. }
  77739. function createPrivateIdentifierAccess(info, receiver) {
  77740. receiver = ts.visitNode(receiver, visitor, ts.isExpression);
  77741. switch (info.placement) {
  77742. case 0 /* InstanceField */:
  77743. return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
  77744. default: return ts.Debug.fail("Unexpected private identifier placement");
  77745. }
  77746. }
  77747. function visitPropertyAccessExpression(node) {
  77748. if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
  77749. var privateIdentifierInfo = accessPrivateIdentifier(node.name);
  77750. if (privateIdentifierInfo) {
  77751. return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
  77752. }
  77753. }
  77754. return ts.visitEachChild(node, visitor, context);
  77755. }
  77756. function visitPrefixUnaryExpression(node) {
  77757. if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
  77758. var operator = node.operator === 45 /* PlusPlusToken */ ?
  77759. 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
  77760. 40 /* MinusToken */ : undefined;
  77761. var info = void 0;
  77762. if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
  77763. var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
  77764. var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
  77765. var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
  77766. return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
  77767. }
  77768. }
  77769. return ts.visitEachChild(node, visitor, context);
  77770. }
  77771. function visitPostfixUnaryExpression(node, valueIsDiscarded) {
  77772. if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
  77773. var operator = node.operator === 45 /* PlusPlusToken */ ?
  77774. 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
  77775. 40 /* MinusToken */ : undefined;
  77776. var info = void 0;
  77777. if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
  77778. var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
  77779. var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
  77780. var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
  77781. // Create a temporary variable to store the value returned by the expression.
  77782. var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
  77783. return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
  77784. createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
  77785. returnValue
  77786. ])), node);
  77787. }
  77788. }
  77789. return ts.visitEachChild(node, visitor, context);
  77790. }
  77791. function visitForStatement(node) {
  77792. if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
  77793. return ts.updateFor(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement));
  77794. }
  77795. return ts.visitEachChild(node, visitor, context);
  77796. }
  77797. function visitExpressionStatement(node) {
  77798. if (ts.isPostfixUnaryExpression(node.expression)) {
  77799. return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
  77800. }
  77801. return ts.visitEachChild(node, visitor, context);
  77802. }
  77803. function createCopiableReceiverExpr(receiver) {
  77804. var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
  77805. if (ts.isSimpleInlineableExpression(receiver)) {
  77806. return { readExpression: clone, initializeExpression: undefined };
  77807. }
  77808. var readExpression = ts.createTempVariable(hoistVariableDeclaration);
  77809. var initializeExpression = ts.createAssignment(readExpression, clone);
  77810. return { readExpression: readExpression, initializeExpression: initializeExpression };
  77811. }
  77812. function visitCallExpression(node) {
  77813. if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
  77814. // Transform call expressions of private names to properly bind the `this` parameter.
  77815. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
  77816. return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"),
  77817. /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
  77818. }
  77819. return ts.visitEachChild(node, visitor, context);
  77820. }
  77821. function visitTaggedTemplateExpression(node) {
  77822. if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
  77823. // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
  77824. var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
  77825. return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"),
  77826. /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
  77827. }
  77828. return ts.visitEachChild(node, visitor, context);
  77829. }
  77830. function visitBinaryExpression(node) {
  77831. if (shouldTransformPrivateFields) {
  77832. if (ts.isDestructuringAssignment(node)) {
  77833. var savedPendingExpressions = pendingExpressions;
  77834. pendingExpressions = undefined;
  77835. node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
  77836. var expr = ts.some(pendingExpressions) ?
  77837. ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
  77838. node;
  77839. pendingExpressions = savedPendingExpressions;
  77840. return expr;
  77841. }
  77842. if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
  77843. var info = accessPrivateIdentifier(node.left.name);
  77844. if (info) {
  77845. return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
  77846. }
  77847. }
  77848. }
  77849. return ts.visitEachChild(node, visitor, context);
  77850. }
  77851. function createPrivateIdentifierAssignment(info, receiver, right, operator) {
  77852. switch (info.placement) {
  77853. case 0 /* InstanceField */: {
  77854. return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
  77855. }
  77856. default: return ts.Debug.fail("Unexpected private identifier placement");
  77857. }
  77858. }
  77859. function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
  77860. receiver = ts.visitNode(receiver, visitor, ts.isExpression);
  77861. right = ts.visitNode(right, visitor, ts.isExpression);
  77862. if (ts.isCompoundAssignment(operator)) {
  77863. var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
  77864. return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
  77865. }
  77866. else {
  77867. return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
  77868. }
  77869. }
  77870. /**
  77871. * Set up the environment for a class.
  77872. */
  77873. function visitClassLike(node) {
  77874. var savedPendingExpressions = pendingExpressions;
  77875. pendingExpressions = undefined;
  77876. if (shouldTransformPrivateFields) {
  77877. startPrivateIdentifierEnvironment();
  77878. }
  77879. var result = ts.isClassDeclaration(node) ?
  77880. visitClassDeclaration(node) :
  77881. visitClassExpression(node);
  77882. if (shouldTransformPrivateFields) {
  77883. endPrivateIdentifierEnvironment();
  77884. }
  77885. pendingExpressions = savedPendingExpressions;
  77886. return result;
  77887. }
  77888. function doesClassElementNeedTransform(node) {
  77889. return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
  77890. }
  77891. function visitClassDeclaration(node) {
  77892. if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
  77893. return ts.visitEachChild(node, visitor, context);
  77894. }
  77895. var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
  77896. var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
  77897. var statements = [
  77898. ts.updateClassDeclaration(node,
  77899. /*decorators*/ undefined, node.modifiers, node.name,
  77900. /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
  77901. ];
  77902. // Write any pending expressions from elided or moved computed property names
  77903. if (ts.some(pendingExpressions)) {
  77904. statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
  77905. }
  77906. // Emit static property assignment. Because classDeclaration is lexically evaluated,
  77907. // it is safe to emit static property assignment after classDeclaration
  77908. // From ES6 specification:
  77909. // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
  77910. // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
  77911. var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
  77912. if (ts.some(staticProperties)) {
  77913. addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
  77914. }
  77915. return statements;
  77916. }
  77917. function visitClassExpression(node) {
  77918. if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
  77919. return ts.visitEachChild(node, visitor, context);
  77920. }
  77921. // If this class expression is a transformation of a decorated class declaration,
  77922. // then we want to output the pendingExpressions as statements, not as inlined
  77923. // expressions with the class statement.
  77924. //
  77925. // In this case, we use pendingStatements to produce the same output as the
  77926. // class declaration transformation. The VariableStatement visitor will insert
  77927. // these statements after the class expression variable statement.
  77928. var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
  77929. var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
  77930. var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
  77931. var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
  77932. var classExpression = ts.updateClassExpression(node, node.modifiers, node.name,
  77933. /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
  77934. if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
  77935. if (isDecoratedClassDeclaration) {
  77936. ts.Debug.assertDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
  77937. // Write any pending expressions from elided or moved computed property names
  77938. if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
  77939. pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
  77940. }
  77941. if (pendingStatements && ts.some(staticProperties)) {
  77942. addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
  77943. }
  77944. return classExpression;
  77945. }
  77946. else {
  77947. var expressions = [];
  77948. var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
  77949. var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
  77950. if (isClassWithConstructorReference) {
  77951. // record an alias as the class name is not in scope for statics.
  77952. enableSubstitutionForClassAliases();
  77953. var alias = ts.getSynthesizedClone(temp);
  77954. alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
  77955. classAliases[ts.getOriginalNodeId(node)] = alias;
  77956. }
  77957. // To preserve the behavior of the old emitter, we explicitly indent
  77958. // the body of a class with static initializers.
  77959. ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
  77960. expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
  77961. // Add any pending expressions leftover from elided or relocated computed property names
  77962. ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
  77963. ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
  77964. expressions.push(ts.startOnNewLine(temp));
  77965. return ts.inlineExpressions(expressions);
  77966. }
  77967. }
  77968. return classExpression;
  77969. }
  77970. function transformClassMembers(node, isDerivedClass) {
  77971. if (shouldTransformPrivateFields) {
  77972. // Declare private names.
  77973. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  77974. var member = _a[_i];
  77975. if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
  77976. addPrivateIdentifierToEnvironment(member.name);
  77977. }
  77978. }
  77979. }
  77980. var members = [];
  77981. var constructor = transformConstructor(node, isDerivedClass);
  77982. if (constructor) {
  77983. members.push(constructor);
  77984. }
  77985. ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
  77986. return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
  77987. }
  77988. function isPropertyDeclarationThatRequiresConstructorStatement(member) {
  77989. if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
  77990. return false;
  77991. }
  77992. if (context.getCompilerOptions().useDefineForClassFields) {
  77993. // If we are using define semantics and targeting ESNext or higher,
  77994. // then we don't need to transform any class properties.
  77995. return languageVersion < 99 /* ESNext */;
  77996. }
  77997. return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
  77998. }
  77999. function transformConstructor(node, isDerivedClass) {
  78000. var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
  78001. var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
  78002. if (!ts.some(properties)) {
  78003. return constructor;
  78004. }
  78005. var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
  78006. var body = transformConstructorBody(node, constructor, isDerivedClass);
  78007. if (!body) {
  78008. return undefined;
  78009. }
  78010. return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
  78011. /*decorators*/ undefined,
  78012. /*modifiers*/ undefined, parameters, body), constructor || node), constructor));
  78013. }
  78014. function transformConstructorBody(node, constructor, isDerivedClass) {
  78015. var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
  78016. var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
  78017. if (!useDefineForClassFields) {
  78018. properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
  78019. }
  78020. // Only generate synthetic constructor when there are property initializers to move.
  78021. if (!constructor && !ts.some(properties)) {
  78022. return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
  78023. }
  78024. resumeLexicalEnvironment();
  78025. var indexOfFirstStatement = 0;
  78026. var statements = [];
  78027. if (!constructor && isDerivedClass) {
  78028. // Add a synthetic `super` call:
  78029. //
  78030. // super(...arguments);
  78031. //
  78032. statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(),
  78033. /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
  78034. }
  78035. if (constructor) {
  78036. indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
  78037. }
  78038. // Add the property initializers. Transforms this:
  78039. //
  78040. // public x = 1;
  78041. //
  78042. // Into this:
  78043. //
  78044. // constructor() {
  78045. // this.x = 1;
  78046. // }
  78047. //
  78048. if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
  78049. var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
  78050. if (afterParameterProperties === -1) {
  78051. afterParameterProperties = constructor.body.statements.length;
  78052. }
  78053. if (afterParameterProperties > indexOfFirstStatement) {
  78054. if (!useDefineForClassFields) {
  78055. ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
  78056. }
  78057. indexOfFirstStatement = afterParameterProperties;
  78058. }
  78059. }
  78060. addPropertyStatements(statements, properties, ts.createThis());
  78061. // Add existing statements, skipping the initial super call.
  78062. if (constructor) {
  78063. ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
  78064. }
  78065. statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
  78066. return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
  78067. /*location*/ constructor ? constructor.body.statements : node.members),
  78068. /*multiLine*/ true),
  78069. /*location*/ constructor ? constructor.body : undefined);
  78070. }
  78071. /**
  78072. * Generates assignment statements for property initializers.
  78073. *
  78074. * @param properties An array of property declarations to transform.
  78075. * @param receiver The receiver on which each property should be assigned.
  78076. */
  78077. function addPropertyStatements(statements, properties, receiver) {
  78078. for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
  78079. var property = properties_6[_i];
  78080. var expression = transformProperty(property, receiver);
  78081. if (!expression) {
  78082. continue;
  78083. }
  78084. var statement = ts.createExpressionStatement(expression);
  78085. ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
  78086. ts.setCommentRange(statement, property);
  78087. ts.setOriginalNode(statement, property);
  78088. statements.push(statement);
  78089. }
  78090. }
  78091. /**
  78092. * Generates assignment expressions for property initializers.
  78093. *
  78094. * @param properties An array of property declarations to transform.
  78095. * @param receiver The receiver on which each property should be assigned.
  78096. */
  78097. function generateInitializedPropertyExpressions(properties, receiver) {
  78098. var expressions = [];
  78099. for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
  78100. var property = properties_7[_i];
  78101. var expression = transformProperty(property, receiver);
  78102. if (!expression) {
  78103. continue;
  78104. }
  78105. ts.startOnNewLine(expression);
  78106. ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
  78107. ts.setCommentRange(expression, property);
  78108. ts.setOriginalNode(expression, property);
  78109. expressions.push(expression);
  78110. }
  78111. return expressions;
  78112. }
  78113. /**
  78114. * Transforms a property initializer into an assignment statement.
  78115. *
  78116. * @param property The property declaration.
  78117. * @param receiver The object receiving the property assignment.
  78118. */
  78119. function transformProperty(property, receiver) {
  78120. // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
  78121. var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
  78122. var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
  78123. ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
  78124. : property.name;
  78125. if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
  78126. var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
  78127. if (privateIdentifierInfo) {
  78128. switch (privateIdentifierInfo.placement) {
  78129. case 0 /* InstanceField */: {
  78130. return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
  78131. }
  78132. }
  78133. }
  78134. else {
  78135. ts.Debug.fail("Undeclared private name for property declaration.");
  78136. }
  78137. }
  78138. if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
  78139. return undefined;
  78140. }
  78141. if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
  78142. return undefined;
  78143. }
  78144. var propertyOriginalNode = ts.getOriginalNode(property);
  78145. var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
  78146. : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
  78147. : ts.createVoidZero();
  78148. if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
  78149. var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
  78150. return ts.createAssignment(memberAccess, initializer);
  78151. }
  78152. else {
  78153. var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
  78154. : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
  78155. : propertyName;
  78156. var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
  78157. return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
  78158. }
  78159. }
  78160. function enableSubstitutionForClassAliases() {
  78161. if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
  78162. enabledSubstitutions |= 1 /* ClassAliases */;
  78163. // We need to enable substitutions for identifiers. This allows us to
  78164. // substitute class names inside of a class declaration.
  78165. context.enableSubstitution(75 /* Identifier */);
  78166. // Keep track of class aliases.
  78167. classAliases = [];
  78168. }
  78169. }
  78170. /**
  78171. * Hooks node substitutions.
  78172. *
  78173. * @param hint The context for the emitter.
  78174. * @param node The node to substitute.
  78175. */
  78176. function onSubstituteNode(hint, node) {
  78177. node = previousOnSubstituteNode(hint, node);
  78178. if (hint === 1 /* Expression */) {
  78179. return substituteExpression(node);
  78180. }
  78181. return node;
  78182. }
  78183. function substituteExpression(node) {
  78184. switch (node.kind) {
  78185. case 75 /* Identifier */:
  78186. return substituteExpressionIdentifier(node);
  78187. }
  78188. return node;
  78189. }
  78190. function substituteExpressionIdentifier(node) {
  78191. return trySubstituteClassAlias(node) || node;
  78192. }
  78193. function trySubstituteClassAlias(node) {
  78194. if (enabledSubstitutions & 1 /* ClassAliases */) {
  78195. if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
  78196. // Due to the emit for class decorators, any reference to the class from inside of the class body
  78197. // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
  78198. // behavior of class names in ES6.
  78199. // Also, when emitting statics for class expressions, we must substitute a class alias for
  78200. // constructor references in static property initializers.
  78201. var declaration = resolver.getReferencedValueDeclaration(node);
  78202. if (declaration) {
  78203. var classAlias = classAliases[declaration.id]; // TODO: GH#18217
  78204. if (classAlias) {
  78205. var clone_2 = ts.getSynthesizedClone(classAlias);
  78206. ts.setSourceMapRange(clone_2, node);
  78207. ts.setCommentRange(clone_2, node);
  78208. return clone_2;
  78209. }
  78210. }
  78211. }
  78212. }
  78213. return undefined;
  78214. }
  78215. /**
  78216. * If the name is a computed property, this function transforms it, then either returns an expression which caches the
  78217. * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
  78218. * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
  78219. */
  78220. function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
  78221. if (ts.isComputedPropertyName(name)) {
  78222. var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
  78223. var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
  78224. var inlinable = ts.isSimpleInlineableExpression(innerExpression);
  78225. var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
  78226. if (!alreadyTransformed && !inlinable && shouldHoist) {
  78227. var generatedName = ts.getGeneratedNameForNode(name);
  78228. hoistVariableDeclaration(generatedName);
  78229. return ts.createAssignment(generatedName, expression);
  78230. }
  78231. return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
  78232. }
  78233. }
  78234. function startPrivateIdentifierEnvironment() {
  78235. privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
  78236. currentPrivateIdentifierEnvironment = undefined;
  78237. }
  78238. function endPrivateIdentifierEnvironment() {
  78239. currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
  78240. }
  78241. function addPrivateIdentifierToEnvironment(name) {
  78242. var text = ts.getTextOfPropertyName(name);
  78243. var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
  78244. weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
  78245. hoistVariableDeclaration(weakMapName);
  78246. (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
  78247. .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
  78248. (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"),
  78249. /*typeArguments*/ undefined, [])));
  78250. }
  78251. function accessPrivateIdentifier(name) {
  78252. if (currentPrivateIdentifierEnvironment) {
  78253. var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
  78254. if (info) {
  78255. return info;
  78256. }
  78257. }
  78258. for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
  78259. var env = privateIdentifierEnvironmentStack[i];
  78260. if (!env) {
  78261. continue;
  78262. }
  78263. var info = env.get(name.escapedText);
  78264. if (info) {
  78265. return info;
  78266. }
  78267. }
  78268. return undefined;
  78269. }
  78270. function wrapPrivateIdentifierForDestructuringTarget(node) {
  78271. var parameter = ts.getGeneratedNameForNode(node);
  78272. var info = accessPrivateIdentifier(node.name);
  78273. if (!info) {
  78274. return ts.visitEachChild(node, visitor, context);
  78275. }
  78276. var receiver = node.expression;
  78277. // We cannot copy `this` or `super` into the function because they will be bound
  78278. // differently inside the function.
  78279. if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
  78280. receiver = ts.createTempVariable(hoistVariableDeclaration);
  78281. receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
  78282. (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
  78283. }
  78284. return ts.createPropertyAccess(
  78285. // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
  78286. ts.createParen(ts.createObjectLiteral([
  78287. ts.createSetAccessor(
  78288. /*decorators*/ undefined,
  78289. /*modifiers*/ undefined, "value", [ts.createParameter(
  78290. /*decorators*/ undefined,
  78291. /*modifiers*/ undefined,
  78292. /*dotDotDotToken*/ undefined, parameter,
  78293. /*questionToken*/ undefined,
  78294. /*type*/ undefined,
  78295. /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
  78296. ])), "value");
  78297. }
  78298. function visitArrayAssignmentTarget(node) {
  78299. var target = ts.getTargetOfBindingOrAssignmentElement(node);
  78300. if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
  78301. var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
  78302. if (ts.isAssignmentExpression(node)) {
  78303. return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
  78304. }
  78305. else if (ts.isSpreadElement(node)) {
  78306. return ts.updateSpread(node, wrapped);
  78307. }
  78308. else {
  78309. return wrapped;
  78310. }
  78311. }
  78312. return ts.visitNode(node, visitorDestructuringTarget);
  78313. }
  78314. function visitObjectAssignmentTarget(node) {
  78315. if (ts.isPropertyAssignment(node)) {
  78316. var target = ts.getTargetOfBindingOrAssignmentElement(node);
  78317. if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
  78318. var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
  78319. var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
  78320. return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
  78321. }
  78322. return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
  78323. }
  78324. return ts.visitNode(node, visitor);
  78325. }
  78326. function visitAssignmentPattern(node) {
  78327. if (ts.isArrayLiteralExpression(node)) {
  78328. // Transforms private names in destructuring assignment array bindings.
  78329. //
  78330. // Source:
  78331. // ([ this.#myProp ] = [ "hello" ]);
  78332. //
  78333. // Transformation:
  78334. // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
  78335. return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
  78336. }
  78337. else {
  78338. // Transforms private names in destructuring assignment object bindings.
  78339. //
  78340. // Source:
  78341. // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
  78342. //
  78343. // Transformation:
  78344. // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
  78345. return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
  78346. }
  78347. }
  78348. }
  78349. ts.transformClassFields = transformClassFields;
  78350. function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
  78351. return ts.createCall(ts.createPropertyAccess(weakMapName, "set"),
  78352. /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
  78353. }
  78354. ts.classPrivateFieldGetHelper = {
  78355. name: "typescript:classPrivateFieldGet",
  78356. scoped: false,
  78357. text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };"
  78358. };
  78359. function createClassPrivateFieldGetHelper(context, receiver, privateField) {
  78360. context.requestEmitHelper(ts.classPrivateFieldGetHelper);
  78361. return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
  78362. }
  78363. ts.classPrivateFieldSetHelper = {
  78364. name: "typescript:classPrivateFieldSet",
  78365. scoped: false,
  78366. text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };"
  78367. };
  78368. function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
  78369. context.requestEmitHelper(ts.classPrivateFieldSetHelper);
  78370. return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
  78371. }
  78372. })(ts || (ts = {}));
  78373. /*@internal*/
  78374. var ts;
  78375. (function (ts) {
  78376. var ES2017SubstitutionFlags;
  78377. (function (ES2017SubstitutionFlags) {
  78378. /** Enables substitutions for async methods with `super` calls. */
  78379. ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
  78380. })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
  78381. var ContextFlags;
  78382. (function (ContextFlags) {
  78383. ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
  78384. ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
  78385. })(ContextFlags || (ContextFlags = {}));
  78386. function transformES2017(context) {
  78387. var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
  78388. var resolver = context.getEmitResolver();
  78389. var compilerOptions = context.getCompilerOptions();
  78390. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  78391. /**
  78392. * Keeps track of whether expression substitution has been enabled for specific edge cases.
  78393. * They are persisted between each SourceFile transformation and should not be reset.
  78394. */
  78395. var enabledSubstitutions;
  78396. /**
  78397. * This keeps track of containers where `super` is valid, for use with
  78398. * just-in-time substitution for `super` expressions inside of async methods.
  78399. */
  78400. var enclosingSuperContainerFlags = 0;
  78401. var enclosingFunctionParameterNames;
  78402. /**
  78403. * Keeps track of property names accessed on super (`super.x`) within async functions.
  78404. */
  78405. var capturedSuperProperties;
  78406. /** Whether the async function contains an element access on super (`super[x]`). */
  78407. var hasSuperElementAccess;
  78408. /** A set of node IDs for generated super accessors (variable statements). */
  78409. var substitutedSuperAccessors = [];
  78410. var contextFlags = 0;
  78411. // Save the previous transformation hooks.
  78412. var previousOnEmitNode = context.onEmitNode;
  78413. var previousOnSubstituteNode = context.onSubstituteNode;
  78414. // Set new transformation hooks.
  78415. context.onEmitNode = onEmitNode;
  78416. context.onSubstituteNode = onSubstituteNode;
  78417. return ts.chainBundle(transformSourceFile);
  78418. function transformSourceFile(node) {
  78419. if (node.isDeclarationFile) {
  78420. return node;
  78421. }
  78422. setContextFlag(1 /* NonTopLevel */, false);
  78423. setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
  78424. var visited = ts.visitEachChild(node, visitor, context);
  78425. ts.addEmitHelpers(visited, context.readEmitHelpers());
  78426. return visited;
  78427. }
  78428. function setContextFlag(flag, val) {
  78429. contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
  78430. }
  78431. function inContext(flags) {
  78432. return (contextFlags & flags) !== 0;
  78433. }
  78434. function inTopLevelContext() {
  78435. return !inContext(1 /* NonTopLevel */);
  78436. }
  78437. function inHasLexicalThisContext() {
  78438. return inContext(2 /* HasLexicalThis */);
  78439. }
  78440. function doWithContext(flags, cb, value) {
  78441. var contextFlagsToSet = flags & ~contextFlags;
  78442. if (contextFlagsToSet) {
  78443. setContextFlag(contextFlagsToSet, /*val*/ true);
  78444. var result = cb(value);
  78445. setContextFlag(contextFlagsToSet, /*val*/ false);
  78446. return result;
  78447. }
  78448. return cb(value);
  78449. }
  78450. function visitDefault(node) {
  78451. return ts.visitEachChild(node, visitor, context);
  78452. }
  78453. function visitor(node) {
  78454. if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
  78455. return node;
  78456. }
  78457. switch (node.kind) {
  78458. case 126 /* AsyncKeyword */:
  78459. // ES2017 async modifier should be elided for targets < ES2017
  78460. return undefined;
  78461. case 206 /* AwaitExpression */:
  78462. return visitAwaitExpression(node);
  78463. case 161 /* MethodDeclaration */:
  78464. return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
  78465. case 244 /* FunctionDeclaration */:
  78466. return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
  78467. case 201 /* FunctionExpression */:
  78468. return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
  78469. case 202 /* ArrowFunction */:
  78470. return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
  78471. case 194 /* PropertyAccessExpression */:
  78472. if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
  78473. capturedSuperProperties.set(node.name.escapedText, true);
  78474. }
  78475. return ts.visitEachChild(node, visitor, context);
  78476. case 195 /* ElementAccessExpression */:
  78477. if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
  78478. hasSuperElementAccess = true;
  78479. }
  78480. return ts.visitEachChild(node, visitor, context);
  78481. case 163 /* GetAccessor */:
  78482. case 164 /* SetAccessor */:
  78483. case 162 /* Constructor */:
  78484. case 245 /* ClassDeclaration */:
  78485. case 214 /* ClassExpression */:
  78486. return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
  78487. default:
  78488. return ts.visitEachChild(node, visitor, context);
  78489. }
  78490. }
  78491. function asyncBodyVisitor(node) {
  78492. if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
  78493. switch (node.kind) {
  78494. case 225 /* VariableStatement */:
  78495. return visitVariableStatementInAsyncBody(node);
  78496. case 230 /* ForStatement */:
  78497. return visitForStatementInAsyncBody(node);
  78498. case 231 /* ForInStatement */:
  78499. return visitForInStatementInAsyncBody(node);
  78500. case 232 /* ForOfStatement */:
  78501. return visitForOfStatementInAsyncBody(node);
  78502. case 280 /* CatchClause */:
  78503. return visitCatchClauseInAsyncBody(node);
  78504. case 223 /* Block */:
  78505. case 237 /* SwitchStatement */:
  78506. case 251 /* CaseBlock */:
  78507. case 277 /* CaseClause */:
  78508. case 278 /* DefaultClause */:
  78509. case 240 /* TryStatement */:
  78510. case 228 /* DoStatement */:
  78511. case 229 /* WhileStatement */:
  78512. case 227 /* IfStatement */:
  78513. case 236 /* WithStatement */:
  78514. case 238 /* LabeledStatement */:
  78515. return ts.visitEachChild(node, asyncBodyVisitor, context);
  78516. default:
  78517. return ts.Debug.assertNever(node, "Unhandled node.");
  78518. }
  78519. }
  78520. return visitor(node);
  78521. }
  78522. function visitCatchClauseInAsyncBody(node) {
  78523. var catchClauseNames = ts.createUnderscoreEscapedMap();
  78524. recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
  78525. // names declared in a catch variable are block scoped
  78526. var catchClauseUnshadowedNames;
  78527. catchClauseNames.forEach(function (_, escapedName) {
  78528. if (enclosingFunctionParameterNames.has(escapedName)) {
  78529. if (!catchClauseUnshadowedNames) {
  78530. catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
  78531. }
  78532. catchClauseUnshadowedNames.delete(escapedName);
  78533. }
  78534. });
  78535. if (catchClauseUnshadowedNames) {
  78536. var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
  78537. enclosingFunctionParameterNames = catchClauseUnshadowedNames;
  78538. var result = ts.visitEachChild(node, asyncBodyVisitor, context);
  78539. enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
  78540. return result;
  78541. }
  78542. else {
  78543. return ts.visitEachChild(node, asyncBodyVisitor, context);
  78544. }
  78545. }
  78546. function visitVariableStatementInAsyncBody(node) {
  78547. if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
  78548. var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
  78549. return expression ? ts.createExpressionStatement(expression) : undefined;
  78550. }
  78551. return ts.visitEachChild(node, visitor, context);
  78552. }
  78553. function visitForInStatementInAsyncBody(node) {
  78554. return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
  78555. ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
  78556. : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
  78557. }
  78558. function visitForOfStatementInAsyncBody(node) {
  78559. return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
  78560. ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
  78561. : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
  78562. }
  78563. function visitForStatementInAsyncBody(node) {
  78564. var initializer = node.initializer; // TODO: GH#18217
  78565. return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
  78566. ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
  78567. : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
  78568. }
  78569. /**
  78570. * Visits an AwaitExpression node.
  78571. *
  78572. * This function will be called any time a ES2017 await expression is encountered.
  78573. *
  78574. * @param node The node to visit.
  78575. */
  78576. function visitAwaitExpression(node) {
  78577. // do not downlevel a top-level await as it is module syntax...
  78578. if (inTopLevelContext()) {
  78579. return ts.visitEachChild(node, visitor, context);
  78580. }
  78581. return ts.setOriginalNode(ts.setTextRange(ts.createYield(
  78582. /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
  78583. }
  78584. /**
  78585. * Visits a MethodDeclaration node.
  78586. *
  78587. * This function will be called when one of the following conditions are met:
  78588. * - The node is marked as async
  78589. *
  78590. * @param node The node to visit.
  78591. */
  78592. function visitMethodDeclaration(node) {
  78593. return ts.updateMethod(node,
  78594. /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
  78595. /*questionToken*/ undefined,
  78596. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  78597. /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
  78598. ? transformAsyncFunctionBody(node)
  78599. : ts.visitFunctionBody(node.body, visitor, context));
  78600. }
  78601. /**
  78602. * Visits a FunctionDeclaration node.
  78603. *
  78604. * This function will be called when one of the following conditions are met:
  78605. * - The node is marked async
  78606. *
  78607. * @param node The node to visit.
  78608. */
  78609. function visitFunctionDeclaration(node) {
  78610. return ts.updateFunctionDeclaration(node,
  78611. /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
  78612. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  78613. /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
  78614. ? transformAsyncFunctionBody(node)
  78615. : ts.visitFunctionBody(node.body, visitor, context));
  78616. }
  78617. /**
  78618. * Visits a FunctionExpression node.
  78619. *
  78620. * This function will be called when one of the following conditions are met:
  78621. * - The node is marked async
  78622. *
  78623. * @param node The node to visit.
  78624. */
  78625. function visitFunctionExpression(node) {
  78626. return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
  78627. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  78628. /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
  78629. ? transformAsyncFunctionBody(node)
  78630. : ts.visitFunctionBody(node.body, visitor, context));
  78631. }
  78632. /**
  78633. * Visits an ArrowFunction.
  78634. *
  78635. * This function will be called when one of the following conditions are met:
  78636. * - The node is marked async
  78637. *
  78638. * @param node The node to visit.
  78639. */
  78640. function visitArrowFunction(node) {
  78641. return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier),
  78642. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  78643. /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
  78644. ? transformAsyncFunctionBody(node)
  78645. : ts.visitFunctionBody(node.body, visitor, context));
  78646. }
  78647. function recordDeclarationName(_a, names) {
  78648. var name = _a.name;
  78649. if (ts.isIdentifier(name)) {
  78650. names.set(name.escapedText, true);
  78651. }
  78652. else {
  78653. for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
  78654. var element = _b[_i];
  78655. if (!ts.isOmittedExpression(element)) {
  78656. recordDeclarationName(element, names);
  78657. }
  78658. }
  78659. }
  78660. }
  78661. function isVariableDeclarationListWithCollidingName(node) {
  78662. return !!node
  78663. && ts.isVariableDeclarationList(node)
  78664. && !(node.flags & 3 /* BlockScoped */)
  78665. && node.declarations.some(collidesWithParameterName);
  78666. }
  78667. function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
  78668. hoistVariableDeclarationList(node);
  78669. var variables = ts.getInitializedVariables(node);
  78670. if (variables.length === 0) {
  78671. if (hasReceiver) {
  78672. return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
  78673. }
  78674. return undefined;
  78675. }
  78676. return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
  78677. }
  78678. function hoistVariableDeclarationList(node) {
  78679. ts.forEach(node.declarations, hoistVariable);
  78680. }
  78681. function hoistVariable(_a) {
  78682. var name = _a.name;
  78683. if (ts.isIdentifier(name)) {
  78684. hoistVariableDeclaration(name);
  78685. }
  78686. else {
  78687. for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
  78688. var element = _b[_i];
  78689. if (!ts.isOmittedExpression(element)) {
  78690. hoistVariable(element);
  78691. }
  78692. }
  78693. }
  78694. }
  78695. function transformInitializedVariable(node) {
  78696. var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
  78697. return ts.visitNode(converted, visitor, ts.isExpression);
  78698. }
  78699. function collidesWithParameterName(_a) {
  78700. var name = _a.name;
  78701. if (ts.isIdentifier(name)) {
  78702. return enclosingFunctionParameterNames.has(name.escapedText);
  78703. }
  78704. else {
  78705. for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
  78706. var element = _b[_i];
  78707. if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
  78708. return true;
  78709. }
  78710. }
  78711. }
  78712. return false;
  78713. }
  78714. function transformAsyncFunctionBody(node) {
  78715. resumeLexicalEnvironment();
  78716. var original = ts.getOriginalNode(node, ts.isFunctionLike);
  78717. var nodeType = original.type;
  78718. var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
  78719. var isArrowFunction = node.kind === 202 /* ArrowFunction */;
  78720. var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
  78721. // An async function is emit as an outer function that calls an inner
  78722. // generator function. To preserve lexical bindings, we pass the current
  78723. // `this` and `arguments` objects to `__awaiter`. The generator function
  78724. // passed to `__awaiter` is executed inside of the callback to the
  78725. // promise constructor.
  78726. var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
  78727. enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
  78728. for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
  78729. var parameter = _a[_i];
  78730. recordDeclarationName(parameter, enclosingFunctionParameterNames);
  78731. }
  78732. var savedCapturedSuperProperties = capturedSuperProperties;
  78733. var savedHasSuperElementAccess = hasSuperElementAccess;
  78734. if (!isArrowFunction) {
  78735. capturedSuperProperties = ts.createUnderscoreEscapedMap();
  78736. hasSuperElementAccess = false;
  78737. }
  78738. var result;
  78739. if (!isArrowFunction) {
  78740. var statements = [];
  78741. var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
  78742. statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
  78743. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  78744. // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
  78745. // This step isn't needed if we eventually transform this to ES5.
  78746. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
  78747. if (emitSuperHelpers) {
  78748. enableSubstitutionForAsyncMethodsWithSuper();
  78749. if (ts.hasEntries(capturedSuperProperties)) {
  78750. var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
  78751. substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
  78752. ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
  78753. }
  78754. }
  78755. var block = ts.createBlock(statements, /*multiLine*/ true);
  78756. ts.setTextRange(block, node.body);
  78757. if (emitSuperHelpers && hasSuperElementAccess) {
  78758. // Emit helpers for super element access expressions (`super[x]`).
  78759. if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
  78760. ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
  78761. }
  78762. else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
  78763. ts.addEmitHelper(block, ts.asyncSuperHelper);
  78764. }
  78765. }
  78766. result = block;
  78767. }
  78768. else {
  78769. var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
  78770. var declarations = endLexicalEnvironment();
  78771. if (ts.some(declarations)) {
  78772. var block = ts.convertToFunctionBody(expression);
  78773. result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
  78774. }
  78775. else {
  78776. result = expression;
  78777. }
  78778. }
  78779. enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
  78780. if (!isArrowFunction) {
  78781. capturedSuperProperties = savedCapturedSuperProperties;
  78782. hasSuperElementAccess = savedHasSuperElementAccess;
  78783. }
  78784. return result;
  78785. }
  78786. function transformAsyncFunctionBodyWorker(body, start) {
  78787. if (ts.isBlock(body)) {
  78788. return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
  78789. }
  78790. else {
  78791. return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
  78792. }
  78793. }
  78794. function getPromiseConstructor(type) {
  78795. var typeName = type && ts.getEntityNameFromTypeNode(type);
  78796. if (typeName && ts.isEntityName(typeName)) {
  78797. var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
  78798. if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
  78799. || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
  78800. return typeName;
  78801. }
  78802. }
  78803. return undefined;
  78804. }
  78805. function enableSubstitutionForAsyncMethodsWithSuper() {
  78806. if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
  78807. enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
  78808. // We need to enable substitutions for call, property access, and element access
  78809. // if we need to rewrite super calls.
  78810. context.enableSubstitution(196 /* CallExpression */);
  78811. context.enableSubstitution(194 /* PropertyAccessExpression */);
  78812. context.enableSubstitution(195 /* ElementAccessExpression */);
  78813. // We need to be notified when entering and exiting declarations that bind super.
  78814. context.enableEmitNotification(245 /* ClassDeclaration */);
  78815. context.enableEmitNotification(161 /* MethodDeclaration */);
  78816. context.enableEmitNotification(163 /* GetAccessor */);
  78817. context.enableEmitNotification(164 /* SetAccessor */);
  78818. context.enableEmitNotification(162 /* Constructor */);
  78819. // We need to be notified when entering the generated accessor arrow functions.
  78820. context.enableEmitNotification(225 /* VariableStatement */);
  78821. }
  78822. }
  78823. /**
  78824. * Hook for node emit.
  78825. *
  78826. * @param hint A hint as to the intended usage of the node.
  78827. * @param node The node to emit.
  78828. * @param emit A callback used to emit the node in the printer.
  78829. */
  78830. function onEmitNode(hint, node, emitCallback) {
  78831. // If we need to support substitutions for `super` in an async method,
  78832. // we should track it here.
  78833. if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
  78834. var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
  78835. if (superContainerFlags !== enclosingSuperContainerFlags) {
  78836. var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
  78837. enclosingSuperContainerFlags = superContainerFlags;
  78838. previousOnEmitNode(hint, node, emitCallback);
  78839. enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
  78840. return;
  78841. }
  78842. }
  78843. // Disable substitution in the generated super accessor itself.
  78844. else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
  78845. var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
  78846. enclosingSuperContainerFlags = 0;
  78847. previousOnEmitNode(hint, node, emitCallback);
  78848. enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
  78849. return;
  78850. }
  78851. previousOnEmitNode(hint, node, emitCallback);
  78852. }
  78853. /**
  78854. * Hooks node substitutions.
  78855. *
  78856. * @param hint A hint as to the intended usage of the node.
  78857. * @param node The node to substitute.
  78858. */
  78859. function onSubstituteNode(hint, node) {
  78860. node = previousOnSubstituteNode(hint, node);
  78861. if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
  78862. return substituteExpression(node);
  78863. }
  78864. return node;
  78865. }
  78866. function substituteExpression(node) {
  78867. switch (node.kind) {
  78868. case 194 /* PropertyAccessExpression */:
  78869. return substitutePropertyAccessExpression(node);
  78870. case 195 /* ElementAccessExpression */:
  78871. return substituteElementAccessExpression(node);
  78872. case 196 /* CallExpression */:
  78873. return substituteCallExpression(node);
  78874. }
  78875. return node;
  78876. }
  78877. function substitutePropertyAccessExpression(node) {
  78878. if (node.expression.kind === 102 /* SuperKeyword */) {
  78879. return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
  78880. }
  78881. return node;
  78882. }
  78883. function substituteElementAccessExpression(node) {
  78884. if (node.expression.kind === 102 /* SuperKeyword */) {
  78885. return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
  78886. }
  78887. return node;
  78888. }
  78889. function substituteCallExpression(node) {
  78890. var expression = node.expression;
  78891. if (ts.isSuperProperty(expression)) {
  78892. var argumentExpression = ts.isPropertyAccessExpression(expression)
  78893. ? substitutePropertyAccessExpression(expression)
  78894. : substituteElementAccessExpression(expression);
  78895. return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
  78896. /*typeArguments*/ undefined, __spreadArrays([
  78897. ts.createThis()
  78898. ], node.arguments));
  78899. }
  78900. return node;
  78901. }
  78902. function isSuperContainer(node) {
  78903. var kind = node.kind;
  78904. return kind === 245 /* ClassDeclaration */
  78905. || kind === 162 /* Constructor */
  78906. || kind === 161 /* MethodDeclaration */
  78907. || kind === 163 /* GetAccessor */
  78908. || kind === 164 /* SetAccessor */;
  78909. }
  78910. function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
  78911. if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
  78912. return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"),
  78913. /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
  78914. }
  78915. else {
  78916. return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"),
  78917. /*typeArguments*/ undefined, [argumentExpression]), location);
  78918. }
  78919. }
  78920. }
  78921. ts.transformES2017 = transformES2017;
  78922. /** Creates a variable named `_super` with accessor properties for the given property names. */
  78923. function createSuperAccessVariableStatement(resolver, node, names) {
  78924. // Create a variable declaration with a getter/setter (if binding) definition for each name:
  78925. // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
  78926. var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
  78927. var accessors = [];
  78928. names.forEach(function (_, key) {
  78929. var name = ts.unescapeLeadingUnderscores(key);
  78930. var getterAndSetter = [];
  78931. getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
  78932. /* modifiers */ undefined,
  78933. /* typeParameters */ undefined,
  78934. /* parameters */ [],
  78935. /* type */ undefined,
  78936. /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
  78937. if (hasBinding) {
  78938. getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
  78939. /* modifiers */ undefined,
  78940. /* typeParameters */ undefined,
  78941. /* parameters */ [
  78942. ts.createParameter(
  78943. /* decorators */ undefined,
  78944. /* modifiers */ undefined,
  78945. /* dotDotDotToken */ undefined, "v",
  78946. /* questionToken */ undefined,
  78947. /* type */ undefined,
  78948. /* initializer */ undefined)
  78949. ],
  78950. /* type */ undefined,
  78951. /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
  78952. }
  78953. accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
  78954. });
  78955. return ts.createVariableStatement(
  78956. /* modifiers */ undefined, ts.createVariableDeclarationList([
  78957. ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"),
  78958. /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"),
  78959. /* typeArguments */ undefined, [
  78960. ts.createNull(),
  78961. ts.createObjectLiteral(accessors, /* multiline */ true)
  78962. ]))
  78963. ], 2 /* Const */));
  78964. }
  78965. ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
  78966. ts.awaiterHelper = {
  78967. name: "typescript:awaiter",
  78968. importName: "__awaiter",
  78969. scoped: false,
  78970. priority: 5,
  78971. text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
  78972. };
  78973. function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
  78974. context.requestEmitHelper(ts.awaiterHelper);
  78975. var generatorFunc = ts.createFunctionExpression(
  78976. /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */),
  78977. /*name*/ undefined,
  78978. /*typeParameters*/ undefined,
  78979. /*parameters*/ [],
  78980. /*type*/ undefined, body);
  78981. // Mark this node as originally an async function
  78982. (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
  78983. return ts.createCall(ts.getUnscopedHelperName("__awaiter"),
  78984. /*typeArguments*/ undefined, [
  78985. hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
  78986. hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
  78987. promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
  78988. generatorFunc
  78989. ]);
  78990. }
  78991. ts.asyncSuperHelper = {
  78992. name: "typescript:async-super",
  78993. scoped: true,
  78994. text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex")
  78995. };
  78996. ts.advancedAsyncSuperHelper = {
  78997. name: "typescript:advanced-async-super",
  78998. scoped: true,
  78999. text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex")
  79000. };
  79001. })(ts || (ts = {}));
  79002. /*@internal*/
  79003. var ts;
  79004. (function (ts) {
  79005. var ESNextSubstitutionFlags;
  79006. (function (ESNextSubstitutionFlags) {
  79007. /** Enables substitutions for async methods with `super` calls. */
  79008. ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
  79009. })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
  79010. function transformES2018(context) {
  79011. var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
  79012. var resolver = context.getEmitResolver();
  79013. var compilerOptions = context.getCompilerOptions();
  79014. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  79015. var previousOnEmitNode = context.onEmitNode;
  79016. context.onEmitNode = onEmitNode;
  79017. var previousOnSubstituteNode = context.onSubstituteNode;
  79018. context.onSubstituteNode = onSubstituteNode;
  79019. var exportedVariableStatement = false;
  79020. var enabledSubstitutions;
  79021. var enclosingFunctionFlags;
  79022. var enclosingSuperContainerFlags = 0;
  79023. var hasLexicalThis;
  79024. /** Keeps track of property names accessed on super (`super.x`) within async functions. */
  79025. var capturedSuperProperties;
  79026. /** Whether the async function contains an element access on super (`super[x]`). */
  79027. var hasSuperElementAccess;
  79028. /** A set of node IDs for generated super accessors. */
  79029. var substitutedSuperAccessors = [];
  79030. return ts.chainBundle(transformSourceFile);
  79031. function transformSourceFile(node) {
  79032. if (node.isDeclarationFile) {
  79033. return node;
  79034. }
  79035. exportedVariableStatement = false;
  79036. hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions);
  79037. var visited = ts.visitEachChild(node, visitor, context);
  79038. ts.addEmitHelpers(visited, context.readEmitHelpers());
  79039. return visited;
  79040. }
  79041. function visitor(node) {
  79042. return visitorWorker(node, /*noDestructuringValue*/ false);
  79043. }
  79044. function visitorNoDestructuringValue(node) {
  79045. return visitorWorker(node, /*noDestructuringValue*/ true);
  79046. }
  79047. function visitorNoAsyncModifier(node) {
  79048. if (node.kind === 126 /* AsyncKeyword */) {
  79049. return undefined;
  79050. }
  79051. return node;
  79052. }
  79053. function doWithLexicalThis(cb, value) {
  79054. if (!hasLexicalThis) {
  79055. hasLexicalThis = true;
  79056. var result = cb(value);
  79057. hasLexicalThis = false;
  79058. return result;
  79059. }
  79060. return cb(value);
  79061. }
  79062. function visitDefault(node) {
  79063. return ts.visitEachChild(node, visitor, context);
  79064. }
  79065. function visitorWorker(node, noDestructuringValue) {
  79066. if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
  79067. return node;
  79068. }
  79069. switch (node.kind) {
  79070. case 206 /* AwaitExpression */:
  79071. return visitAwaitExpression(node);
  79072. case 212 /* YieldExpression */:
  79073. return visitYieldExpression(node);
  79074. case 235 /* ReturnStatement */:
  79075. return visitReturnStatement(node);
  79076. case 238 /* LabeledStatement */:
  79077. return visitLabeledStatement(node);
  79078. case 193 /* ObjectLiteralExpression */:
  79079. return visitObjectLiteralExpression(node);
  79080. case 209 /* BinaryExpression */:
  79081. return visitBinaryExpression(node, noDestructuringValue);
  79082. case 280 /* CatchClause */:
  79083. return visitCatchClause(node);
  79084. case 225 /* VariableStatement */:
  79085. return visitVariableStatement(node);
  79086. case 242 /* VariableDeclaration */:
  79087. return visitVariableDeclaration(node);
  79088. case 232 /* ForOfStatement */:
  79089. return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
  79090. case 230 /* ForStatement */:
  79091. return visitForStatement(node);
  79092. case 205 /* VoidExpression */:
  79093. return visitVoidExpression(node);
  79094. case 162 /* Constructor */:
  79095. return doWithLexicalThis(visitConstructorDeclaration, node);
  79096. case 161 /* MethodDeclaration */:
  79097. return doWithLexicalThis(visitMethodDeclaration, node);
  79098. case 163 /* GetAccessor */:
  79099. return doWithLexicalThis(visitGetAccessorDeclaration, node);
  79100. case 164 /* SetAccessor */:
  79101. return doWithLexicalThis(visitSetAccessorDeclaration, node);
  79102. case 244 /* FunctionDeclaration */:
  79103. return doWithLexicalThis(visitFunctionDeclaration, node);
  79104. case 201 /* FunctionExpression */:
  79105. return doWithLexicalThis(visitFunctionExpression, node);
  79106. case 202 /* ArrowFunction */:
  79107. return visitArrowFunction(node);
  79108. case 156 /* Parameter */:
  79109. return visitParameter(node);
  79110. case 226 /* ExpressionStatement */:
  79111. return visitExpressionStatement(node);
  79112. case 200 /* ParenthesizedExpression */:
  79113. return visitParenthesizedExpression(node, noDestructuringValue);
  79114. case 194 /* PropertyAccessExpression */:
  79115. if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
  79116. capturedSuperProperties.set(node.name.escapedText, true);
  79117. }
  79118. return ts.visitEachChild(node, visitor, context);
  79119. case 195 /* ElementAccessExpression */:
  79120. if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
  79121. hasSuperElementAccess = true;
  79122. }
  79123. return ts.visitEachChild(node, visitor, context);
  79124. case 245 /* ClassDeclaration */:
  79125. case 214 /* ClassExpression */:
  79126. return doWithLexicalThis(visitDefault, node);
  79127. default:
  79128. return ts.visitEachChild(node, visitor, context);
  79129. }
  79130. }
  79131. function visitAwaitExpression(node) {
  79132. if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
  79133. return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))),
  79134. /*location*/ node), node);
  79135. }
  79136. return ts.visitEachChild(node, visitor, context);
  79137. }
  79138. function visitYieldExpression(node) {
  79139. if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
  79140. if (node.asteriskToken) {
  79141. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  79142. return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
  79143. }
  79144. return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
  79145. ? ts.visitNode(node.expression, visitor, ts.isExpression)
  79146. : ts.createVoidZero())), node), node);
  79147. }
  79148. return ts.visitEachChild(node, visitor, context);
  79149. }
  79150. function visitReturnStatement(node) {
  79151. if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
  79152. return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
  79153. }
  79154. return ts.visitEachChild(node, visitor, context);
  79155. }
  79156. function visitLabeledStatement(node) {
  79157. if (enclosingFunctionFlags & 2 /* Async */) {
  79158. var statement = ts.unwrapInnermostStatementOfLabel(node);
  79159. if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
  79160. return visitForOfStatement(statement, node);
  79161. }
  79162. return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node);
  79163. }
  79164. return ts.visitEachChild(node, visitor, context);
  79165. }
  79166. function chunkObjectLiteralElements(elements) {
  79167. var chunkObject;
  79168. var objects = [];
  79169. for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
  79170. var e = elements_4[_i];
  79171. if (e.kind === 283 /* SpreadAssignment */) {
  79172. if (chunkObject) {
  79173. objects.push(ts.createObjectLiteral(chunkObject));
  79174. chunkObject = undefined;
  79175. }
  79176. var target = e.expression;
  79177. objects.push(ts.visitNode(target, visitor, ts.isExpression));
  79178. }
  79179. else {
  79180. chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
  79181. ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
  79182. : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
  79183. }
  79184. }
  79185. if (chunkObject) {
  79186. objects.push(ts.createObjectLiteral(chunkObject));
  79187. }
  79188. return objects;
  79189. }
  79190. function visitObjectLiteralExpression(node) {
  79191. if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79192. // spread elements emit like so:
  79193. // non-spread elements are chunked together into object literals, and then all are passed to __assign:
  79194. // { a, ...o, b } => __assign(__assign({a}, o), {b});
  79195. // If the first element is a spread element, then the first argument to __assign is {}:
  79196. // { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
  79197. //
  79198. // We cannot call __assign with more than two elements, since any element could cause side effects. For
  79199. // example:
  79200. // var k = { a: 1, b: 2 };
  79201. // var o = { a: 3, ...k, b: k.a++ };
  79202. // // expected: { a: 1, b: 1 }
  79203. // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
  79204. // `k` is spread and we end up with `{ a: 2, b: 1 }`.
  79205. //
  79206. // This also occurs for spread elements, not just property assignments:
  79207. // var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
  79208. // var l = { c: 3 };
  79209. // var o = { ...k, ...l };
  79210. // // expected: { a: 1, b: 2, z: 9 }
  79211. // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
  79212. // end up with `{ a: 1, b: 2, c: 3 }`
  79213. var objects = chunkObjectLiteralElements(node.properties);
  79214. if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
  79215. objects.unshift(ts.createObjectLiteral());
  79216. }
  79217. var expression = objects[0];
  79218. if (objects.length > 1) {
  79219. for (var i = 1; i < objects.length; i++) {
  79220. expression = createAssignHelper(context, [expression, objects[i]]);
  79221. }
  79222. return expression;
  79223. }
  79224. else {
  79225. return createAssignHelper(context, objects);
  79226. }
  79227. }
  79228. return ts.visitEachChild(node, visitor, context);
  79229. }
  79230. function visitExpressionStatement(node) {
  79231. return ts.visitEachChild(node, visitorNoDestructuringValue, context);
  79232. }
  79233. function visitParenthesizedExpression(node, noDestructuringValue) {
  79234. return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
  79235. }
  79236. /**
  79237. * Visits a BinaryExpression that contains a destructuring assignment.
  79238. *
  79239. * @param node A BinaryExpression node.
  79240. */
  79241. function visitBinaryExpression(node, noDestructuringValue) {
  79242. if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79243. return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
  79244. }
  79245. else if (node.operatorToken.kind === 27 /* CommaToken */) {
  79246. return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
  79247. }
  79248. return ts.visitEachChild(node, visitor, context);
  79249. }
  79250. function visitCatchClause(node) {
  79251. if (node.variableDeclaration &&
  79252. ts.isBindingPattern(node.variableDeclaration.name) &&
  79253. node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79254. var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
  79255. var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
  79256. var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
  79257. var block = ts.visitNode(node.block, visitor, ts.isBlock);
  79258. if (ts.some(visitedBindings)) {
  79259. block = ts.updateBlock(block, __spreadArrays([
  79260. ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
  79261. ], block.statements));
  79262. }
  79263. return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
  79264. }
  79265. return ts.visitEachChild(node, visitor, context);
  79266. }
  79267. function visitVariableStatement(node) {
  79268. if (ts.hasModifier(node, 1 /* Export */)) {
  79269. var savedExportedVariableStatement = exportedVariableStatement;
  79270. exportedVariableStatement = true;
  79271. var visited = ts.visitEachChild(node, visitor, context);
  79272. exportedVariableStatement = savedExportedVariableStatement;
  79273. return visited;
  79274. }
  79275. return ts.visitEachChild(node, visitor, context);
  79276. }
  79277. /**
  79278. * Visits a VariableDeclaration node with a binding pattern.
  79279. *
  79280. * @param node A VariableDeclaration node.
  79281. */
  79282. function visitVariableDeclaration(node) {
  79283. if (exportedVariableStatement) {
  79284. var savedExportedVariableStatement = exportedVariableStatement;
  79285. exportedVariableStatement = false;
  79286. var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
  79287. exportedVariableStatement = savedExportedVariableStatement;
  79288. return visited;
  79289. }
  79290. return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
  79291. }
  79292. function visitVariableDeclarationWorker(node, exportedVariableStatement) {
  79293. // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
  79294. if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79295. return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */,
  79296. /*rval*/ undefined, exportedVariableStatement);
  79297. }
  79298. return ts.visitEachChild(node, visitor, context);
  79299. }
  79300. function visitForStatement(node) {
  79301. return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
  79302. }
  79303. function visitVoidExpression(node) {
  79304. return ts.visitEachChild(node, visitorNoDestructuringValue, context);
  79305. }
  79306. /**
  79307. * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
  79308. *
  79309. * @param node A ForOfStatement.
  79310. */
  79311. function visitForOfStatement(node, outermostLabeledStatement) {
  79312. if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79313. node = transformForOfStatementWithObjectRest(node);
  79314. }
  79315. if (node.awaitModifier) {
  79316. return transformForAwaitOfStatement(node, outermostLabeledStatement);
  79317. }
  79318. else {
  79319. return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
  79320. }
  79321. }
  79322. function transformForOfStatementWithObjectRest(node) {
  79323. var initializerWithoutParens = ts.skipParentheses(node.initializer);
  79324. if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
  79325. var bodyLocation = void 0;
  79326. var statementsLocation = void 0;
  79327. var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
  79328. var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
  79329. if (ts.isBlock(node.statement)) {
  79330. ts.addRange(statements, node.statement.statements);
  79331. bodyLocation = node.statement;
  79332. statementsLocation = node.statement.statements;
  79333. }
  79334. else if (node.statement) {
  79335. ts.append(statements, node.statement);
  79336. bodyLocation = node.statement;
  79337. statementsLocation = node.statement;
  79338. }
  79339. return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
  79340. ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
  79341. ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
  79342. /*multiLine*/ true), bodyLocation));
  79343. }
  79344. return node;
  79345. }
  79346. function convertForOfStatementHead(node, boundValue) {
  79347. var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
  79348. var bodyLocation;
  79349. var statementsLocation;
  79350. var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
  79351. var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
  79352. if (ts.isBlock(statement)) {
  79353. ts.addRange(statements, statement.statements);
  79354. bodyLocation = statement;
  79355. statementsLocation = statement.statements;
  79356. }
  79357. else {
  79358. statements.push(statement);
  79359. }
  79360. return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
  79361. /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
  79362. }
  79363. function createDownlevelAwait(expression) {
  79364. return enclosingFunctionFlags & 1 /* Generator */
  79365. ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
  79366. : ts.createAwait(expression);
  79367. }
  79368. function transformForAwaitOfStatement(node, outermostLabeledStatement) {
  79369. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  79370. var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
  79371. var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
  79372. var errorRecord = ts.createUniqueName("e");
  79373. var catchVariable = ts.getGeneratedNameForNode(errorRecord);
  79374. var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
  79375. var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
  79376. var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
  79377. var getDone = ts.createPropertyAccess(result, "done");
  79378. var getValue = ts.createPropertyAccess(result, "value");
  79379. var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
  79380. hoistVariableDeclaration(errorRecord);
  79381. hoistVariableDeclaration(returnMethod);
  79382. var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
  79383. /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
  79384. ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression),
  79385. ts.createVariableDeclaration(result)
  79386. ]), node.expression), 2097152 /* NoHoisting */),
  79387. /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)),
  79388. /*incrementor*/ undefined,
  79389. /*statement*/ convertForOfStatementHead(node, getValue)),
  79390. /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
  79391. return ts.createTry(ts.createBlock([
  79392. ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
  79393. ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
  79394. ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
  79395. ts.createPropertyAssignment("error", catchVariable)
  79396. ])))
  79397. ]), 1 /* SingleLine */)), ts.createBlock([
  79398. ts.createTry(
  79399. /*tryBlock*/ ts.createBlock([
  79400. ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
  79401. ]),
  79402. /*catchClause*/ undefined,
  79403. /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
  79404. ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
  79405. ]), 1 /* SingleLine */))
  79406. ]));
  79407. }
  79408. function visitParameter(node) {
  79409. if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79410. // Binding patterns are converted into a generated name and are
  79411. // evaluated inside the function body.
  79412. return ts.updateParameter(node,
  79413. /*decorators*/ undefined,
  79414. /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node),
  79415. /*questionToken*/ undefined,
  79416. /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
  79417. }
  79418. return ts.visitEachChild(node, visitor, context);
  79419. }
  79420. function visitConstructorDeclaration(node) {
  79421. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79422. enclosingFunctionFlags = 0 /* Normal */;
  79423. var updated = ts.updateConstructor(node,
  79424. /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
  79425. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79426. return updated;
  79427. }
  79428. function visitGetAccessorDeclaration(node) {
  79429. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79430. enclosingFunctionFlags = 0 /* Normal */;
  79431. var updated = ts.updateGetAccessor(node,
  79432. /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context),
  79433. /*type*/ undefined, transformFunctionBody(node));
  79434. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79435. return updated;
  79436. }
  79437. function visitSetAccessorDeclaration(node) {
  79438. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79439. enclosingFunctionFlags = 0 /* Normal */;
  79440. var updated = ts.updateSetAccessor(node,
  79441. /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
  79442. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79443. return updated;
  79444. }
  79445. function visitMethodDeclaration(node) {
  79446. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79447. enclosingFunctionFlags = ts.getFunctionFlags(node);
  79448. var updated = ts.updateMethod(node,
  79449. /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
  79450. ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
  79451. : node.modifiers, enclosingFunctionFlags & 2 /* Async */
  79452. ? undefined
  79453. : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken),
  79454. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  79455. /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
  79456. ? transformAsyncGeneratorFunctionBody(node)
  79457. : transformFunctionBody(node));
  79458. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79459. return updated;
  79460. }
  79461. function visitFunctionDeclaration(node) {
  79462. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79463. enclosingFunctionFlags = ts.getFunctionFlags(node);
  79464. var updated = ts.updateFunctionDeclaration(node,
  79465. /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
  79466. ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
  79467. : node.modifiers, enclosingFunctionFlags & 2 /* Async */
  79468. ? undefined
  79469. : node.asteriskToken, node.name,
  79470. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  79471. /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
  79472. ? transformAsyncGeneratorFunctionBody(node)
  79473. : transformFunctionBody(node));
  79474. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79475. return updated;
  79476. }
  79477. function visitArrowFunction(node) {
  79478. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79479. enclosingFunctionFlags = ts.getFunctionFlags(node);
  79480. var updated = ts.updateArrowFunction(node, node.modifiers,
  79481. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  79482. /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
  79483. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79484. return updated;
  79485. }
  79486. function visitFunctionExpression(node) {
  79487. var savedEnclosingFunctionFlags = enclosingFunctionFlags;
  79488. enclosingFunctionFlags = ts.getFunctionFlags(node);
  79489. var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
  79490. ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
  79491. : node.modifiers, enclosingFunctionFlags & 2 /* Async */
  79492. ? undefined
  79493. : node.asteriskToken, node.name,
  79494. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  79495. /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
  79496. ? transformAsyncGeneratorFunctionBody(node)
  79497. : transformFunctionBody(node));
  79498. enclosingFunctionFlags = savedEnclosingFunctionFlags;
  79499. return updated;
  79500. }
  79501. function transformAsyncGeneratorFunctionBody(node) {
  79502. resumeLexicalEnvironment();
  79503. var statements = [];
  79504. var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
  79505. appendObjectRestAssignmentsIfNeeded(statements, node);
  79506. var savedCapturedSuperProperties = capturedSuperProperties;
  79507. var savedHasSuperElementAccess = hasSuperElementAccess;
  79508. capturedSuperProperties = ts.createUnderscoreEscapedMap();
  79509. hasSuperElementAccess = false;
  79510. var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
  79511. /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name),
  79512. /*typeParameters*/ undefined,
  79513. /*parameters*/ [],
  79514. /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis));
  79515. // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
  79516. // This step isn't needed if we eventually transform this to ES5.
  79517. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
  79518. if (emitSuperHelpers) {
  79519. enableSubstitutionForAsyncMethodsWithSuper();
  79520. var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
  79521. substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
  79522. ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
  79523. }
  79524. statements.push(returnStatement);
  79525. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  79526. var block = ts.updateBlock(node.body, statements);
  79527. if (emitSuperHelpers && hasSuperElementAccess) {
  79528. if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
  79529. ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
  79530. }
  79531. else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
  79532. ts.addEmitHelper(block, ts.asyncSuperHelper);
  79533. }
  79534. }
  79535. capturedSuperProperties = savedCapturedSuperProperties;
  79536. hasSuperElementAccess = savedHasSuperElementAccess;
  79537. return block;
  79538. }
  79539. function transformFunctionBody(node) {
  79540. resumeLexicalEnvironment();
  79541. var statementOffset = 0;
  79542. var statements = [];
  79543. var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
  79544. if (ts.isBlock(body)) {
  79545. statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
  79546. }
  79547. ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
  79548. var leadingStatements = endLexicalEnvironment();
  79549. if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
  79550. var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
  79551. ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
  79552. ts.addRange(statements, block.statements.slice(statementOffset));
  79553. return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
  79554. }
  79555. return body;
  79556. }
  79557. function appendObjectRestAssignmentsIfNeeded(statements, node) {
  79558. for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
  79559. var parameter = _a[_i];
  79560. if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
  79561. var temp = ts.getGeneratedNameForNode(parameter);
  79562. var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
  79563. /*doNotRecordTempVariablesInLine*/ false,
  79564. /*skipInitializer*/ true);
  79565. if (ts.some(declarations)) {
  79566. var statement = ts.createVariableStatement(
  79567. /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
  79568. ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
  79569. statements = ts.append(statements, statement);
  79570. }
  79571. }
  79572. }
  79573. return statements;
  79574. }
  79575. function enableSubstitutionForAsyncMethodsWithSuper() {
  79576. if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
  79577. enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
  79578. // We need to enable substitutions for call, property access, and element access
  79579. // if we need to rewrite super calls.
  79580. context.enableSubstitution(196 /* CallExpression */);
  79581. context.enableSubstitution(194 /* PropertyAccessExpression */);
  79582. context.enableSubstitution(195 /* ElementAccessExpression */);
  79583. // We need to be notified when entering and exiting declarations that bind super.
  79584. context.enableEmitNotification(245 /* ClassDeclaration */);
  79585. context.enableEmitNotification(161 /* MethodDeclaration */);
  79586. context.enableEmitNotification(163 /* GetAccessor */);
  79587. context.enableEmitNotification(164 /* SetAccessor */);
  79588. context.enableEmitNotification(162 /* Constructor */);
  79589. // We need to be notified when entering the generated accessor arrow functions.
  79590. context.enableEmitNotification(225 /* VariableStatement */);
  79591. }
  79592. }
  79593. /**
  79594. * Called by the printer just before a node is printed.
  79595. *
  79596. * @param hint A hint as to the intended usage of the node.
  79597. * @param node The node to be printed.
  79598. * @param emitCallback The callback used to emit the node.
  79599. */
  79600. function onEmitNode(hint, node, emitCallback) {
  79601. // If we need to support substitutions for `super` in an async method,
  79602. // we should track it here.
  79603. if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
  79604. var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
  79605. if (superContainerFlags !== enclosingSuperContainerFlags) {
  79606. var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
  79607. enclosingSuperContainerFlags = superContainerFlags;
  79608. previousOnEmitNode(hint, node, emitCallback);
  79609. enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
  79610. return;
  79611. }
  79612. }
  79613. // Disable substitution in the generated super accessor itself.
  79614. else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
  79615. var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
  79616. enclosingSuperContainerFlags = 0;
  79617. previousOnEmitNode(hint, node, emitCallback);
  79618. enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
  79619. return;
  79620. }
  79621. previousOnEmitNode(hint, node, emitCallback);
  79622. }
  79623. /**
  79624. * Hooks node substitutions.
  79625. *
  79626. * @param hint The context for the emitter.
  79627. * @param node The node to substitute.
  79628. */
  79629. function onSubstituteNode(hint, node) {
  79630. node = previousOnSubstituteNode(hint, node);
  79631. if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
  79632. return substituteExpression(node);
  79633. }
  79634. return node;
  79635. }
  79636. function substituteExpression(node) {
  79637. switch (node.kind) {
  79638. case 194 /* PropertyAccessExpression */:
  79639. return substitutePropertyAccessExpression(node);
  79640. case 195 /* ElementAccessExpression */:
  79641. return substituteElementAccessExpression(node);
  79642. case 196 /* CallExpression */:
  79643. return substituteCallExpression(node);
  79644. }
  79645. return node;
  79646. }
  79647. function substitutePropertyAccessExpression(node) {
  79648. if (node.expression.kind === 102 /* SuperKeyword */) {
  79649. return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
  79650. }
  79651. return node;
  79652. }
  79653. function substituteElementAccessExpression(node) {
  79654. if (node.expression.kind === 102 /* SuperKeyword */) {
  79655. return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
  79656. }
  79657. return node;
  79658. }
  79659. function substituteCallExpression(node) {
  79660. var expression = node.expression;
  79661. if (ts.isSuperProperty(expression)) {
  79662. var argumentExpression = ts.isPropertyAccessExpression(expression)
  79663. ? substitutePropertyAccessExpression(expression)
  79664. : substituteElementAccessExpression(expression);
  79665. return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
  79666. /*typeArguments*/ undefined, __spreadArrays([
  79667. ts.createThis()
  79668. ], node.arguments));
  79669. }
  79670. return node;
  79671. }
  79672. function isSuperContainer(node) {
  79673. var kind = node.kind;
  79674. return kind === 245 /* ClassDeclaration */
  79675. || kind === 162 /* Constructor */
  79676. || kind === 161 /* MethodDeclaration */
  79677. || kind === 163 /* GetAccessor */
  79678. || kind === 164 /* SetAccessor */;
  79679. }
  79680. function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
  79681. if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
  79682. return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"),
  79683. /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
  79684. }
  79685. else {
  79686. return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"),
  79687. /*typeArguments*/ undefined, [argumentExpression]), location);
  79688. }
  79689. }
  79690. }
  79691. ts.transformES2018 = transformES2018;
  79692. ts.assignHelper = {
  79693. name: "typescript:assign",
  79694. importName: "__assign",
  79695. scoped: false,
  79696. priority: 1,
  79697. text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };"
  79698. };
  79699. function createAssignHelper(context, attributesSegments) {
  79700. if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
  79701. return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
  79702. }
  79703. context.requestEmitHelper(ts.assignHelper);
  79704. return ts.createCall(ts.getUnscopedHelperName("__assign"),
  79705. /*typeArguments*/ undefined, attributesSegments);
  79706. }
  79707. ts.createAssignHelper = createAssignHelper;
  79708. ts.awaitHelper = {
  79709. name: "typescript:await",
  79710. importName: "__await",
  79711. scoped: false,
  79712. text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
  79713. };
  79714. function createAwaitHelper(context, expression) {
  79715. context.requestEmitHelper(ts.awaitHelper);
  79716. return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
  79717. }
  79718. ts.asyncGeneratorHelper = {
  79719. name: "typescript:asyncGenerator",
  79720. importName: "__asyncGenerator",
  79721. scoped: false,
  79722. text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
  79723. };
  79724. function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
  79725. context.requestEmitHelper(ts.awaitHelper);
  79726. context.requestEmitHelper(ts.asyncGeneratorHelper);
  79727. // Mark this node as originally an async function
  79728. (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
  79729. return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"),
  79730. /*typeArguments*/ undefined, [
  79731. hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
  79732. ts.createIdentifier("arguments"),
  79733. generatorFunc
  79734. ]);
  79735. }
  79736. ts.asyncDelegator = {
  79737. name: "typescript:asyncDelegator",
  79738. importName: "__asyncDelegator",
  79739. scoped: false,
  79740. text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
  79741. };
  79742. function createAsyncDelegatorHelper(context, expression, location) {
  79743. context.requestEmitHelper(ts.awaitHelper);
  79744. context.requestEmitHelper(ts.asyncDelegator);
  79745. return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"),
  79746. /*typeArguments*/ undefined, [expression]), location);
  79747. }
  79748. ts.asyncValues = {
  79749. name: "typescript:asyncValues",
  79750. importName: "__asyncValues",
  79751. scoped: false,
  79752. text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
  79753. };
  79754. function createAsyncValuesHelper(context, expression, location) {
  79755. context.requestEmitHelper(ts.asyncValues);
  79756. return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"),
  79757. /*typeArguments*/ undefined, [expression]), location);
  79758. }
  79759. })(ts || (ts = {}));
  79760. /*@internal*/
  79761. var ts;
  79762. (function (ts) {
  79763. function transformES2019(context) {
  79764. return ts.chainBundle(transformSourceFile);
  79765. function transformSourceFile(node) {
  79766. if (node.isDeclarationFile) {
  79767. return node;
  79768. }
  79769. return ts.visitEachChild(node, visitor, context);
  79770. }
  79771. function visitor(node) {
  79772. if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
  79773. return node;
  79774. }
  79775. switch (node.kind) {
  79776. case 280 /* CatchClause */:
  79777. return visitCatchClause(node);
  79778. default:
  79779. return ts.visitEachChild(node, visitor, context);
  79780. }
  79781. }
  79782. function visitCatchClause(node) {
  79783. if (!node.variableDeclaration) {
  79784. return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
  79785. }
  79786. return ts.visitEachChild(node, visitor, context);
  79787. }
  79788. }
  79789. ts.transformES2019 = transformES2019;
  79790. })(ts || (ts = {}));
  79791. /*@internal*/
  79792. var ts;
  79793. (function (ts) {
  79794. function transformES2020(context) {
  79795. var hoistVariableDeclaration = context.hoistVariableDeclaration;
  79796. return ts.chainBundle(transformSourceFile);
  79797. function transformSourceFile(node) {
  79798. if (node.isDeclarationFile) {
  79799. return node;
  79800. }
  79801. return ts.visitEachChild(node, visitor, context);
  79802. }
  79803. function visitor(node) {
  79804. if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
  79805. return node;
  79806. }
  79807. switch (node.kind) {
  79808. case 194 /* PropertyAccessExpression */:
  79809. case 195 /* ElementAccessExpression */:
  79810. case 196 /* CallExpression */:
  79811. if (node.flags & 32 /* OptionalChain */) {
  79812. var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
  79813. ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
  79814. return updated;
  79815. }
  79816. return ts.visitEachChild(node, visitor, context);
  79817. case 209 /* BinaryExpression */:
  79818. if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
  79819. return transformNullishCoalescingExpression(node);
  79820. }
  79821. return ts.visitEachChild(node, visitor, context);
  79822. case 203 /* DeleteExpression */:
  79823. return visitDeleteExpression(node);
  79824. default:
  79825. return ts.visitEachChild(node, visitor, context);
  79826. }
  79827. }
  79828. function flattenChain(chain) {
  79829. var links = [chain];
  79830. while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
  79831. chain = ts.cast(chain.expression, ts.isOptionalChain);
  79832. links.unshift(chain);
  79833. }
  79834. return { expression: chain.expression, chain: links };
  79835. }
  79836. function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
  79837. var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
  79838. if (ts.isSyntheticReference(expression)) {
  79839. // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
  79840. // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
  79841. return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
  79842. }
  79843. return ts.updateParen(node, expression);
  79844. }
  79845. function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
  79846. if (ts.isOptionalChain(node)) {
  79847. // If `node` is an optional chain, then it is the outermost chain of an optional expression.
  79848. return visitOptionalExpression(node, captureThisArg, isDelete);
  79849. }
  79850. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  79851. ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
  79852. var thisArg;
  79853. if (captureThisArg) {
  79854. if (shouldCaptureInTempVariable(expression)) {
  79855. thisArg = ts.createTempVariable(hoistVariableDeclaration);
  79856. expression = ts.createAssignment(thisArg, expression);
  79857. }
  79858. else {
  79859. thisArg = expression;
  79860. }
  79861. }
  79862. expression = node.kind === 194 /* PropertyAccessExpression */
  79863. ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
  79864. : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
  79865. return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
  79866. }
  79867. function visitNonOptionalCallExpression(node, captureThisArg) {
  79868. if (ts.isOptionalChain(node)) {
  79869. // If `node` is an optional chain, then it is the outermost chain of an optional expression.
  79870. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
  79871. }
  79872. return ts.visitEachChild(node, visitor, context);
  79873. }
  79874. function visitNonOptionalExpression(node, captureThisArg, isDelete) {
  79875. switch (node.kind) {
  79876. case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
  79877. case 194 /* PropertyAccessExpression */:
  79878. case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
  79879. case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
  79880. default: return ts.visitNode(node, visitor, ts.isExpression);
  79881. }
  79882. }
  79883. function visitOptionalExpression(node, captureThisArg, isDelete) {
  79884. var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
  79885. var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
  79886. var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
  79887. var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
  79888. var capturedLeft = leftExpression;
  79889. if (shouldCaptureInTempVariable(leftExpression)) {
  79890. capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
  79891. leftExpression = ts.createAssignment(capturedLeft, leftExpression);
  79892. }
  79893. var rightExpression = capturedLeft;
  79894. var thisArg;
  79895. for (var i = 0; i < chain.length; i++) {
  79896. var segment = chain[i];
  79897. switch (segment.kind) {
  79898. case 194 /* PropertyAccessExpression */:
  79899. case 195 /* ElementAccessExpression */:
  79900. if (i === chain.length - 1 && captureThisArg) {
  79901. if (shouldCaptureInTempVariable(rightExpression)) {
  79902. thisArg = ts.createTempVariable(hoistVariableDeclaration);
  79903. rightExpression = ts.createAssignment(thisArg, rightExpression);
  79904. }
  79905. else {
  79906. thisArg = rightExpression;
  79907. }
  79908. }
  79909. rightExpression = segment.kind === 194 /* PropertyAccessExpression */
  79910. ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
  79911. : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
  79912. break;
  79913. case 196 /* CallExpression */:
  79914. if (i === 0 && leftThisArg) {
  79915. rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
  79916. }
  79917. else {
  79918. rightExpression = ts.createCall(rightExpression,
  79919. /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
  79920. }
  79921. break;
  79922. }
  79923. ts.setOriginalNode(rightExpression, segment);
  79924. }
  79925. var target = isDelete
  79926. ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
  79927. : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
  79928. return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
  79929. }
  79930. function createNotNullCondition(left, right, invert) {
  79931. return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero()));
  79932. }
  79933. function transformNullishCoalescingExpression(node) {
  79934. var left = ts.visitNode(node.left, visitor, ts.isExpression);
  79935. var right = left;
  79936. if (shouldCaptureInTempVariable(left)) {
  79937. right = ts.createTempVariable(hoistVariableDeclaration);
  79938. left = ts.createAssignment(right, left);
  79939. }
  79940. return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
  79941. }
  79942. function shouldCaptureInTempVariable(expression) {
  79943. // don't capture identifiers and `this` in a temporary variable
  79944. // `super` cannot be captured as it's no real variable
  79945. return !ts.isIdentifier(expression) &&
  79946. expression.kind !== 104 /* ThisKeyword */ &&
  79947. expression.kind !== 102 /* SuperKeyword */;
  79948. }
  79949. function visitDeleteExpression(node) {
  79950. return ts.isOptionalChain(ts.skipParentheses(node.expression))
  79951. ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
  79952. : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
  79953. }
  79954. }
  79955. ts.transformES2020 = transformES2020;
  79956. })(ts || (ts = {}));
  79957. /*@internal*/
  79958. var ts;
  79959. (function (ts) {
  79960. function transformESNext(context) {
  79961. return ts.chainBundle(transformSourceFile);
  79962. function transformSourceFile(node) {
  79963. if (node.isDeclarationFile) {
  79964. return node;
  79965. }
  79966. return ts.visitEachChild(node, visitor, context);
  79967. }
  79968. function visitor(node) {
  79969. if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
  79970. return node;
  79971. }
  79972. switch (node.kind) {
  79973. default:
  79974. return ts.visitEachChild(node, visitor, context);
  79975. }
  79976. }
  79977. }
  79978. ts.transformESNext = transformESNext;
  79979. })(ts || (ts = {}));
  79980. /*@internal*/
  79981. var ts;
  79982. (function (ts) {
  79983. function transformJsx(context) {
  79984. var compilerOptions = context.getCompilerOptions();
  79985. var currentSourceFile;
  79986. return ts.chainBundle(transformSourceFile);
  79987. /**
  79988. * Transform JSX-specific syntax in a SourceFile.
  79989. *
  79990. * @param node A SourceFile node.
  79991. */
  79992. function transformSourceFile(node) {
  79993. if (node.isDeclarationFile) {
  79994. return node;
  79995. }
  79996. currentSourceFile = node;
  79997. var visited = ts.visitEachChild(node, visitor, context);
  79998. ts.addEmitHelpers(visited, context.readEmitHelpers());
  79999. return visited;
  80000. }
  80001. function visitor(node) {
  80002. if (node.transformFlags & 2 /* ContainsJsx */) {
  80003. return visitorWorker(node);
  80004. }
  80005. else {
  80006. return node;
  80007. }
  80008. }
  80009. function visitorWorker(node) {
  80010. switch (node.kind) {
  80011. case 266 /* JsxElement */:
  80012. return visitJsxElement(node, /*isChild*/ false);
  80013. case 267 /* JsxSelfClosingElement */:
  80014. return visitJsxSelfClosingElement(node, /*isChild*/ false);
  80015. case 270 /* JsxFragment */:
  80016. return visitJsxFragment(node, /*isChild*/ false);
  80017. case 276 /* JsxExpression */:
  80018. return visitJsxExpression(node);
  80019. default:
  80020. return ts.visitEachChild(node, visitor, context);
  80021. }
  80022. }
  80023. function transformJsxChildToExpression(node) {
  80024. switch (node.kind) {
  80025. case 11 /* JsxText */:
  80026. return visitJsxText(node);
  80027. case 276 /* JsxExpression */:
  80028. return visitJsxExpression(node);
  80029. case 266 /* JsxElement */:
  80030. return visitJsxElement(node, /*isChild*/ true);
  80031. case 267 /* JsxSelfClosingElement */:
  80032. return visitJsxSelfClosingElement(node, /*isChild*/ true);
  80033. case 270 /* JsxFragment */:
  80034. return visitJsxFragment(node, /*isChild*/ true);
  80035. default:
  80036. return ts.Debug.failBadSyntaxKind(node);
  80037. }
  80038. }
  80039. function visitJsxElement(node, isChild) {
  80040. return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
  80041. }
  80042. function visitJsxSelfClosingElement(node, isChild) {
  80043. return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
  80044. }
  80045. function visitJsxFragment(node, isChild) {
  80046. return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
  80047. }
  80048. function visitJsxOpeningLikeElement(node, children, isChild, location) {
  80049. var tagName = getTagName(node);
  80050. var objectProperties;
  80051. var attrs = node.attributes.properties;
  80052. if (attrs.length === 0) {
  80053. // When there are no attributes, React wants "null"
  80054. objectProperties = ts.createNull();
  80055. }
  80056. else {
  80057. // Map spans of JsxAttribute nodes into object literals and spans
  80058. // of JsxSpreadAttribute nodes into expressions.
  80059. var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
  80060. ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
  80061. : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
  80062. if (ts.isJsxSpreadAttribute(attrs[0])) {
  80063. // We must always emit at least one object literal before a spread
  80064. // argument.
  80065. segments.unshift(ts.createObjectLiteral());
  80066. }
  80067. // Either emit one big object literal (no spread attribs), or
  80068. // a call to the __assign helper.
  80069. objectProperties = ts.singleOrUndefined(segments);
  80070. if (!objectProperties) {
  80071. objectProperties = ts.createAssignHelper(context, segments);
  80072. }
  80073. }
  80074. var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
  80075. tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
  80076. if (isChild) {
  80077. ts.startOnNewLine(element);
  80078. }
  80079. return element;
  80080. }
  80081. function visitJsxOpeningFragment(node, children, isChild, location) {
  80082. var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
  80083. ts.mapDefined(children, transformJsxChildToExpression), node, location);
  80084. if (isChild) {
  80085. ts.startOnNewLine(element);
  80086. }
  80087. return element;
  80088. }
  80089. function transformJsxSpreadAttributeToExpression(node) {
  80090. return ts.visitNode(node.expression, visitor, ts.isExpression);
  80091. }
  80092. function transformJsxAttributeToObjectLiteralElement(node) {
  80093. var name = getAttributeName(node);
  80094. var expression = transformJsxAttributeInitializer(node.initializer);
  80095. return ts.createPropertyAssignment(name, expression);
  80096. }
  80097. function transformJsxAttributeInitializer(node) {
  80098. if (node === undefined) {
  80099. return ts.createTrue();
  80100. }
  80101. else if (node.kind === 10 /* StringLiteral */) {
  80102. // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
  80103. // Need to be escaped to be handled correctly in a normal string
  80104. var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
  80105. literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
  80106. return ts.setTextRange(literal, node);
  80107. }
  80108. else if (node.kind === 276 /* JsxExpression */) {
  80109. if (node.expression === undefined) {
  80110. return ts.createTrue();
  80111. }
  80112. return visitJsxExpression(node);
  80113. }
  80114. else {
  80115. return ts.Debug.failBadSyntaxKind(node);
  80116. }
  80117. }
  80118. function visitJsxText(node) {
  80119. var fixed = fixupWhitespaceAndDecodeEntities(node.text);
  80120. return fixed === undefined ? undefined : ts.createLiteral(fixed);
  80121. }
  80122. /**
  80123. * JSX trims whitespace at the end and beginning of lines, except that the
  80124. * start/end of a tag is considered a start/end of a line only if that line is
  80125. * on the same line as the closing tag. See examples in
  80126. * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
  80127. * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model
  80128. *
  80129. * An equivalent algorithm would be:
  80130. * - If there is only one line, return it.
  80131. * - If there is only whitespace (but multiple lines), return `undefined`.
  80132. * - Split the text into lines.
  80133. * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
  80134. * - Decode entities on each line (individually).
  80135. * - Remove empty lines and join the rest with " ".
  80136. */
  80137. function fixupWhitespaceAndDecodeEntities(text) {
  80138. var acc;
  80139. // First non-whitespace character on this line.
  80140. var firstNonWhitespace = 0;
  80141. // Last non-whitespace character on this line.
  80142. var lastNonWhitespace = -1;
  80143. // These initial values are special because the first line is:
  80144. // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
  80145. // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
  80146. for (var i = 0; i < text.length; i++) {
  80147. var c = text.charCodeAt(i);
  80148. if (ts.isLineBreak(c)) {
  80149. // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
  80150. // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
  80151. if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
  80152. acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
  80153. }
  80154. // Reset firstNonWhitespace for the next line.
  80155. // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
  80156. firstNonWhitespace = -1;
  80157. }
  80158. else if (!ts.isWhiteSpaceSingleLine(c)) {
  80159. lastNonWhitespace = i;
  80160. if (firstNonWhitespace === -1) {
  80161. firstNonWhitespace = i;
  80162. }
  80163. }
  80164. }
  80165. return firstNonWhitespace !== -1
  80166. // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
  80167. ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
  80168. // Last line was all whitespace, so ignore it
  80169. : acc;
  80170. }
  80171. function addLineOfJsxText(acc, trimmedLine) {
  80172. // We do not escape the string here as that is handled by the printer
  80173. // when it emits the literal. We do, however, need to decode JSX entities.
  80174. var decoded = decodeEntities(trimmedLine);
  80175. return acc === undefined ? decoded : acc + " " + decoded;
  80176. }
  80177. /**
  80178. * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
  80179. * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
  80180. */
  80181. function decodeEntities(text) {
  80182. return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
  80183. if (decimal) {
  80184. return ts.utf16EncodeAsString(parseInt(decimal, 10));
  80185. }
  80186. else if (hex) {
  80187. return ts.utf16EncodeAsString(parseInt(hex, 16));
  80188. }
  80189. else {
  80190. var ch = entities.get(word);
  80191. // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
  80192. return ch ? ts.utf16EncodeAsString(ch) : match;
  80193. }
  80194. });
  80195. }
  80196. /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
  80197. function tryDecodeEntities(text) {
  80198. var decoded = decodeEntities(text);
  80199. return decoded === text ? undefined : decoded;
  80200. }
  80201. function getTagName(node) {
  80202. if (node.kind === 266 /* JsxElement */) {
  80203. return getTagName(node.openingElement);
  80204. }
  80205. else {
  80206. var name = node.tagName;
  80207. if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
  80208. return ts.createLiteral(ts.idText(name));
  80209. }
  80210. else {
  80211. return ts.createExpressionFromEntityName(name);
  80212. }
  80213. }
  80214. }
  80215. /**
  80216. * Emit an attribute name, which is quoted if it needs to be quoted. Because
  80217. * these emit into an object literal property name, we don't need to be worried
  80218. * about keywords, just non-identifier characters
  80219. */
  80220. function getAttributeName(node) {
  80221. var name = node.name;
  80222. var text = ts.idText(name);
  80223. if (/^[A-Za-z_]\w*$/.test(text)) {
  80224. return name;
  80225. }
  80226. else {
  80227. return ts.createLiteral(text);
  80228. }
  80229. }
  80230. function visitJsxExpression(node) {
  80231. return ts.visitNode(node.expression, visitor, ts.isExpression);
  80232. }
  80233. }
  80234. ts.transformJsx = transformJsx;
  80235. var entities = ts.createMapFromTemplate({
  80236. quot: 0x0022,
  80237. amp: 0x0026,
  80238. apos: 0x0027,
  80239. lt: 0x003C,
  80240. gt: 0x003E,
  80241. nbsp: 0x00A0,
  80242. iexcl: 0x00A1,
  80243. cent: 0x00A2,
  80244. pound: 0x00A3,
  80245. curren: 0x00A4,
  80246. yen: 0x00A5,
  80247. brvbar: 0x00A6,
  80248. sect: 0x00A7,
  80249. uml: 0x00A8,
  80250. copy: 0x00A9,
  80251. ordf: 0x00AA,
  80252. laquo: 0x00AB,
  80253. not: 0x00AC,
  80254. shy: 0x00AD,
  80255. reg: 0x00AE,
  80256. macr: 0x00AF,
  80257. deg: 0x00B0,
  80258. plusmn: 0x00B1,
  80259. sup2: 0x00B2,
  80260. sup3: 0x00B3,
  80261. acute: 0x00B4,
  80262. micro: 0x00B5,
  80263. para: 0x00B6,
  80264. middot: 0x00B7,
  80265. cedil: 0x00B8,
  80266. sup1: 0x00B9,
  80267. ordm: 0x00BA,
  80268. raquo: 0x00BB,
  80269. frac14: 0x00BC,
  80270. frac12: 0x00BD,
  80271. frac34: 0x00BE,
  80272. iquest: 0x00BF,
  80273. Agrave: 0x00C0,
  80274. Aacute: 0x00C1,
  80275. Acirc: 0x00C2,
  80276. Atilde: 0x00C3,
  80277. Auml: 0x00C4,
  80278. Aring: 0x00C5,
  80279. AElig: 0x00C6,
  80280. Ccedil: 0x00C7,
  80281. Egrave: 0x00C8,
  80282. Eacute: 0x00C9,
  80283. Ecirc: 0x00CA,
  80284. Euml: 0x00CB,
  80285. Igrave: 0x00CC,
  80286. Iacute: 0x00CD,
  80287. Icirc: 0x00CE,
  80288. Iuml: 0x00CF,
  80289. ETH: 0x00D0,
  80290. Ntilde: 0x00D1,
  80291. Ograve: 0x00D2,
  80292. Oacute: 0x00D3,
  80293. Ocirc: 0x00D4,
  80294. Otilde: 0x00D5,
  80295. Ouml: 0x00D6,
  80296. times: 0x00D7,
  80297. Oslash: 0x00D8,
  80298. Ugrave: 0x00D9,
  80299. Uacute: 0x00DA,
  80300. Ucirc: 0x00DB,
  80301. Uuml: 0x00DC,
  80302. Yacute: 0x00DD,
  80303. THORN: 0x00DE,
  80304. szlig: 0x00DF,
  80305. agrave: 0x00E0,
  80306. aacute: 0x00E1,
  80307. acirc: 0x00E2,
  80308. atilde: 0x00E3,
  80309. auml: 0x00E4,
  80310. aring: 0x00E5,
  80311. aelig: 0x00E6,
  80312. ccedil: 0x00E7,
  80313. egrave: 0x00E8,
  80314. eacute: 0x00E9,
  80315. ecirc: 0x00EA,
  80316. euml: 0x00EB,
  80317. igrave: 0x00EC,
  80318. iacute: 0x00ED,
  80319. icirc: 0x00EE,
  80320. iuml: 0x00EF,
  80321. eth: 0x00F0,
  80322. ntilde: 0x00F1,
  80323. ograve: 0x00F2,
  80324. oacute: 0x00F3,
  80325. ocirc: 0x00F4,
  80326. otilde: 0x00F5,
  80327. ouml: 0x00F6,
  80328. divide: 0x00F7,
  80329. oslash: 0x00F8,
  80330. ugrave: 0x00F9,
  80331. uacute: 0x00FA,
  80332. ucirc: 0x00FB,
  80333. uuml: 0x00FC,
  80334. yacute: 0x00FD,
  80335. thorn: 0x00FE,
  80336. yuml: 0x00FF,
  80337. OElig: 0x0152,
  80338. oelig: 0x0153,
  80339. Scaron: 0x0160,
  80340. scaron: 0x0161,
  80341. Yuml: 0x0178,
  80342. fnof: 0x0192,
  80343. circ: 0x02C6,
  80344. tilde: 0x02DC,
  80345. Alpha: 0x0391,
  80346. Beta: 0x0392,
  80347. Gamma: 0x0393,
  80348. Delta: 0x0394,
  80349. Epsilon: 0x0395,
  80350. Zeta: 0x0396,
  80351. Eta: 0x0397,
  80352. Theta: 0x0398,
  80353. Iota: 0x0399,
  80354. Kappa: 0x039A,
  80355. Lambda: 0x039B,
  80356. Mu: 0x039C,
  80357. Nu: 0x039D,
  80358. Xi: 0x039E,
  80359. Omicron: 0x039F,
  80360. Pi: 0x03A0,
  80361. Rho: 0x03A1,
  80362. Sigma: 0x03A3,
  80363. Tau: 0x03A4,
  80364. Upsilon: 0x03A5,
  80365. Phi: 0x03A6,
  80366. Chi: 0x03A7,
  80367. Psi: 0x03A8,
  80368. Omega: 0x03A9,
  80369. alpha: 0x03B1,
  80370. beta: 0x03B2,
  80371. gamma: 0x03B3,
  80372. delta: 0x03B4,
  80373. epsilon: 0x03B5,
  80374. zeta: 0x03B6,
  80375. eta: 0x03B7,
  80376. theta: 0x03B8,
  80377. iota: 0x03B9,
  80378. kappa: 0x03BA,
  80379. lambda: 0x03BB,
  80380. mu: 0x03BC,
  80381. nu: 0x03BD,
  80382. xi: 0x03BE,
  80383. omicron: 0x03BF,
  80384. pi: 0x03C0,
  80385. rho: 0x03C1,
  80386. sigmaf: 0x03C2,
  80387. sigma: 0x03C3,
  80388. tau: 0x03C4,
  80389. upsilon: 0x03C5,
  80390. phi: 0x03C6,
  80391. chi: 0x03C7,
  80392. psi: 0x03C8,
  80393. omega: 0x03C9,
  80394. thetasym: 0x03D1,
  80395. upsih: 0x03D2,
  80396. piv: 0x03D6,
  80397. ensp: 0x2002,
  80398. emsp: 0x2003,
  80399. thinsp: 0x2009,
  80400. zwnj: 0x200C,
  80401. zwj: 0x200D,
  80402. lrm: 0x200E,
  80403. rlm: 0x200F,
  80404. ndash: 0x2013,
  80405. mdash: 0x2014,
  80406. lsquo: 0x2018,
  80407. rsquo: 0x2019,
  80408. sbquo: 0x201A,
  80409. ldquo: 0x201C,
  80410. rdquo: 0x201D,
  80411. bdquo: 0x201E,
  80412. dagger: 0x2020,
  80413. Dagger: 0x2021,
  80414. bull: 0x2022,
  80415. hellip: 0x2026,
  80416. permil: 0x2030,
  80417. prime: 0x2032,
  80418. Prime: 0x2033,
  80419. lsaquo: 0x2039,
  80420. rsaquo: 0x203A,
  80421. oline: 0x203E,
  80422. frasl: 0x2044,
  80423. euro: 0x20AC,
  80424. image: 0x2111,
  80425. weierp: 0x2118,
  80426. real: 0x211C,
  80427. trade: 0x2122,
  80428. alefsym: 0x2135,
  80429. larr: 0x2190,
  80430. uarr: 0x2191,
  80431. rarr: 0x2192,
  80432. darr: 0x2193,
  80433. harr: 0x2194,
  80434. crarr: 0x21B5,
  80435. lArr: 0x21D0,
  80436. uArr: 0x21D1,
  80437. rArr: 0x21D2,
  80438. dArr: 0x21D3,
  80439. hArr: 0x21D4,
  80440. forall: 0x2200,
  80441. part: 0x2202,
  80442. exist: 0x2203,
  80443. empty: 0x2205,
  80444. nabla: 0x2207,
  80445. isin: 0x2208,
  80446. notin: 0x2209,
  80447. ni: 0x220B,
  80448. prod: 0x220F,
  80449. sum: 0x2211,
  80450. minus: 0x2212,
  80451. lowast: 0x2217,
  80452. radic: 0x221A,
  80453. prop: 0x221D,
  80454. infin: 0x221E,
  80455. ang: 0x2220,
  80456. and: 0x2227,
  80457. or: 0x2228,
  80458. cap: 0x2229,
  80459. cup: 0x222A,
  80460. int: 0x222B,
  80461. there4: 0x2234,
  80462. sim: 0x223C,
  80463. cong: 0x2245,
  80464. asymp: 0x2248,
  80465. ne: 0x2260,
  80466. equiv: 0x2261,
  80467. le: 0x2264,
  80468. ge: 0x2265,
  80469. sub: 0x2282,
  80470. sup: 0x2283,
  80471. nsub: 0x2284,
  80472. sube: 0x2286,
  80473. supe: 0x2287,
  80474. oplus: 0x2295,
  80475. otimes: 0x2297,
  80476. perp: 0x22A5,
  80477. sdot: 0x22C5,
  80478. lceil: 0x2308,
  80479. rceil: 0x2309,
  80480. lfloor: 0x230A,
  80481. rfloor: 0x230B,
  80482. lang: 0x2329,
  80483. rang: 0x232A,
  80484. loz: 0x25CA,
  80485. spades: 0x2660,
  80486. clubs: 0x2663,
  80487. hearts: 0x2665,
  80488. diams: 0x2666
  80489. });
  80490. })(ts || (ts = {}));
  80491. /*@internal*/
  80492. var ts;
  80493. (function (ts) {
  80494. function transformES2016(context) {
  80495. var hoistVariableDeclaration = context.hoistVariableDeclaration;
  80496. return ts.chainBundle(transformSourceFile);
  80497. function transformSourceFile(node) {
  80498. if (node.isDeclarationFile) {
  80499. return node;
  80500. }
  80501. return ts.visitEachChild(node, visitor, context);
  80502. }
  80503. function visitor(node) {
  80504. if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
  80505. return node;
  80506. }
  80507. switch (node.kind) {
  80508. case 209 /* BinaryExpression */:
  80509. return visitBinaryExpression(node);
  80510. default:
  80511. return ts.visitEachChild(node, visitor, context);
  80512. }
  80513. }
  80514. function visitBinaryExpression(node) {
  80515. switch (node.operatorToken.kind) {
  80516. case 66 /* AsteriskAsteriskEqualsToken */:
  80517. return visitExponentiationAssignmentExpression(node);
  80518. case 42 /* AsteriskAsteriskToken */:
  80519. return visitExponentiationExpression(node);
  80520. default:
  80521. return ts.visitEachChild(node, visitor, context);
  80522. }
  80523. }
  80524. function visitExponentiationAssignmentExpression(node) {
  80525. var target;
  80526. var value;
  80527. var left = ts.visitNode(node.left, visitor, ts.isExpression);
  80528. var right = ts.visitNode(node.right, visitor, ts.isExpression);
  80529. if (ts.isElementAccessExpression(left)) {
  80530. // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
  80531. var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
  80532. var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
  80533. target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
  80534. value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
  80535. }
  80536. else if (ts.isPropertyAccessExpression(left)) {
  80537. // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
  80538. var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
  80539. target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
  80540. value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
  80541. }
  80542. else {
  80543. // Transforms `a **= b` into `a = Math.pow(a, b)`
  80544. target = left;
  80545. value = left;
  80546. }
  80547. return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
  80548. }
  80549. function visitExponentiationExpression(node) {
  80550. // Transforms `a ** b` into `Math.pow(a, b)`
  80551. var left = ts.visitNode(node.left, visitor, ts.isExpression);
  80552. var right = ts.visitNode(node.right, visitor, ts.isExpression);
  80553. return ts.createMathPow(left, right, /*location*/ node);
  80554. }
  80555. }
  80556. ts.transformES2016 = transformES2016;
  80557. })(ts || (ts = {}));
  80558. /*@internal*/
  80559. var ts;
  80560. (function (ts) {
  80561. var ES2015SubstitutionFlags;
  80562. (function (ES2015SubstitutionFlags) {
  80563. /** Enables substitutions for captured `this` */
  80564. ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
  80565. /** Enables substitutions for block-scoped bindings. */
  80566. ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
  80567. })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
  80568. var LoopOutParameterFlags;
  80569. (function (LoopOutParameterFlags) {
  80570. LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
  80571. LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
  80572. })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
  80573. var CopyDirection;
  80574. (function (CopyDirection) {
  80575. CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
  80576. CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
  80577. })(CopyDirection || (CopyDirection = {}));
  80578. var Jump;
  80579. (function (Jump) {
  80580. Jump[Jump["Break"] = 2] = "Break";
  80581. Jump[Jump["Continue"] = 4] = "Continue";
  80582. Jump[Jump["Return"] = 8] = "Return";
  80583. })(Jump || (Jump = {}));
  80584. // Facts we track as we traverse the tree
  80585. var HierarchyFacts;
  80586. (function (HierarchyFacts) {
  80587. HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
  80588. //
  80589. // Ancestor facts
  80590. //
  80591. HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
  80592. HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
  80593. HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
  80594. HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
  80595. HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
  80596. HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
  80597. HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
  80598. HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
  80599. HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
  80600. HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
  80601. HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
  80602. HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
  80603. HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
  80604. HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
  80605. // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
  80606. // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
  80607. //
  80608. // Ancestor masks
  80609. //
  80610. HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
  80611. // We are always in *some* kind of block scope, but only specific block-scope containers are
  80612. // top-level or Blocks.
  80613. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
  80614. HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
  80615. // A source file is a top-level block scope.
  80616. HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
  80617. HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
  80618. // Functions, methods, and accessors are both new lexical scopes and new block scopes.
  80619. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
  80620. HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
  80621. HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
  80622. HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
  80623. // Arrow functions are lexically scoped to their container, but are new block scopes.
  80624. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
  80625. HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
  80626. // Constructors are both new lexical scopes and new block scopes. Constructors are also
  80627. // always considered non-static members of a class.
  80628. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
  80629. HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
  80630. // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
  80631. // within an IterationStatement to indicate whether the embedded statement is an
  80632. // IterationStatementBlock.
  80633. HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
  80634. HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
  80635. // 'for' statements are new block scopes and have special handling for 'let' declarations.
  80636. HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
  80637. HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
  80638. // 'for-in' and 'for-of' statements are new block scopes and have special handling for
  80639. // 'let' declarations.
  80640. HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
  80641. HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
  80642. // Blocks (other than function bodies) are new block scopes.
  80643. HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
  80644. HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
  80645. HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
  80646. HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
  80647. //
  80648. // Subtree facts
  80649. //
  80650. HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
  80651. HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
  80652. //
  80653. // Subtree masks
  80654. //
  80655. HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
  80656. HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
  80657. HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
  80658. })(HierarchyFacts || (HierarchyFacts = {}));
  80659. function transformES2015(context) {
  80660. var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
  80661. var compilerOptions = context.getCompilerOptions();
  80662. var resolver = context.getEmitResolver();
  80663. var previousOnSubstituteNode = context.onSubstituteNode;
  80664. var previousOnEmitNode = context.onEmitNode;
  80665. context.onEmitNode = onEmitNode;
  80666. context.onSubstituteNode = onSubstituteNode;
  80667. var currentSourceFile;
  80668. var currentText;
  80669. var hierarchyFacts;
  80670. var taggedTemplateStringDeclarations;
  80671. function recordTaggedTemplateString(temp) {
  80672. taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
  80673. }
  80674. /**
  80675. * Used to track if we are emitting body of the converted loop
  80676. */
  80677. var convertedLoopState;
  80678. /**
  80679. * Keeps track of whether substitutions have been enabled for specific cases.
  80680. * They are persisted between each SourceFile transformation and should not
  80681. * be reset.
  80682. */
  80683. var enabledSubstitutions;
  80684. return ts.chainBundle(transformSourceFile);
  80685. function transformSourceFile(node) {
  80686. if (node.isDeclarationFile) {
  80687. return node;
  80688. }
  80689. currentSourceFile = node;
  80690. currentText = node.text;
  80691. var visited = visitSourceFile(node);
  80692. ts.addEmitHelpers(visited, context.readEmitHelpers());
  80693. currentSourceFile = undefined;
  80694. currentText = undefined;
  80695. taggedTemplateStringDeclarations = undefined;
  80696. hierarchyFacts = 0 /* None */;
  80697. return visited;
  80698. }
  80699. /**
  80700. * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
  80701. * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
  80702. * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
  80703. */
  80704. function enterSubtree(excludeFacts, includeFacts) {
  80705. var ancestorFacts = hierarchyFacts;
  80706. hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
  80707. return ancestorFacts;
  80708. }
  80709. /**
  80710. * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
  80711. * subtree, propagating specific facts from the subtree.
  80712. * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
  80713. * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
  80714. * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
  80715. */
  80716. function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
  80717. hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
  80718. }
  80719. function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
  80720. return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
  80721. && node.kind === 235 /* ReturnStatement */
  80722. && !node.expression;
  80723. }
  80724. function shouldVisitNode(node) {
  80725. return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
  80726. || convertedLoopState !== undefined
  80727. || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
  80728. || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
  80729. || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
  80730. }
  80731. function visitor(node) {
  80732. if (shouldVisitNode(node)) {
  80733. return visitJavaScript(node);
  80734. }
  80735. else {
  80736. return node;
  80737. }
  80738. }
  80739. function callExpressionVisitor(node) {
  80740. if (node.kind === 102 /* SuperKeyword */) {
  80741. return visitSuperKeyword(/*isExpressionOfCall*/ true);
  80742. }
  80743. return visitor(node);
  80744. }
  80745. function visitJavaScript(node) {
  80746. switch (node.kind) {
  80747. case 120 /* StaticKeyword */:
  80748. return undefined; // elide static keyword
  80749. case 245 /* ClassDeclaration */:
  80750. return visitClassDeclaration(node);
  80751. case 214 /* ClassExpression */:
  80752. return visitClassExpression(node);
  80753. case 156 /* Parameter */:
  80754. return visitParameter(node);
  80755. case 244 /* FunctionDeclaration */:
  80756. return visitFunctionDeclaration(node);
  80757. case 202 /* ArrowFunction */:
  80758. return visitArrowFunction(node);
  80759. case 201 /* FunctionExpression */:
  80760. return visitFunctionExpression(node);
  80761. case 242 /* VariableDeclaration */:
  80762. return visitVariableDeclaration(node);
  80763. case 75 /* Identifier */:
  80764. return visitIdentifier(node);
  80765. case 243 /* VariableDeclarationList */:
  80766. return visitVariableDeclarationList(node);
  80767. case 237 /* SwitchStatement */:
  80768. return visitSwitchStatement(node);
  80769. case 251 /* CaseBlock */:
  80770. return visitCaseBlock(node);
  80771. case 223 /* Block */:
  80772. return visitBlock(node, /*isFunctionBody*/ false);
  80773. case 234 /* BreakStatement */:
  80774. case 233 /* ContinueStatement */:
  80775. return visitBreakOrContinueStatement(node);
  80776. case 238 /* LabeledStatement */:
  80777. return visitLabeledStatement(node);
  80778. case 228 /* DoStatement */:
  80779. case 229 /* WhileStatement */:
  80780. return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
  80781. case 230 /* ForStatement */:
  80782. return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
  80783. case 231 /* ForInStatement */:
  80784. return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
  80785. case 232 /* ForOfStatement */:
  80786. return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
  80787. case 226 /* ExpressionStatement */:
  80788. return visitExpressionStatement(node);
  80789. case 193 /* ObjectLiteralExpression */:
  80790. return visitObjectLiteralExpression(node);
  80791. case 280 /* CatchClause */:
  80792. return visitCatchClause(node);
  80793. case 282 /* ShorthandPropertyAssignment */:
  80794. return visitShorthandPropertyAssignment(node);
  80795. case 154 /* ComputedPropertyName */:
  80796. return visitComputedPropertyName(node);
  80797. case 192 /* ArrayLiteralExpression */:
  80798. return visitArrayLiteralExpression(node);
  80799. case 196 /* CallExpression */:
  80800. return visitCallExpression(node);
  80801. case 197 /* NewExpression */:
  80802. return visitNewExpression(node);
  80803. case 200 /* ParenthesizedExpression */:
  80804. return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
  80805. case 209 /* BinaryExpression */:
  80806. return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
  80807. case 14 /* NoSubstitutionTemplateLiteral */:
  80808. case 15 /* TemplateHead */:
  80809. case 16 /* TemplateMiddle */:
  80810. case 17 /* TemplateTail */:
  80811. return visitTemplateLiteral(node);
  80812. case 10 /* StringLiteral */:
  80813. return visitStringLiteral(node);
  80814. case 8 /* NumericLiteral */:
  80815. return visitNumericLiteral(node);
  80816. case 198 /* TaggedTemplateExpression */:
  80817. return visitTaggedTemplateExpression(node);
  80818. case 211 /* TemplateExpression */:
  80819. return visitTemplateExpression(node);
  80820. case 212 /* YieldExpression */:
  80821. return visitYieldExpression(node);
  80822. case 213 /* SpreadElement */:
  80823. return visitSpreadElement(node);
  80824. case 102 /* SuperKeyword */:
  80825. return visitSuperKeyword(/*isExpressionOfCall*/ false);
  80826. case 104 /* ThisKeyword */:
  80827. return visitThisKeyword(node);
  80828. case 219 /* MetaProperty */:
  80829. return visitMetaProperty(node);
  80830. case 161 /* MethodDeclaration */:
  80831. return visitMethodDeclaration(node);
  80832. case 163 /* GetAccessor */:
  80833. case 164 /* SetAccessor */:
  80834. return visitAccessorDeclaration(node);
  80835. case 225 /* VariableStatement */:
  80836. return visitVariableStatement(node);
  80837. case 235 /* ReturnStatement */:
  80838. return visitReturnStatement(node);
  80839. default:
  80840. return ts.visitEachChild(node, visitor, context);
  80841. }
  80842. }
  80843. function visitSourceFile(node) {
  80844. var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
  80845. var prologue = [];
  80846. var statements = [];
  80847. startLexicalEnvironment();
  80848. var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
  80849. statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
  80850. ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
  80851. if (taggedTemplateStringDeclarations) {
  80852. statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
  80853. }
  80854. ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
  80855. insertCaptureThisForNodeIfNeeded(prologue, node);
  80856. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  80857. return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
  80858. }
  80859. function visitSwitchStatement(node) {
  80860. if (convertedLoopState !== undefined) {
  80861. var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
  80862. // for switch statement allow only non-labeled break
  80863. convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
  80864. var result = ts.visitEachChild(node, visitor, context);
  80865. convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
  80866. return result;
  80867. }
  80868. return ts.visitEachChild(node, visitor, context);
  80869. }
  80870. function visitCaseBlock(node) {
  80871. var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
  80872. var updated = ts.visitEachChild(node, visitor, context);
  80873. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  80874. return updated;
  80875. }
  80876. function returnCapturedThis(node) {
  80877. return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
  80878. }
  80879. function visitReturnStatement(node) {
  80880. if (convertedLoopState) {
  80881. convertedLoopState.nonLocalJumps |= 8 /* Return */;
  80882. if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
  80883. node = returnCapturedThis(node);
  80884. }
  80885. return ts.createReturn(ts.createObjectLiteral([
  80886. ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
  80887. ? ts.visitNode(node.expression, visitor, ts.isExpression)
  80888. : ts.createVoidZero())
  80889. ]));
  80890. }
  80891. else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
  80892. return returnCapturedThis(node);
  80893. }
  80894. return ts.visitEachChild(node, visitor, context);
  80895. }
  80896. function visitThisKeyword(node) {
  80897. if (hierarchyFacts & 2 /* ArrowFunction */) {
  80898. hierarchyFacts |= 32768 /* CapturedLexicalThis */;
  80899. }
  80900. if (convertedLoopState) {
  80901. if (hierarchyFacts & 2 /* ArrowFunction */) {
  80902. // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
  80903. convertedLoopState.containsLexicalThis = true;
  80904. return node;
  80905. }
  80906. return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
  80907. }
  80908. return node;
  80909. }
  80910. function visitIdentifier(node) {
  80911. if (!convertedLoopState) {
  80912. return node;
  80913. }
  80914. if (ts.isGeneratedIdentifier(node)) {
  80915. return node;
  80916. }
  80917. if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
  80918. return node;
  80919. }
  80920. return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
  80921. }
  80922. function visitBreakOrContinueStatement(node) {
  80923. if (convertedLoopState) {
  80924. // check if we can emit break/continue as is
  80925. // it is possible if either
  80926. // - break/continue is labeled and label is located inside the converted loop
  80927. // - break/continue is non-labeled and located in non-converted loop/switch statement
  80928. var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
  80929. var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
  80930. (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
  80931. if (!canUseBreakOrContinue) {
  80932. var labelMarker = void 0;
  80933. var label = node.label;
  80934. if (!label) {
  80935. if (node.kind === 234 /* BreakStatement */) {
  80936. convertedLoopState.nonLocalJumps |= 2 /* Break */;
  80937. labelMarker = "break";
  80938. }
  80939. else {
  80940. convertedLoopState.nonLocalJumps |= 4 /* Continue */;
  80941. // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
  80942. labelMarker = "continue";
  80943. }
  80944. }
  80945. else {
  80946. if (node.kind === 234 /* BreakStatement */) {
  80947. labelMarker = "break-" + label.escapedText;
  80948. setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
  80949. }
  80950. else {
  80951. labelMarker = "continue-" + label.escapedText;
  80952. setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
  80953. }
  80954. }
  80955. var returnExpression = ts.createLiteral(labelMarker);
  80956. if (convertedLoopState.loopOutParameters.length) {
  80957. var outParams = convertedLoopState.loopOutParameters;
  80958. var expr = void 0;
  80959. for (var i = 0; i < outParams.length; i++) {
  80960. var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
  80961. if (i === 0) {
  80962. expr = copyExpr;
  80963. }
  80964. else {
  80965. expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
  80966. }
  80967. }
  80968. returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
  80969. }
  80970. return ts.createReturn(returnExpression);
  80971. }
  80972. }
  80973. return ts.visitEachChild(node, visitor, context);
  80974. }
  80975. /**
  80976. * Visits a ClassDeclaration and transforms it into a variable statement.
  80977. *
  80978. * @param node A ClassDeclaration node.
  80979. */
  80980. function visitClassDeclaration(node) {
  80981. // [source]
  80982. // class C { }
  80983. //
  80984. // [output]
  80985. // var C = (function () {
  80986. // function C() {
  80987. // }
  80988. // return C;
  80989. // }());
  80990. var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true),
  80991. /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
  80992. ts.setOriginalNode(variable, node);
  80993. var statements = [];
  80994. var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
  80995. ts.setOriginalNode(statement, node);
  80996. ts.setTextRange(statement, node);
  80997. ts.startOnNewLine(statement);
  80998. statements.push(statement);
  80999. // Add an `export default` statement for default exports (for `--target es5 --module es6`)
  81000. if (ts.hasModifier(node, 1 /* Export */)) {
  81001. var exportStatement = ts.hasModifier(node, 512 /* Default */)
  81002. ? ts.createExportDefault(ts.getLocalName(node))
  81003. : ts.createExternalModuleExport(ts.getLocalName(node));
  81004. ts.setOriginalNode(exportStatement, statement);
  81005. statements.push(exportStatement);
  81006. }
  81007. var emitFlags = ts.getEmitFlags(node);
  81008. if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
  81009. // Add a DeclarationMarker as a marker for the end of the declaration
  81010. statements.push(ts.createEndOfDeclarationMarker(node));
  81011. ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
  81012. }
  81013. return ts.singleOrMany(statements);
  81014. }
  81015. /**
  81016. * Visits a ClassExpression and transforms it into an expression.
  81017. *
  81018. * @param node A ClassExpression node.
  81019. */
  81020. function visitClassExpression(node) {
  81021. // [source]
  81022. // C = class { }
  81023. //
  81024. // [output]
  81025. // C = (function () {
  81026. // function class_1() {
  81027. // }
  81028. // return class_1;
  81029. // }())
  81030. return transformClassLikeDeclarationToExpression(node);
  81031. }
  81032. /**
  81033. * Transforms a ClassExpression or ClassDeclaration into an expression.
  81034. *
  81035. * @param node A ClassExpression or ClassDeclaration node.
  81036. */
  81037. function transformClassLikeDeclarationToExpression(node) {
  81038. // [source]
  81039. // class C extends D {
  81040. // constructor() {}
  81041. // method() {}
  81042. // get prop() {}
  81043. // set prop(v) {}
  81044. // }
  81045. //
  81046. // [output]
  81047. // (function (_super) {
  81048. // __extends(C, _super);
  81049. // function C() {
  81050. // }
  81051. // C.prototype.method = function () {}
  81052. // Object.defineProperty(C.prototype, "prop", {
  81053. // get: function() {},
  81054. // set: function() {},
  81055. // enumerable: true,
  81056. // configurable: true
  81057. // });
  81058. // return C;
  81059. // }(D))
  81060. if (node.name) {
  81061. enableSubstitutionsForBlockScopedBindings();
  81062. }
  81063. var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
  81064. var classFunction = ts.createFunctionExpression(
  81065. /*modifiers*/ undefined,
  81066. /*asteriskToken*/ undefined,
  81067. /*name*/ undefined,
  81068. /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [],
  81069. /*type*/ undefined, transformClassBody(node, extendsClauseElement));
  81070. // To preserve the behavior of the old emitter, we explicitly indent
  81071. // the body of the function here if it was requested in an earlier
  81072. // transformation.
  81073. ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
  81074. // "inner" and "outer" below are added purely to preserve source map locations from
  81075. // the old emitter
  81076. var inner = ts.createPartiallyEmittedExpression(classFunction);
  81077. inner.end = node.end;
  81078. ts.setEmitFlags(inner, 1536 /* NoComments */);
  81079. var outer = ts.createPartiallyEmittedExpression(inner);
  81080. outer.end = ts.skipTrivia(currentText, node.pos);
  81081. ts.setEmitFlags(outer, 1536 /* NoComments */);
  81082. var result = ts.createParen(ts.createCall(outer,
  81083. /*typeArguments*/ undefined, extendsClauseElement
  81084. ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
  81085. : []));
  81086. ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
  81087. return result;
  81088. }
  81089. /**
  81090. * Transforms a ClassExpression or ClassDeclaration into a function body.
  81091. *
  81092. * @param node A ClassExpression or ClassDeclaration node.
  81093. * @param extendsClauseElement The expression for the class `extends` clause.
  81094. */
  81095. function transformClassBody(node, extendsClauseElement) {
  81096. var statements = [];
  81097. startLexicalEnvironment();
  81098. addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
  81099. addConstructor(statements, node, extendsClauseElement);
  81100. addClassMembers(statements, node);
  81101. // Create a synthetic text range for the return statement.
  81102. var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
  81103. var localName = ts.getInternalName(node);
  81104. // The following partially-emitted expression exists purely to align our sourcemap
  81105. // emit with the original emitter.
  81106. var outer = ts.createPartiallyEmittedExpression(localName);
  81107. outer.end = closingBraceLocation.end;
  81108. ts.setEmitFlags(outer, 1536 /* NoComments */);
  81109. var statement = ts.createReturn(outer);
  81110. statement.pos = closingBraceLocation.pos;
  81111. ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
  81112. statements.push(statement);
  81113. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  81114. var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
  81115. ts.setEmitFlags(block, 1536 /* NoComments */);
  81116. return block;
  81117. }
  81118. /**
  81119. * Adds a call to the `__extends` helper if needed for a class.
  81120. *
  81121. * @param statements The statements of the class body function.
  81122. * @param node The ClassExpression or ClassDeclaration node.
  81123. * @param extendsClauseElement The expression for the class `extends` clause.
  81124. */
  81125. function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
  81126. if (extendsClauseElement) {
  81127. statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))),
  81128. /*location*/ extendsClauseElement));
  81129. }
  81130. }
  81131. /**
  81132. * Adds the constructor of the class to a class body function.
  81133. *
  81134. * @param statements The statements of the class body function.
  81135. * @param node The ClassExpression or ClassDeclaration node.
  81136. * @param extendsClauseElement The expression for the class `extends` clause.
  81137. */
  81138. function addConstructor(statements, node, extendsClauseElement) {
  81139. var savedConvertedLoopState = convertedLoopState;
  81140. convertedLoopState = undefined;
  81141. var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
  81142. var constructor = ts.getFirstConstructorWithBody(node);
  81143. var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
  81144. var constructorFunction = ts.createFunctionDeclaration(
  81145. /*decorators*/ undefined,
  81146. /*modifiers*/ undefined,
  81147. /*asteriskToken*/ undefined, ts.getInternalName(node),
  81148. /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper),
  81149. /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
  81150. ts.setTextRange(constructorFunction, constructor || node);
  81151. if (extendsClauseElement) {
  81152. ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
  81153. }
  81154. statements.push(constructorFunction);
  81155. exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
  81156. convertedLoopState = savedConvertedLoopState;
  81157. }
  81158. /**
  81159. * Transforms the parameters of the constructor declaration of a class.
  81160. *
  81161. * @param constructor The constructor for the class.
  81162. * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
  81163. * synthesized `super` call.
  81164. */
  81165. function transformConstructorParameters(constructor, hasSynthesizedSuper) {
  81166. // If the TypeScript transformer needed to synthesize a constructor for property
  81167. // initializers, it would have also added a synthetic `...args` parameter and
  81168. // `super` call.
  81169. // If this is the case, we do not include the synthetic `...args` parameter and
  81170. // will instead use the `arguments` object in ES5/3.
  81171. return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
  81172. || [];
  81173. }
  81174. function createDefaultConstructorBody(node, isDerivedClass) {
  81175. // We must be here because the user didn't write a constructor
  81176. // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
  81177. // If that's the case we can just immediately return the result of a 'super()' call.
  81178. var statements = [];
  81179. resumeLexicalEnvironment();
  81180. ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
  81181. if (isDerivedClass) {
  81182. // return _super !== null && _super.apply(this, arguments) || this;
  81183. statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
  81184. }
  81185. var statementsArray = ts.createNodeArray(statements);
  81186. ts.setTextRange(statementsArray, node.members);
  81187. var block = ts.createBlock(statementsArray, /*multiLine*/ true);
  81188. ts.setTextRange(block, node);
  81189. ts.setEmitFlags(block, 1536 /* NoComments */);
  81190. return block;
  81191. }
  81192. /**
  81193. * Transforms the body of a constructor declaration of a class.
  81194. *
  81195. * @param constructor The constructor for the class.
  81196. * @param node The node which contains the constructor.
  81197. * @param extendsClauseElement The expression for the class `extends` clause.
  81198. * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
  81199. * synthesized `super` call.
  81200. */
  81201. function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
  81202. // determine whether the class is known syntactically to be a derived class (e.g. a
  81203. // class that extends a value that is not syntactically known to be `null`).
  81204. var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
  81205. // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
  81206. // representation:
  81207. //
  81208. // ```
  81209. // // es2015 (source)
  81210. // class C extends Base { }
  81211. //
  81212. // // es5 (transformed)
  81213. // var C = (function (_super) {
  81214. // function C() {
  81215. // return _super.apply(this, arguments) || this;
  81216. // }
  81217. // return C;
  81218. // })(Base);
  81219. // ```
  81220. if (!constructor)
  81221. return createDefaultConstructorBody(node, isDerivedClass);
  81222. // The prologue will contain all leading standard and custom prologue statements added by this transform
  81223. var prologue = [];
  81224. var statements = [];
  81225. resumeLexicalEnvironment();
  81226. // If a super call has already been synthesized,
  81227. // we're going to assume that we should just transform everything after that.
  81228. // The assumption is that no prior step in the pipeline has added any prologue directives.
  81229. var statementOffset = 0;
  81230. if (!hasSynthesizedSuper)
  81231. statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
  81232. addDefaultValueAssignmentsIfNeeded(statements, constructor);
  81233. addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
  81234. if (!hasSynthesizedSuper)
  81235. statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
  81236. // If the first statement is a call to `super()`, visit the statement directly
  81237. var superCallExpression;
  81238. if (hasSynthesizedSuper) {
  81239. superCallExpression = createDefaultSuperCallOrThis();
  81240. }
  81241. else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
  81242. var firstStatement = constructor.body.statements[statementOffset];
  81243. if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
  81244. superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
  81245. }
  81246. }
  81247. if (superCallExpression) {
  81248. hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
  81249. statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
  81250. }
  81251. // visit the remaining statements
  81252. ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
  81253. ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
  81254. insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
  81255. if (isDerivedClass) {
  81256. if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
  81257. // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
  81258. // following representation:
  81259. //
  81260. // ```
  81261. // // es2015 (source)
  81262. // class C extends Base {
  81263. // constructor() {
  81264. // super("foo");
  81265. // }
  81266. // }
  81267. //
  81268. // // es5 (transformed)
  81269. // var C = (function (_super) {
  81270. // function C() {
  81271. // return _super.call(this, "foo") || this;
  81272. // }
  81273. // return C;
  81274. // })(Base);
  81275. // ```
  81276. var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
  81277. var returnStatement = ts.createReturn(superCallExpression);
  81278. ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
  81279. ts.setEmitFlags(superCall, 1536 /* NoComments */);
  81280. statements.push(returnStatement);
  81281. }
  81282. else {
  81283. // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
  81284. //
  81285. // ```
  81286. // // es2015 (source)
  81287. // class C extends Base {
  81288. // constructor() {
  81289. // super("foo");
  81290. // this.x = 1;
  81291. // }
  81292. // }
  81293. //
  81294. // // es5 (transformed)
  81295. // var C = (function (_super) {
  81296. // function C() {
  81297. // var _this = _super.call(this, "foo") || this;
  81298. // _this.x = 1;
  81299. // return _this;
  81300. // }
  81301. // return C;
  81302. // })(Base);
  81303. // ```
  81304. // Since the `super()` call was the first statement, we insert the `this` capturing call to
  81305. // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
  81306. insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
  81307. if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
  81308. statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
  81309. }
  81310. }
  81311. }
  81312. else {
  81313. // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
  81314. // captured when necessitated by an arrow function capturing the lexical `this`:
  81315. //
  81316. // ```
  81317. // // es2015
  81318. // class C {}
  81319. //
  81320. // // es5
  81321. // var C = (function () {
  81322. // function C() {
  81323. // }
  81324. // return C;
  81325. // })();
  81326. // ```
  81327. insertCaptureThisForNodeIfNeeded(prologue, constructor);
  81328. }
  81329. var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
  81330. /*location*/ constructor.body.statements),
  81331. /*multiLine*/ true);
  81332. ts.setTextRange(block, constructor.body);
  81333. return block;
  81334. }
  81335. /**
  81336. * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
  81337. * It would generate obviously dead code, so we'll try to make things a little bit prettier
  81338. * by doing a minimal check on whether some common patterns always explicitly return.
  81339. */
  81340. function isSufficientlyCoveredByReturnStatements(statement) {
  81341. // A return statement is considered covered.
  81342. if (statement.kind === 235 /* ReturnStatement */) {
  81343. return true;
  81344. }
  81345. // An if-statement with two covered branches is covered.
  81346. else if (statement.kind === 227 /* IfStatement */) {
  81347. var ifStatement = statement;
  81348. if (ifStatement.elseStatement) {
  81349. return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
  81350. isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
  81351. }
  81352. }
  81353. // A block is covered if it has a last statement which is covered.
  81354. else if (statement.kind === 223 /* Block */) {
  81355. var lastStatement = ts.lastOrUndefined(statement.statements);
  81356. if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
  81357. return true;
  81358. }
  81359. }
  81360. return false;
  81361. }
  81362. function createActualThis() {
  81363. return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
  81364. }
  81365. function createDefaultSuperCallOrThis() {
  81366. return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
  81367. }
  81368. /**
  81369. * Visits a parameter declaration.
  81370. *
  81371. * @param node A ParameterDeclaration node.
  81372. */
  81373. function visitParameter(node) {
  81374. if (node.dotDotDotToken) {
  81375. // rest parameters are elided
  81376. return undefined;
  81377. }
  81378. else if (ts.isBindingPattern(node.name)) {
  81379. // Binding patterns are converted into a generated name and are
  81380. // evaluated inside the function body.
  81381. return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
  81382. /*decorators*/ undefined,
  81383. /*modifiers*/ undefined,
  81384. /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node),
  81385. /*questionToken*/ undefined,
  81386. /*type*/ undefined,
  81387. /*initializer*/ undefined),
  81388. /*location*/ node),
  81389. /*original*/ node);
  81390. }
  81391. else if (node.initializer) {
  81392. // Initializers are elided
  81393. return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
  81394. /*decorators*/ undefined,
  81395. /*modifiers*/ undefined,
  81396. /*dotDotDotToken*/ undefined, node.name,
  81397. /*questionToken*/ undefined,
  81398. /*type*/ undefined,
  81399. /*initializer*/ undefined),
  81400. /*location*/ node),
  81401. /*original*/ node);
  81402. }
  81403. else {
  81404. return node;
  81405. }
  81406. }
  81407. function hasDefaultValueOrBindingPattern(node) {
  81408. return node.initializer !== undefined
  81409. || ts.isBindingPattern(node.name);
  81410. }
  81411. /**
  81412. * Adds statements to the body of a function-like node if it contains parameters with
  81413. * binding patterns or initializers.
  81414. *
  81415. * @param statements The statements for the new function body.
  81416. * @param node A function-like node.
  81417. */
  81418. function addDefaultValueAssignmentsIfNeeded(statements, node) {
  81419. if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
  81420. return false;
  81421. }
  81422. var added = false;
  81423. for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
  81424. var parameter = _a[_i];
  81425. var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
  81426. // A rest parameter cannot have a binding pattern or an initializer,
  81427. // so let's just ignore it.
  81428. if (dotDotDotToken) {
  81429. continue;
  81430. }
  81431. if (ts.isBindingPattern(name)) {
  81432. added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
  81433. }
  81434. else if (initializer) {
  81435. insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
  81436. added = true;
  81437. }
  81438. }
  81439. return added;
  81440. }
  81441. /**
  81442. * Adds statements to the body of a function-like node for parameters with binding patterns
  81443. *
  81444. * @param statements The statements for the new function body.
  81445. * @param parameter The parameter for the function.
  81446. * @param name The name of the parameter.
  81447. * @param initializer The initializer for the parameter.
  81448. */
  81449. function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
  81450. // In cases where a binding pattern is simply '[]' or '{}',
  81451. // we usually don't want to emit a var declaration; however, in the presence
  81452. // of an initializer, we must emit that expression to preserve side effects.
  81453. if (name.elements.length > 0) {
  81454. ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
  81455. /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
  81456. return true;
  81457. }
  81458. else if (initializer) {
  81459. ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
  81460. return true;
  81461. }
  81462. return false;
  81463. }
  81464. /**
  81465. * Adds statements to the body of a function-like node for parameters with initializers.
  81466. *
  81467. * @param statements The statements for the new function body.
  81468. * @param parameter The parameter for the function.
  81469. * @param name The name of the parameter.
  81470. * @param initializer The initializer for the parameter.
  81471. */
  81472. function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
  81473. initializer = ts.visitNode(initializer, visitor, ts.isExpression);
  81474. var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
  81475. ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
  81476. ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
  81477. ts.startOnNewLine(statement);
  81478. ts.setTextRange(statement, parameter);
  81479. ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
  81480. ts.insertStatementAfterCustomPrologue(statements, statement);
  81481. }
  81482. /**
  81483. * Gets a value indicating whether we need to add statements to handle a rest parameter.
  81484. *
  81485. * @param node A ParameterDeclaration node.
  81486. * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
  81487. * part of a constructor declaration with a
  81488. * synthesized call to `super`
  81489. */
  81490. function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
  81491. return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
  81492. }
  81493. /**
  81494. * Adds statements to the body of a function-like node if it contains a rest parameter.
  81495. *
  81496. * @param statements The statements for the new function body.
  81497. * @param node A function-like node.
  81498. * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
  81499. * part of a constructor declaration with a
  81500. * synthesized call to `super`
  81501. */
  81502. function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
  81503. var prologueStatements = [];
  81504. var parameter = ts.lastOrUndefined(node.parameters);
  81505. if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
  81506. return false;
  81507. }
  81508. // `declarationName` is the name of the local declaration for the parameter.
  81509. var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
  81510. ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
  81511. // `expressionName` is the name of the parameter used in expressions.
  81512. var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
  81513. var restIndex = node.parameters.length - 1;
  81514. var temp = ts.createLoopVariable();
  81515. // var param = [];
  81516. prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
  81517. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  81518. ts.createVariableDeclaration(declarationName,
  81519. /*type*/ undefined, ts.createArrayLiteral([]))
  81520. ])),
  81521. /*location*/ parameter), 1048576 /* CustomPrologue */));
  81522. // for (var _i = restIndex; _i < arguments.length; _i++) {
  81523. // param[_i - restIndex] = arguments[_i];
  81524. // }
  81525. var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
  81526. ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
  81527. ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
  81528. ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
  81529. ? temp
  81530. : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))),
  81531. /*location*/ parameter))
  81532. ]));
  81533. ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
  81534. ts.startOnNewLine(forStatement);
  81535. prologueStatements.push(forStatement);
  81536. if (parameter.name.kind !== 75 /* Identifier */) {
  81537. // do the actual destructuring of the rest parameter if necessary
  81538. prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
  81539. /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
  81540. }
  81541. ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
  81542. return true;
  81543. }
  81544. /**
  81545. * Adds a statement to capture the `this` of a function declaration if it is needed.
  81546. * NOTE: This must be executed *after* the subtree has been visited.
  81547. *
  81548. * @param statements The statements for the new function body.
  81549. * @param node A node.
  81550. */
  81551. function insertCaptureThisForNodeIfNeeded(statements, node) {
  81552. if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
  81553. insertCaptureThisForNode(statements, node, ts.createThis());
  81554. return true;
  81555. }
  81556. return false;
  81557. }
  81558. function insertCaptureThisForNode(statements, node, initializer) {
  81559. enableSubstitutionsForCapturedThis();
  81560. var captureThisStatement = ts.createVariableStatement(
  81561. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  81562. ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"),
  81563. /*type*/ undefined, initializer)
  81564. ]));
  81565. ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
  81566. ts.setSourceMapRange(captureThisStatement, node);
  81567. ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
  81568. }
  81569. function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
  81570. if (hierarchyFacts & 16384 /* NewTarget */) {
  81571. var newTarget = void 0;
  81572. switch (node.kind) {
  81573. case 202 /* ArrowFunction */:
  81574. return statements;
  81575. case 161 /* MethodDeclaration */:
  81576. case 163 /* GetAccessor */:
  81577. case 164 /* SetAccessor */:
  81578. // Methods and accessors cannot be constructors, so 'new.target' will
  81579. // always return 'undefined'.
  81580. newTarget = ts.createVoidZero();
  81581. break;
  81582. case 162 /* Constructor */:
  81583. // Class constructors can only be called with `new`, so `this.constructor`
  81584. // should be relatively safe to use.
  81585. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
  81586. break;
  81587. case 244 /* FunctionDeclaration */:
  81588. case 201 /* FunctionExpression */:
  81589. // Functions can be called or constructed, and may have a `this` due to
  81590. // being a member or when calling an imported function via `other_1.f()`.
  81591. newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 98 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero());
  81592. break;
  81593. default:
  81594. return ts.Debug.failBadSyntaxKind(node);
  81595. }
  81596. var captureNewTargetStatement = ts.createVariableStatement(
  81597. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  81598. ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
  81599. /*type*/ undefined, newTarget)
  81600. ]));
  81601. ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
  81602. if (copyOnWrite) {
  81603. statements = statements.slice();
  81604. }
  81605. ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
  81606. }
  81607. return statements;
  81608. }
  81609. /**
  81610. * Adds statements to the class body function for a class to define the members of the
  81611. * class.
  81612. *
  81613. * @param statements The statements for the class body function.
  81614. * @param node The ClassExpression or ClassDeclaration node.
  81615. */
  81616. function addClassMembers(statements, node) {
  81617. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  81618. var member = _a[_i];
  81619. switch (member.kind) {
  81620. case 222 /* SemicolonClassElement */:
  81621. statements.push(transformSemicolonClassElementToStatement(member));
  81622. break;
  81623. case 161 /* MethodDeclaration */:
  81624. statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
  81625. break;
  81626. case 163 /* GetAccessor */:
  81627. case 164 /* SetAccessor */:
  81628. var accessors = ts.getAllAccessorDeclarations(node.members, member);
  81629. if (member === accessors.firstAccessor) {
  81630. statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
  81631. }
  81632. break;
  81633. case 162 /* Constructor */:
  81634. // Constructors are handled in visitClassExpression/visitClassDeclaration
  81635. break;
  81636. default:
  81637. ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
  81638. break;
  81639. }
  81640. }
  81641. }
  81642. /**
  81643. * Transforms a SemicolonClassElement into a statement for a class body function.
  81644. *
  81645. * @param member The SemicolonClassElement node.
  81646. */
  81647. function transformSemicolonClassElementToStatement(member) {
  81648. return ts.setTextRange(ts.createEmptyStatement(), member);
  81649. }
  81650. /**
  81651. * Transforms a MethodDeclaration into a statement for a class body function.
  81652. *
  81653. * @param receiver The receiver for the member.
  81654. * @param member The MethodDeclaration node.
  81655. */
  81656. function transformClassMethodDeclarationToStatement(receiver, member, container) {
  81657. var commentRange = ts.getCommentRange(member);
  81658. var sourceMapRange = ts.getSourceMapRange(member);
  81659. var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
  81660. var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
  81661. var e;
  81662. if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
  81663. var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
  81664. : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
  81665. : propertyName;
  81666. e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
  81667. }
  81668. else {
  81669. var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
  81670. e = ts.createAssignment(memberName, memberFunction);
  81671. }
  81672. ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
  81673. ts.setSourceMapRange(memberFunction, sourceMapRange);
  81674. var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
  81675. ts.setOriginalNode(statement, member);
  81676. ts.setCommentRange(statement, commentRange);
  81677. // The location for the statement is used to emit comments only.
  81678. // No source map should be emitted for this statement to align with the
  81679. // old emitter.
  81680. ts.setEmitFlags(statement, 48 /* NoSourceMap */);
  81681. return statement;
  81682. }
  81683. /**
  81684. * Transforms a set of related of get/set accessors into a statement for a class body function.
  81685. *
  81686. * @param receiver The receiver for the member.
  81687. * @param accessors The set of related get/set accessors.
  81688. */
  81689. function transformAccessorsToStatement(receiver, accessors, container) {
  81690. var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
  81691. // The location for the statement is used to emit source maps only.
  81692. // No comments should be emitted for this statement to align with the
  81693. // old emitter.
  81694. ts.setEmitFlags(statement, 1536 /* NoComments */);
  81695. ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
  81696. return statement;
  81697. }
  81698. /**
  81699. * Transforms a set of related get/set accessors into an expression for either a class
  81700. * body function or an ObjectLiteralExpression with computed properties.
  81701. *
  81702. * @param receiver The receiver for the member.
  81703. */
  81704. function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
  81705. var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
  81706. // To align with source maps in the old emitter, the receiver and property name
  81707. // arguments are both mapped contiguously to the accessor name.
  81708. var target = ts.getMutableClone(receiver);
  81709. ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
  81710. ts.setSourceMapRange(target, firstAccessor.name);
  81711. var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
  81712. if (ts.isPrivateIdentifier(visitedAccessorName)) {
  81713. return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
  81714. }
  81715. var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
  81716. ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
  81717. ts.setSourceMapRange(propertyName, firstAccessor.name);
  81718. var properties = [];
  81719. if (getAccessor) {
  81720. var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
  81721. ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
  81722. ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
  81723. var getter = ts.createPropertyAssignment("get", getterFunction);
  81724. ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
  81725. properties.push(getter);
  81726. }
  81727. if (setAccessor) {
  81728. var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
  81729. ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
  81730. ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
  81731. var setter = ts.createPropertyAssignment("set", setterFunction);
  81732. ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
  81733. properties.push(setter);
  81734. }
  81735. properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
  81736. var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
  81737. /*typeArguments*/ undefined, [
  81738. target,
  81739. propertyName,
  81740. ts.createObjectLiteral(properties, /*multiLine*/ true)
  81741. ]);
  81742. if (startsOnNewLine) {
  81743. ts.startOnNewLine(call);
  81744. }
  81745. return call;
  81746. }
  81747. /**
  81748. * Visits an ArrowFunction and transforms it into a FunctionExpression.
  81749. *
  81750. * @param node An ArrowFunction node.
  81751. */
  81752. function visitArrowFunction(node) {
  81753. if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
  81754. hierarchyFacts |= 32768 /* CapturedLexicalThis */;
  81755. }
  81756. var savedConvertedLoopState = convertedLoopState;
  81757. convertedLoopState = undefined;
  81758. var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
  81759. var func = ts.createFunctionExpression(
  81760. /*modifiers*/ undefined,
  81761. /*asteriskToken*/ undefined,
  81762. /*name*/ undefined,
  81763. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  81764. /*type*/ undefined, transformFunctionBody(node));
  81765. ts.setTextRange(func, node);
  81766. ts.setOriginalNode(func, node);
  81767. ts.setEmitFlags(func, 8 /* CapturesThis */);
  81768. if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
  81769. enableSubstitutionsForCapturedThis();
  81770. }
  81771. // If an arrow function contains
  81772. exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
  81773. convertedLoopState = savedConvertedLoopState;
  81774. return func;
  81775. }
  81776. /**
  81777. * Visits a FunctionExpression node.
  81778. *
  81779. * @param node a FunctionExpression node.
  81780. */
  81781. function visitFunctionExpression(node) {
  81782. var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
  81783. ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
  81784. : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
  81785. var savedConvertedLoopState = convertedLoopState;
  81786. convertedLoopState = undefined;
  81787. var parameters = ts.visitParameterList(node.parameters, visitor, context);
  81788. var body = transformFunctionBody(node);
  81789. var name = hierarchyFacts & 16384 /* NewTarget */
  81790. ? ts.getLocalName(node)
  81791. : node.name;
  81792. exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
  81793. convertedLoopState = savedConvertedLoopState;
  81794. return ts.updateFunctionExpression(node,
  81795. /*modifiers*/ undefined, node.asteriskToken, name,
  81796. /*typeParameters*/ undefined, parameters,
  81797. /*type*/ undefined, body);
  81798. }
  81799. /**
  81800. * Visits a FunctionDeclaration node.
  81801. *
  81802. * @param node a FunctionDeclaration node.
  81803. */
  81804. function visitFunctionDeclaration(node) {
  81805. var savedConvertedLoopState = convertedLoopState;
  81806. convertedLoopState = undefined;
  81807. var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
  81808. var parameters = ts.visitParameterList(node.parameters, visitor, context);
  81809. var body = transformFunctionBody(node);
  81810. var name = hierarchyFacts & 16384 /* NewTarget */
  81811. ? ts.getLocalName(node)
  81812. : node.name;
  81813. exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
  81814. convertedLoopState = savedConvertedLoopState;
  81815. return ts.updateFunctionDeclaration(node,
  81816. /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
  81817. /*typeParameters*/ undefined, parameters,
  81818. /*type*/ undefined, body);
  81819. }
  81820. /**
  81821. * Transforms a function-like node into a FunctionExpression.
  81822. *
  81823. * @param node The function-like node to transform.
  81824. * @param location The source-map location for the new FunctionExpression.
  81825. * @param name The name of the new FunctionExpression.
  81826. */
  81827. function transformFunctionLikeToExpression(node, location, name, container) {
  81828. var savedConvertedLoopState = convertedLoopState;
  81829. convertedLoopState = undefined;
  81830. var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
  81831. ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
  81832. : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
  81833. var parameters = ts.visitParameterList(node.parameters, visitor, context);
  81834. var body = transformFunctionBody(node);
  81835. if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
  81836. name = ts.getGeneratedNameForNode(node);
  81837. }
  81838. exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
  81839. convertedLoopState = savedConvertedLoopState;
  81840. return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
  81841. /*modifiers*/ undefined, node.asteriskToken, name,
  81842. /*typeParameters*/ undefined, parameters,
  81843. /*type*/ undefined, body), location),
  81844. /*original*/ node);
  81845. }
  81846. /**
  81847. * Transforms the body of a function-like node.
  81848. *
  81849. * @param node A function-like node.
  81850. */
  81851. function transformFunctionBody(node) {
  81852. var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
  81853. var singleLine = false; // indicates whether the block *may* be emitted as a single line
  81854. var statementsLocation;
  81855. var closeBraceLocation;
  81856. var prologue = [];
  81857. var statements = [];
  81858. var body = node.body;
  81859. var statementOffset;
  81860. resumeLexicalEnvironment();
  81861. if (ts.isBlock(body)) {
  81862. // ensureUseStrict is false because no new prologue-directive should be added.
  81863. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
  81864. statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
  81865. }
  81866. multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
  81867. multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
  81868. if (ts.isBlock(body)) {
  81869. // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
  81870. statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
  81871. statementsLocation = body.statements;
  81872. ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
  81873. // If the original body was a multi-line block, this must be a multi-line block.
  81874. if (!multiLine && body.multiLine) {
  81875. multiLine = true;
  81876. }
  81877. }
  81878. else {
  81879. ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
  81880. // To align with the old emitter, we use a synthetic end position on the location
  81881. // for the statement list we synthesize when we down-level an arrow function with
  81882. // an expression function body. This prevents both comments and source maps from
  81883. // being emitted for the end position only.
  81884. statementsLocation = ts.moveRangeEnd(body, -1);
  81885. var equalsGreaterThanToken = node.equalsGreaterThanToken;
  81886. if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
  81887. if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
  81888. singleLine = true;
  81889. }
  81890. else {
  81891. multiLine = true;
  81892. }
  81893. }
  81894. var expression = ts.visitNode(body, visitor, ts.isExpression);
  81895. var returnStatement = ts.createReturn(expression);
  81896. ts.setTextRange(returnStatement, body);
  81897. ts.moveSyntheticComments(returnStatement, body);
  81898. ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
  81899. statements.push(returnStatement);
  81900. // To align with the source map emit for the old emitter, we set a custom
  81901. // source map location for the close brace.
  81902. closeBraceLocation = body;
  81903. }
  81904. ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
  81905. insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
  81906. insertCaptureThisForNodeIfNeeded(prologue, node);
  81907. // If we added any final generated statements, this must be a multi-line block
  81908. if (ts.some(prologue)) {
  81909. multiLine = true;
  81910. }
  81911. statements.unshift.apply(statements, prologue);
  81912. if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
  81913. // no changes were made, preserve the tree
  81914. return body;
  81915. }
  81916. var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
  81917. ts.setTextRange(block, node.body);
  81918. if (!multiLine && singleLine) {
  81919. ts.setEmitFlags(block, 1 /* SingleLine */);
  81920. }
  81921. if (closeBraceLocation) {
  81922. ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
  81923. }
  81924. ts.setOriginalNode(block, node.body);
  81925. return block;
  81926. }
  81927. function visitBlock(node, isFunctionBody) {
  81928. if (isFunctionBody) {
  81929. // A function body is not a block scope.
  81930. return ts.visitEachChild(node, visitor, context);
  81931. }
  81932. var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
  81933. ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
  81934. : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
  81935. var updated = ts.visitEachChild(node, visitor, context);
  81936. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  81937. return updated;
  81938. }
  81939. /**
  81940. * Visits an ExpressionStatement that contains a destructuring assignment.
  81941. *
  81942. * @param node An ExpressionStatement node.
  81943. */
  81944. function visitExpressionStatement(node) {
  81945. // If we are here it is most likely because our expression is a destructuring assignment.
  81946. switch (node.expression.kind) {
  81947. case 200 /* ParenthesizedExpression */:
  81948. return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
  81949. case 209 /* BinaryExpression */:
  81950. return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
  81951. }
  81952. return ts.visitEachChild(node, visitor, context);
  81953. }
  81954. /**
  81955. * Visits a ParenthesizedExpression that may contain a destructuring assignment.
  81956. *
  81957. * @param node A ParenthesizedExpression node.
  81958. * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
  81959. * of a destructuring assignment.
  81960. */
  81961. function visitParenthesizedExpression(node, needsDestructuringValue) {
  81962. // If we are here it is most likely because our expression is a destructuring assignment.
  81963. if (!needsDestructuringValue) {
  81964. // By default we always emit the RHS at the end of a flattened destructuring
  81965. // expression. If we are in a state where we do not need the destructuring value,
  81966. // we pass that information along to the children that care about it.
  81967. switch (node.expression.kind) {
  81968. case 200 /* ParenthesizedExpression */:
  81969. return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
  81970. case 209 /* BinaryExpression */:
  81971. return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
  81972. }
  81973. }
  81974. return ts.visitEachChild(node, visitor, context);
  81975. }
  81976. /**
  81977. * Visits a BinaryExpression that contains a destructuring assignment.
  81978. *
  81979. * @param node A BinaryExpression node.
  81980. * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
  81981. * of a destructuring assignment.
  81982. */
  81983. function visitBinaryExpression(node, needsDestructuringValue) {
  81984. // If we are here it is because this is a destructuring assignment.
  81985. if (ts.isDestructuringAssignment(node)) {
  81986. return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
  81987. }
  81988. return ts.visitEachChild(node, visitor, context);
  81989. }
  81990. function visitVariableStatement(node) {
  81991. var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
  81992. var updated;
  81993. if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) {
  81994. // we are inside a converted loop - hoist variable declarations
  81995. var assignments = void 0;
  81996. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  81997. var decl = _a[_i];
  81998. hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
  81999. if (decl.initializer) {
  82000. var assignment = void 0;
  82001. if (ts.isBindingPattern(decl.name)) {
  82002. assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
  82003. }
  82004. else {
  82005. assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
  82006. ts.setTextRange(assignment, decl);
  82007. }
  82008. assignments = ts.append(assignments, assignment);
  82009. }
  82010. }
  82011. if (assignments) {
  82012. updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
  82013. }
  82014. else {
  82015. // none of declarations has initializer - the entire variable statement can be deleted
  82016. updated = undefined;
  82017. }
  82018. }
  82019. else {
  82020. updated = ts.visitEachChild(node, visitor, context);
  82021. }
  82022. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  82023. return updated;
  82024. }
  82025. /**
  82026. * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
  82027. *
  82028. * @param node A VariableDeclarationList node.
  82029. */
  82030. function visitVariableDeclarationList(node) {
  82031. if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
  82032. if (node.flags & 3 /* BlockScoped */) {
  82033. enableSubstitutionsForBlockScopedBindings();
  82034. }
  82035. var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
  82036. ? visitVariableDeclarationInLetDeclarationList
  82037. : visitVariableDeclaration);
  82038. var declarationList = ts.createVariableDeclarationList(declarations);
  82039. ts.setOriginalNode(declarationList, node);
  82040. ts.setTextRange(declarationList, node);
  82041. ts.setCommentRange(declarationList, node);
  82042. // If the first or last declaration is a binding pattern, we need to modify
  82043. // the source map range for the declaration list.
  82044. if (node.transformFlags & 131072 /* ContainsBindingPattern */
  82045. && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
  82046. ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
  82047. }
  82048. return declarationList;
  82049. }
  82050. return ts.visitEachChild(node, visitor, context);
  82051. }
  82052. function getRangeUnion(declarations) {
  82053. // declarations may not be sorted by position.
  82054. // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
  82055. var pos = -1, end = -1;
  82056. for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
  82057. var node = declarations_10[_i];
  82058. pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
  82059. end = Math.max(end, node.end);
  82060. }
  82061. return ts.createRange(pos, end);
  82062. }
  82063. /**
  82064. * Gets a value indicating whether we should emit an explicit initializer for a variable
  82065. * declaration in a `let` declaration list.
  82066. *
  82067. * @param node A VariableDeclaration node.
  82068. */
  82069. function shouldEmitExplicitInitializerForLetDeclaration(node) {
  82070. // Nested let bindings might need to be initialized explicitly to preserve
  82071. // ES6 semantic:
  82072. //
  82073. // { let x = 1; }
  82074. // { let x; } // x here should be undefined. not 1
  82075. //
  82076. // Top level bindings never collide with anything and thus don't require
  82077. // explicit initialization. As for nested let bindings there are two cases:
  82078. //
  82079. // - Nested let bindings that were not renamed definitely should be
  82080. // initialized explicitly:
  82081. //
  82082. // { let x = 1; }
  82083. // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
  82084. //
  82085. // Without explicit initialization code in /*1*/ can be executed even if
  82086. // some-condition is evaluated to false.
  82087. //
  82088. // - Renaming introduces fresh name that should not collide with any
  82089. // existing names, however renamed bindings sometimes also should be
  82090. // explicitly initialized. One particular case: non-captured binding
  82091. // declared inside loop body (but not in loop initializer):
  82092. //
  82093. // let x;
  82094. // for (;;) {
  82095. // let x;
  82096. // }
  82097. //
  82098. // In downlevel codegen inner 'x' will be renamed so it won't collide
  82099. // with outer 'x' however it will should be reset on every iteration as
  82100. // if it was declared anew.
  82101. //
  82102. // * Why non-captured binding?
  82103. // - Because if loop contains block scoped binding captured in some
  82104. // function then loop body will be rewritten to have a fresh scope
  82105. // on every iteration so everything will just work.
  82106. //
  82107. // * Why loop initializer is excluded?
  82108. // - Since we've introduced a fresh name it already will be undefined.
  82109. var flags = resolver.getNodeCheckFlags(node);
  82110. var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
  82111. var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
  82112. var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
  82113. || (isCapturedInFunction
  82114. && isDeclaredInLoop
  82115. && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
  82116. var emitExplicitInitializer = !emittedAsTopLevel
  82117. && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
  82118. && (!resolver.isDeclarationWithCollidingName(node)
  82119. || (isDeclaredInLoop
  82120. && !isCapturedInFunction
  82121. && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
  82122. return emitExplicitInitializer;
  82123. }
  82124. /**
  82125. * Visits a VariableDeclaration in a `let` declaration list.
  82126. *
  82127. * @param node A VariableDeclaration node.
  82128. */
  82129. function visitVariableDeclarationInLetDeclarationList(node) {
  82130. // For binding pattern names that lack initializers there is no point to emit
  82131. // explicit initializer since downlevel codegen for destructuring will fail
  82132. // in the absence of initializer so all binding elements will say uninitialized
  82133. var name = node.name;
  82134. if (ts.isBindingPattern(name)) {
  82135. return visitVariableDeclaration(node);
  82136. }
  82137. if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
  82138. var clone_3 = ts.getMutableClone(node);
  82139. clone_3.initializer = ts.createVoidZero();
  82140. return clone_3;
  82141. }
  82142. return ts.visitEachChild(node, visitor, context);
  82143. }
  82144. /**
  82145. * Visits a VariableDeclaration node with a binding pattern.
  82146. *
  82147. * @param node A VariableDeclaration node.
  82148. */
  82149. function visitVariableDeclaration(node) {
  82150. var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
  82151. var updated;
  82152. if (ts.isBindingPattern(node.name)) {
  82153. updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */,
  82154. /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
  82155. }
  82156. else {
  82157. updated = ts.visitEachChild(node, visitor, context);
  82158. }
  82159. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  82160. return updated;
  82161. }
  82162. function recordLabel(node) {
  82163. convertedLoopState.labels.set(ts.idText(node.label), true);
  82164. }
  82165. function resetLabel(node) {
  82166. convertedLoopState.labels.set(ts.idText(node.label), false);
  82167. }
  82168. function visitLabeledStatement(node) {
  82169. if (convertedLoopState && !convertedLoopState.labels) {
  82170. convertedLoopState.labels = ts.createMap();
  82171. }
  82172. var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
  82173. return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
  82174. ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
  82175. : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
  82176. }
  82177. function visitIterationStatement(node, outermostLabeledStatement) {
  82178. switch (node.kind) {
  82179. case 228 /* DoStatement */:
  82180. case 229 /* WhileStatement */:
  82181. return visitDoOrWhileStatement(node, outermostLabeledStatement);
  82182. case 230 /* ForStatement */:
  82183. return visitForStatement(node, outermostLabeledStatement);
  82184. case 231 /* ForInStatement */:
  82185. return visitForInStatement(node, outermostLabeledStatement);
  82186. case 232 /* ForOfStatement */:
  82187. return visitForOfStatement(node, outermostLabeledStatement);
  82188. }
  82189. }
  82190. function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
  82191. var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
  82192. var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
  82193. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  82194. return updated;
  82195. }
  82196. function visitDoOrWhileStatement(node, outermostLabeledStatement) {
  82197. return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
  82198. }
  82199. function visitForStatement(node, outermostLabeledStatement) {
  82200. return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
  82201. }
  82202. function visitForInStatement(node, outermostLabeledStatement) {
  82203. return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
  82204. }
  82205. function visitForOfStatement(node, outermostLabeledStatement) {
  82206. return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
  82207. }
  82208. function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
  82209. var statements = [];
  82210. var initializer = node.initializer;
  82211. if (ts.isVariableDeclarationList(initializer)) {
  82212. if (node.initializer.flags & 3 /* BlockScoped */) {
  82213. enableSubstitutionsForBlockScopedBindings();
  82214. }
  82215. var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
  82216. if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
  82217. // This works whether the declaration is a var, let, or const.
  82218. // It will use rhsIterationValue _a[_i] as the initializer.
  82219. var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
  82220. var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
  82221. ts.setOriginalNode(declarationList, node.initializer);
  82222. // Adjust the source map range for the first declaration to align with the old
  82223. // emitter.
  82224. ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
  82225. statements.push(ts.createVariableStatement(
  82226. /*modifiers*/ undefined, declarationList));
  82227. }
  82228. else {
  82229. // The following call does not include the initializer, so we have
  82230. // to emit it separately.
  82231. statements.push(ts.setTextRange(ts.createVariableStatement(
  82232. /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
  82233. ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined),
  82234. /*type*/ undefined, boundValue)
  82235. ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
  82236. }
  82237. }
  82238. else {
  82239. // Initializer is an expression. Emit the expression in the body, so that it's
  82240. // evaluated on every iteration.
  82241. var assignment = ts.createAssignment(initializer, boundValue);
  82242. if (ts.isDestructuringAssignment(assignment)) {
  82243. ts.aggregateTransformFlags(assignment);
  82244. statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
  82245. }
  82246. else {
  82247. assignment.end = initializer.end;
  82248. statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
  82249. }
  82250. }
  82251. if (convertedLoopBodyStatements) {
  82252. return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
  82253. }
  82254. else {
  82255. var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
  82256. if (ts.isBlock(statement)) {
  82257. return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
  82258. }
  82259. else {
  82260. statements.push(statement);
  82261. return createSyntheticBlockForConvertedStatements(statements);
  82262. }
  82263. }
  82264. }
  82265. function createSyntheticBlockForConvertedStatements(statements) {
  82266. return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements),
  82267. /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
  82268. }
  82269. function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
  82270. // The following ES6 code:
  82271. //
  82272. // for (let v of expr) { }
  82273. //
  82274. // should be emitted as
  82275. //
  82276. // for (var _i = 0, _a = expr; _i < _a.length; _i++) {
  82277. // var v = _a[_i];
  82278. // }
  82279. //
  82280. // where _a and _i are temps emitted to capture the RHS and the counter,
  82281. // respectively.
  82282. // When the left hand side is an expression instead of a let declaration,
  82283. // the "let v" is not emitted.
  82284. // When the left hand side is a let/const, the v is renamed if there is
  82285. // another v in scope.
  82286. // Note that all assignments to the LHS are emitted in the body, including
  82287. // all destructuring.
  82288. // Note also that because an extra statement is needed to assign to the LHS,
  82289. // for-of bodies are always emitted as blocks.
  82290. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  82291. // In the case where the user wrote an identifier as the RHS, like this:
  82292. //
  82293. // for (let v of arr) { }
  82294. //
  82295. // we don't want to emit a temporary variable for the RHS, just use it directly.
  82296. var counter = ts.createLoopVariable();
  82297. var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
  82298. // The old emitter does not emit source maps for the expression
  82299. ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
  82300. var forStatement = ts.setTextRange(ts.createFor(
  82301. /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
  82302. ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
  82303. ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
  82304. ]), node.expression), 2097152 /* NoHoisting */),
  82305. /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression),
  82306. /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression),
  82307. /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)),
  82308. /*location*/ node);
  82309. // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
  82310. ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
  82311. ts.setTextRange(forStatement, node);
  82312. return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
  82313. }
  82314. function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
  82315. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  82316. var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
  82317. var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
  82318. var errorRecord = ts.createUniqueName("e");
  82319. var catchVariable = ts.getGeneratedNameForNode(errorRecord);
  82320. var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
  82321. var values = ts.createValuesHelper(context, expression, node.expression);
  82322. var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
  82323. hoistVariableDeclaration(errorRecord);
  82324. hoistVariableDeclaration(returnMethod);
  82325. // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
  82326. var initializer = ancestorFacts & 1024 /* IterationContainer */
  82327. ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
  82328. : values;
  82329. var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
  82330. /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
  82331. ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
  82332. ts.createVariableDeclaration(result, /*type*/ undefined, next)
  82333. ]), node.expression), 2097152 /* NoHoisting */),
  82334. /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")),
  82335. /*incrementor*/ ts.createAssignment(result, next),
  82336. /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)),
  82337. /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
  82338. return ts.createTry(ts.createBlock([
  82339. ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
  82340. ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
  82341. ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
  82342. ts.createPropertyAssignment("error", catchVariable)
  82343. ])))
  82344. ]), 1 /* SingleLine */)), ts.createBlock([
  82345. ts.createTry(
  82346. /*tryBlock*/ ts.createBlock([
  82347. ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */),
  82348. ]),
  82349. /*catchClause*/ undefined,
  82350. /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
  82351. ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
  82352. ]), 1 /* SingleLine */))
  82353. ]));
  82354. }
  82355. /**
  82356. * Visits an ObjectLiteralExpression with computed property names.
  82357. *
  82358. * @param node An ObjectLiteralExpression node.
  82359. */
  82360. function visitObjectLiteralExpression(node) {
  82361. // We are here because a ComputedPropertyName was used somewhere in the expression.
  82362. var properties = node.properties;
  82363. var numProperties = properties.length;
  82364. // Find the first computed property.
  82365. // Everything until that point can be emitted as part of the initial object literal.
  82366. var numInitialProperties = numProperties;
  82367. var numInitialPropertiesWithoutYield = numProperties;
  82368. for (var i = 0; i < numProperties; i++) {
  82369. var property = properties[i];
  82370. if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
  82371. && i < numInitialPropertiesWithoutYield) {
  82372. numInitialPropertiesWithoutYield = i;
  82373. }
  82374. if (property.name.kind === 154 /* ComputedPropertyName */) {
  82375. numInitialProperties = i;
  82376. break;
  82377. }
  82378. }
  82379. if (numInitialProperties !== numProperties) {
  82380. if (numInitialPropertiesWithoutYield < numInitialProperties) {
  82381. numInitialProperties = numInitialPropertiesWithoutYield;
  82382. }
  82383. // For computed properties, we need to create a unique handle to the object
  82384. // literal so we can modify it without risking internal assignments tainting the object.
  82385. var temp = ts.createTempVariable(hoistVariableDeclaration);
  82386. // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
  82387. var expressions = [];
  82388. var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
  82389. if (node.multiLine) {
  82390. ts.startOnNewLine(assignment);
  82391. }
  82392. expressions.push(assignment);
  82393. addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
  82394. // We need to clone the temporary identifier so that we can write it on a
  82395. // new line
  82396. expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
  82397. return ts.inlineExpressions(expressions);
  82398. }
  82399. return ts.visitEachChild(node, visitor, context);
  82400. }
  82401. function shouldConvertPartOfIterationStatement(node) {
  82402. return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
  82403. }
  82404. function shouldConvertInitializerOfForStatement(node) {
  82405. return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
  82406. }
  82407. function shouldConvertConditionOfForStatement(node) {
  82408. return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
  82409. }
  82410. function shouldConvertIncrementorOfForStatement(node) {
  82411. return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
  82412. }
  82413. function shouldConvertIterationStatement(node) {
  82414. return shouldConvertBodyOfIterationStatement(node)
  82415. || shouldConvertInitializerOfForStatement(node);
  82416. }
  82417. function shouldConvertBodyOfIterationStatement(node) {
  82418. return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
  82419. }
  82420. /**
  82421. * Records constituents of name for the given variable to be hoisted in the outer scope.
  82422. */
  82423. function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
  82424. if (!state.hoistedLocalVariables) {
  82425. state.hoistedLocalVariables = [];
  82426. }
  82427. visit(node.name);
  82428. function visit(node) {
  82429. if (node.kind === 75 /* Identifier */) {
  82430. state.hoistedLocalVariables.push(node);
  82431. }
  82432. else {
  82433. for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
  82434. var element = _a[_i];
  82435. if (!ts.isOmittedExpression(element)) {
  82436. visit(element.name);
  82437. }
  82438. }
  82439. }
  82440. }
  82441. }
  82442. function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
  82443. if (!shouldConvertIterationStatement(node)) {
  82444. var saveAllowedNonLabeledJumps = void 0;
  82445. if (convertedLoopState) {
  82446. // we get here if we are trying to emit normal loop loop inside converted loop
  82447. // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
  82448. saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
  82449. convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
  82450. }
  82451. var result = convert
  82452. ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
  82453. : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
  82454. if (convertedLoopState) {
  82455. convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
  82456. }
  82457. return result;
  82458. }
  82459. var currentState = createConvertedLoopState(node);
  82460. var statements = [];
  82461. var outerConvertedLoopState = convertedLoopState;
  82462. convertedLoopState = currentState;
  82463. var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
  82464. var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
  82465. convertedLoopState = outerConvertedLoopState;
  82466. if (initializerFunction)
  82467. statements.push(initializerFunction.functionDeclaration);
  82468. if (bodyFunction)
  82469. statements.push(bodyFunction.functionDeclaration);
  82470. addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
  82471. if (initializerFunction) {
  82472. statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
  82473. }
  82474. var loop;
  82475. if (bodyFunction) {
  82476. if (convert) {
  82477. loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
  82478. }
  82479. else {
  82480. var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
  82481. ts.aggregateTransformFlags(clone_4);
  82482. loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
  82483. }
  82484. }
  82485. else {
  82486. var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  82487. ts.aggregateTransformFlags(clone_5);
  82488. loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
  82489. }
  82490. statements.push(loop);
  82491. return statements;
  82492. }
  82493. function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
  82494. switch (node.kind) {
  82495. case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
  82496. case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
  82497. case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
  82498. case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
  82499. case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
  82500. default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
  82501. }
  82502. }
  82503. function convertForStatement(node, initializerFunction, convertedLoopBody) {
  82504. var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
  82505. var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
  82506. return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody);
  82507. }
  82508. function convertForOfStatement(node, convertedLoopBody) {
  82509. return ts.updateForOf(node,
  82510. /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
  82511. }
  82512. function convertForInStatement(node, convertedLoopBody) {
  82513. return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
  82514. }
  82515. function convertDoStatement(node, convertedLoopBody) {
  82516. return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
  82517. }
  82518. function convertWhileStatement(node, convertedLoopBody) {
  82519. return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
  82520. }
  82521. function createConvertedLoopState(node) {
  82522. var loopInitializer;
  82523. switch (node.kind) {
  82524. case 230 /* ForStatement */:
  82525. case 231 /* ForInStatement */:
  82526. case 232 /* ForOfStatement */:
  82527. var initializer = node.initializer;
  82528. if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
  82529. loopInitializer = initializer;
  82530. }
  82531. break;
  82532. }
  82533. // variables that will be passed to the loop as parameters
  82534. var loopParameters = [];
  82535. // variables declared in the loop initializer that will be changed inside the loop
  82536. var loopOutParameters = [];
  82537. if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
  82538. var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
  82539. for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
  82540. var decl = _a[_i];
  82541. processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
  82542. }
  82543. }
  82544. var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
  82545. if (convertedLoopState) {
  82546. // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
  82547. // if outer converted loop has already accumulated some state - pass it through
  82548. if (convertedLoopState.argumentsName) {
  82549. // outer loop has already used 'arguments' so we've already have some name to alias it
  82550. // use the same name in all nested loops
  82551. currentState.argumentsName = convertedLoopState.argumentsName;
  82552. }
  82553. if (convertedLoopState.thisName) {
  82554. // outer loop has already used 'this' so we've already have some name to alias it
  82555. // use the same name in all nested loops
  82556. currentState.thisName = convertedLoopState.thisName;
  82557. }
  82558. if (convertedLoopState.hoistedLocalVariables) {
  82559. // we've already collected some non-block scoped variable declarations in enclosing loop
  82560. // use the same storage in nested loop
  82561. currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
  82562. }
  82563. }
  82564. return currentState;
  82565. }
  82566. function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
  82567. var extraVariableDeclarations;
  82568. // propagate state from the inner loop to the outer loop if necessary
  82569. if (state.argumentsName) {
  82570. // if alias for arguments is set
  82571. if (outerState) {
  82572. // pass it to outer converted loop
  82573. outerState.argumentsName = state.argumentsName;
  82574. }
  82575. else {
  82576. // this is top level converted loop and we need to create an alias for 'arguments' object
  82577. (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName,
  82578. /*type*/ undefined, ts.createIdentifier("arguments")));
  82579. }
  82580. }
  82581. if (state.thisName) {
  82582. // if alias for this is set
  82583. if (outerState) {
  82584. // pass it to outer converted loop
  82585. outerState.thisName = state.thisName;
  82586. }
  82587. else {
  82588. // this is top level converted loop so we need to create an alias for 'this' here
  82589. // NOTE:
  82590. // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
  82591. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
  82592. (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName,
  82593. /*type*/ undefined, ts.createIdentifier("this")));
  82594. }
  82595. }
  82596. if (state.hoistedLocalVariables) {
  82597. // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
  82598. if (outerState) {
  82599. // pass them to outer converted loop
  82600. outerState.hoistedLocalVariables = state.hoistedLocalVariables;
  82601. }
  82602. else {
  82603. if (!extraVariableDeclarations) {
  82604. extraVariableDeclarations = [];
  82605. }
  82606. // hoist collected variable declarations
  82607. for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
  82608. var identifier = _a[_i];
  82609. extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
  82610. }
  82611. }
  82612. }
  82613. // add extra variables to hold out parameters if necessary
  82614. if (state.loopOutParameters.length) {
  82615. if (!extraVariableDeclarations) {
  82616. extraVariableDeclarations = [];
  82617. }
  82618. for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
  82619. var outParam = _c[_b];
  82620. extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
  82621. }
  82622. }
  82623. if (state.conditionVariable) {
  82624. if (!extraVariableDeclarations) {
  82625. extraVariableDeclarations = [];
  82626. }
  82627. extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
  82628. }
  82629. // create variable statement to hold all introduced variable declarations
  82630. if (extraVariableDeclarations) {
  82631. statements.push(ts.createVariableStatement(
  82632. /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
  82633. }
  82634. }
  82635. function createOutVariable(p) {
  82636. return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
  82637. }
  82638. /**
  82639. * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
  82640. * that is captured in a closure inside of the initializer. The `_loop_init` function is
  82641. * used to preserve the per-iteration environment semantics of
  82642. * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
  82643. */
  82644. function createFunctionForInitializerOfForStatement(node, currentState) {
  82645. var functionName = ts.createUniqueName("_loop_init");
  82646. var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
  82647. var emitFlags = 0 /* None */;
  82648. if (currentState.containsLexicalThis)
  82649. emitFlags |= 8 /* CapturesThis */;
  82650. if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
  82651. emitFlags |= 262144 /* AsyncFunctionBody */;
  82652. var statements = [];
  82653. statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
  82654. copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
  82655. // This transforms the following ES2015 syntax:
  82656. //
  82657. // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
  82658. // // loop body
  82659. // }
  82660. //
  82661. // Into the following ES5 syntax:
  82662. //
  82663. // var _loop_init_1 = function () {
  82664. // var i = (setImmediate(() => console.log(i)), 0);
  82665. // out_i_1 = i;
  82666. // };
  82667. // var out_i_1;
  82668. // _loop_init_1();
  82669. // for (var i = out_i_1; i < 2; i++) {
  82670. // // loop body
  82671. // }
  82672. //
  82673. // Which prevents mutations to `i` in the per-iteration environment of the body
  82674. // from affecting the initial value for `i` outside of the per-iteration environment.
  82675. var functionDeclaration = ts.createVariableStatement(
  82676. /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
  82677. ts.createVariableDeclaration(functionName,
  82678. /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
  82679. /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined,
  82680. /*name*/ undefined,
  82681. /*typeParameters*/ undefined,
  82682. /*parameters*/ undefined,
  82683. /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
  82684. ]), 2097152 /* NoHoisting */));
  82685. var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
  82686. return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
  82687. }
  82688. /**
  82689. * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
  82690. * that is captured in a closure inside of the loop body. The `_loop` function is used to
  82691. * preserve the per-iteration environment semantics of
  82692. * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
  82693. */
  82694. function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
  82695. var functionName = ts.createUniqueName("_loop");
  82696. startLexicalEnvironment();
  82697. var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
  82698. var lexicalEnvironment = endLexicalEnvironment();
  82699. var statements = [];
  82700. if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
  82701. // If a block-scoped variable declared in the initializer of `node` is captured in
  82702. // the condition or incrementor, we must move the condition and incrementor into
  82703. // the body of the for loop.
  82704. //
  82705. // This transforms the following ES2015 syntax:
  82706. //
  82707. // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
  82708. // // loop body
  82709. // }
  82710. //
  82711. // Into the following ES5 syntax:
  82712. //
  82713. // var _loop_1 = function (i) {
  82714. // if (inc_1)
  82715. // setImmediate(() => console.log(i)), i++;
  82716. // else
  82717. // inc_1 = true;
  82718. // if (!(setImmediate(() => console.log(i)), i < 2))
  82719. // return out_i_1 = i, "break";
  82720. // // loop body
  82721. // out_i_1 = i;
  82722. // }
  82723. // var out_i_1, inc_1 = false;
  82724. // for (var i = 0;;) {
  82725. // var state_1 = _loop_1(i);
  82726. // i = out_i_1;
  82727. // if (state_1 === "break")
  82728. // break;
  82729. // }
  82730. //
  82731. // Which prevents mutations to `i` in the per-iteration environment of the body
  82732. // from affecting the value of `i` in the previous per-iteration environment.
  82733. //
  82734. // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
  82735. // environment that is carried over to the next iteration of the loop. As a result,
  82736. // we must indicate whether this is the first evaluation of the loop body so that
  82737. // we only evaluate the incrementor on subsequent evaluations.
  82738. currentState.conditionVariable = ts.createUniqueName("inc");
  82739. statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
  82740. if (shouldConvertConditionOfForStatement(node)) {
  82741. statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
  82742. }
  82743. }
  82744. if (ts.isBlock(statement)) {
  82745. ts.addRange(statements, statement.statements);
  82746. }
  82747. else {
  82748. statements.push(statement);
  82749. }
  82750. copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
  82751. ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
  82752. var loopBody = ts.createBlock(statements, /*multiLine*/ true);
  82753. if (ts.isBlock(statement))
  82754. ts.setOriginalNode(loopBody, statement);
  82755. var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
  82756. var emitFlags = 0;
  82757. if (currentState.containsLexicalThis)
  82758. emitFlags |= 8 /* CapturesThis */;
  82759. if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
  82760. emitFlags |= 262144 /* AsyncFunctionBody */;
  82761. // This transforms the following ES2015 syntax (in addition to other variations):
  82762. //
  82763. // for (let i = 0; i < 2; i++) {
  82764. // setImmediate(() => console.log(i));
  82765. // }
  82766. //
  82767. // Into the following ES5 syntax:
  82768. //
  82769. // var _loop_1 = function (i) {
  82770. // setImmediate(() => console.log(i));
  82771. // };
  82772. // for (var i = 0; i < 2; i++) {
  82773. // _loop_1(i);
  82774. // }
  82775. var functionDeclaration = ts.createVariableStatement(
  82776. /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
  82777. ts.createVariableDeclaration(functionName,
  82778. /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
  82779. /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined,
  82780. /*name*/ undefined,
  82781. /*typeParameters*/ undefined, currentState.loopParameters,
  82782. /*type*/ undefined, loopBody), emitFlags))
  82783. ]), 2097152 /* NoHoisting */));
  82784. var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
  82785. return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
  82786. }
  82787. function copyOutParameter(outParam, copyDirection) {
  82788. var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
  82789. var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
  82790. return ts.createBinary(target, 62 /* EqualsToken */, source);
  82791. }
  82792. function copyOutParameters(outParams, partFlags, copyDirection, statements) {
  82793. for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
  82794. var outParam = outParams_1[_i];
  82795. if (outParam.flags & partFlags) {
  82796. statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
  82797. }
  82798. }
  82799. }
  82800. function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
  82801. var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
  82802. var callResult = containsYield
  82803. ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
  82804. : call;
  82805. return ts.createStatement(callResult);
  82806. }
  82807. function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
  82808. var statements = [];
  82809. // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
  82810. // simple loops are emitted as just 'loop()';
  82811. // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
  82812. var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
  82813. !state.labeledNonLocalBreaks &&
  82814. !state.labeledNonLocalContinues;
  82815. var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
  82816. var callResult = containsYield
  82817. ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
  82818. : call;
  82819. if (isSimpleLoop) {
  82820. statements.push(ts.createExpressionStatement(callResult));
  82821. copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
  82822. }
  82823. else {
  82824. var loopResultName = ts.createUniqueName("state");
  82825. var stateVariable = ts.createVariableStatement(
  82826. /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
  82827. statements.push(stateVariable);
  82828. copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
  82829. if (state.nonLocalJumps & 8 /* Return */) {
  82830. var returnStatement = void 0;
  82831. if (outerState) {
  82832. outerState.nonLocalJumps |= 8 /* Return */;
  82833. returnStatement = ts.createReturn(loopResultName);
  82834. }
  82835. else {
  82836. returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
  82837. }
  82838. statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
  82839. }
  82840. if (state.nonLocalJumps & 2 /* Break */) {
  82841. statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
  82842. }
  82843. if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
  82844. var caseClauses = [];
  82845. processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
  82846. processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
  82847. statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
  82848. }
  82849. }
  82850. return statements;
  82851. }
  82852. function setLabeledJump(state, isBreak, labelText, labelMarker) {
  82853. if (isBreak) {
  82854. if (!state.labeledNonLocalBreaks) {
  82855. state.labeledNonLocalBreaks = ts.createMap();
  82856. }
  82857. state.labeledNonLocalBreaks.set(labelText, labelMarker);
  82858. }
  82859. else {
  82860. if (!state.labeledNonLocalContinues) {
  82861. state.labeledNonLocalContinues = ts.createMap();
  82862. }
  82863. state.labeledNonLocalContinues.set(labelText, labelMarker);
  82864. }
  82865. }
  82866. function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
  82867. if (!table) {
  82868. return;
  82869. }
  82870. table.forEach(function (labelMarker, labelText) {
  82871. var statements = [];
  82872. // if there are no outer converted loop or outer label in question is located inside outer converted loop
  82873. // then emit labeled break\continue
  82874. // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
  82875. if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
  82876. var label = ts.createIdentifier(labelText);
  82877. statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
  82878. }
  82879. else {
  82880. setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
  82881. statements.push(ts.createReturn(loopResultName));
  82882. }
  82883. caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
  82884. });
  82885. }
  82886. function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
  82887. var name = decl.name;
  82888. if (ts.isBindingPattern(name)) {
  82889. for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
  82890. var element = _a[_i];
  82891. if (!ts.isOmittedExpression(element)) {
  82892. processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
  82893. }
  82894. }
  82895. }
  82896. else {
  82897. loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
  82898. var checkFlags = resolver.getNodeCheckFlags(decl);
  82899. if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
  82900. var outParamName = ts.createUniqueName("out_" + ts.idText(name));
  82901. var flags = 0;
  82902. if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
  82903. flags |= 1 /* Body */;
  82904. }
  82905. if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
  82906. flags |= 2 /* Initializer */;
  82907. }
  82908. loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
  82909. }
  82910. }
  82911. }
  82912. /**
  82913. * Adds the members of an object literal to an array of expressions.
  82914. *
  82915. * @param expressions An array of expressions.
  82916. * @param node An ObjectLiteralExpression node.
  82917. * @param receiver The receiver for members of the ObjectLiteralExpression.
  82918. * @param numInitialNonComputedProperties The number of initial properties without
  82919. * computed property names.
  82920. */
  82921. function addObjectLiteralMembers(expressions, node, receiver, start) {
  82922. var properties = node.properties;
  82923. var numProperties = properties.length;
  82924. for (var i = start; i < numProperties; i++) {
  82925. var property = properties[i];
  82926. switch (property.kind) {
  82927. case 163 /* GetAccessor */:
  82928. case 164 /* SetAccessor */:
  82929. var accessors = ts.getAllAccessorDeclarations(node.properties, property);
  82930. if (property === accessors.firstAccessor) {
  82931. expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
  82932. }
  82933. break;
  82934. case 161 /* MethodDeclaration */:
  82935. expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
  82936. break;
  82937. case 281 /* PropertyAssignment */:
  82938. expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
  82939. break;
  82940. case 282 /* ShorthandPropertyAssignment */:
  82941. expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
  82942. break;
  82943. default:
  82944. ts.Debug.failBadSyntaxKind(node);
  82945. break;
  82946. }
  82947. }
  82948. }
  82949. /**
  82950. * Transforms a PropertyAssignment node into an expression.
  82951. *
  82952. * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
  82953. * @param property The PropertyAssignment node.
  82954. * @param receiver The receiver for the assignment.
  82955. */
  82956. function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
  82957. var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
  82958. ts.setTextRange(expression, property);
  82959. if (startsOnNewLine) {
  82960. ts.startOnNewLine(expression);
  82961. }
  82962. return expression;
  82963. }
  82964. /**
  82965. * Transforms a ShorthandPropertyAssignment node into an expression.
  82966. *
  82967. * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
  82968. * @param property The ShorthandPropertyAssignment node.
  82969. * @param receiver The receiver for the assignment.
  82970. */
  82971. function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
  82972. var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
  82973. ts.setTextRange(expression, property);
  82974. if (startsOnNewLine) {
  82975. ts.startOnNewLine(expression);
  82976. }
  82977. return expression;
  82978. }
  82979. /**
  82980. * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
  82981. *
  82982. * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
  82983. * @param method The MethodDeclaration node.
  82984. * @param receiver The receiver for the assignment.
  82985. */
  82986. function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
  82987. var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
  82988. ts.setTextRange(expression, method);
  82989. if (startsOnNewLine) {
  82990. ts.startOnNewLine(expression);
  82991. }
  82992. return expression;
  82993. }
  82994. function visitCatchClause(node) {
  82995. var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
  82996. var updated;
  82997. ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
  82998. if (ts.isBindingPattern(node.variableDeclaration.name)) {
  82999. var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
  83000. var newVariableDeclaration = ts.createVariableDeclaration(temp);
  83001. ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
  83002. var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
  83003. var list = ts.createVariableDeclarationList(vars);
  83004. ts.setTextRange(list, node.variableDeclaration);
  83005. var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
  83006. updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
  83007. }
  83008. else {
  83009. updated = ts.visitEachChild(node, visitor, context);
  83010. }
  83011. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  83012. return updated;
  83013. }
  83014. function addStatementToStartOfBlock(block, statement) {
  83015. var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
  83016. return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
  83017. }
  83018. /**
  83019. * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
  83020. * PropertyAssignment.
  83021. *
  83022. * @param node A MethodDeclaration node.
  83023. */
  83024. function visitMethodDeclaration(node) {
  83025. // We should only get here for methods on an object literal with regular identifier names.
  83026. // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
  83027. // Methods with computed property names are handled in visitObjectLiteralExpression.
  83028. ts.Debug.assert(!ts.isComputedPropertyName(node.name));
  83029. var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
  83030. ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
  83031. return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression),
  83032. /*location*/ node);
  83033. }
  83034. /**
  83035. * Visits an AccessorDeclaration of an ObjectLiteralExpression.
  83036. *
  83037. * @param node An AccessorDeclaration node.
  83038. */
  83039. function visitAccessorDeclaration(node) {
  83040. ts.Debug.assert(!ts.isComputedPropertyName(node.name));
  83041. var savedConvertedLoopState = convertedLoopState;
  83042. convertedLoopState = undefined;
  83043. var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
  83044. var updated;
  83045. var parameters = ts.visitParameterList(node.parameters, visitor, context);
  83046. var body = transformFunctionBody(node);
  83047. if (node.kind === 163 /* GetAccessor */) {
  83048. updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
  83049. }
  83050. else {
  83051. updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
  83052. }
  83053. exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
  83054. convertedLoopState = savedConvertedLoopState;
  83055. return updated;
  83056. }
  83057. /**
  83058. * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
  83059. *
  83060. * @param node A ShorthandPropertyAssignment node.
  83061. */
  83062. function visitShorthandPropertyAssignment(node) {
  83063. return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)),
  83064. /*location*/ node);
  83065. }
  83066. function visitComputedPropertyName(node) {
  83067. return ts.visitEachChild(node, visitor, context);
  83068. }
  83069. /**
  83070. * Visits a YieldExpression node.
  83071. *
  83072. * @param node A YieldExpression node.
  83073. */
  83074. function visitYieldExpression(node) {
  83075. // `yield` expressions are transformed using the generators transformer.
  83076. return ts.visitEachChild(node, visitor, context);
  83077. }
  83078. /**
  83079. * Visits an ArrayLiteralExpression that contains a spread element.
  83080. *
  83081. * @param node An ArrayLiteralExpression node.
  83082. */
  83083. function visitArrayLiteralExpression(node) {
  83084. if (ts.some(node.elements, ts.isSpreadElement)) {
  83085. // We are here because we contain a SpreadElementExpression.
  83086. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
  83087. }
  83088. return ts.visitEachChild(node, visitor, context);
  83089. }
  83090. /**
  83091. * Visits a CallExpression that contains either a spread element or `super`.
  83092. *
  83093. * @param node a CallExpression.
  83094. */
  83095. function visitCallExpression(node) {
  83096. if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
  83097. return visitTypeScriptClassWrapper(node);
  83098. }
  83099. var expression = ts.skipOuterExpressions(node.expression);
  83100. if (expression.kind === 102 /* SuperKeyword */ ||
  83101. ts.isSuperProperty(expression) ||
  83102. ts.some(node.arguments, ts.isSpreadElement)) {
  83103. return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
  83104. }
  83105. return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
  83106. /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
  83107. }
  83108. function visitTypeScriptClassWrapper(node) {
  83109. // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
  83110. // The wrapper has a form similar to:
  83111. //
  83112. // (function() {
  83113. // class C { // 1
  83114. // }
  83115. // C.x = 1; // 2
  83116. // return C;
  83117. // }())
  83118. //
  83119. // When we transform the class, we end up with something like this:
  83120. //
  83121. // (function () {
  83122. // var C = (function () { // 3
  83123. // function C() {
  83124. // }
  83125. // return C; // 4
  83126. // }());
  83127. // C.x = 1;
  83128. // return C;
  83129. // }())
  83130. //
  83131. // We want to simplify the two nested IIFEs to end up with something like this:
  83132. //
  83133. // (function () {
  83134. // function C() {
  83135. // }
  83136. // C.x = 1;
  83137. // return C;
  83138. // }())
  83139. // We skip any outer expressions in a number of places to get to the innermost
  83140. // expression, but we will restore them later to preserve comments and source maps.
  83141. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
  83142. // The class statements are the statements generated by visiting the first statement with initializer of the
  83143. // body (1), while all other statements are added to remainingStatements (2)
  83144. var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
  83145. var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
  83146. var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
  83147. var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
  83148. var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
  83149. // We know there is only one variable declaration here as we verified this in an
  83150. // earlier call to isTypeScriptClassWrapper
  83151. var variable = varStatement.declarationList.declarations[0];
  83152. var initializer = ts.skipOuterExpressions(variable.initializer);
  83153. // Under certain conditions, the 'ts' transformer may introduce a class alias, which
  83154. // we see as an assignment, for example:
  83155. //
  83156. // (function () {
  83157. // var C_1;
  83158. // var C = C_1 = (function () {
  83159. // function C() {
  83160. // }
  83161. // C.x = function () { return C_1; }
  83162. // return C;
  83163. // }());
  83164. // C = C_1 = __decorate([dec], C);
  83165. // return C;
  83166. // }())
  83167. //
  83168. var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
  83169. // The underlying call (3) is another IIFE that may contain a '_super' argument.
  83170. var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
  83171. var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
  83172. var funcStatements = func.body.statements;
  83173. var classBodyStart = 0;
  83174. var classBodyEnd = -1;
  83175. var statements = [];
  83176. if (aliasAssignment) {
  83177. // If we have a class alias assignment, we need to move it to the down-level constructor
  83178. // function we generated for the class.
  83179. var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
  83180. if (extendsCall) {
  83181. statements.push(extendsCall);
  83182. classBodyStart++;
  83183. }
  83184. // The next statement is the function declaration.
  83185. statements.push(funcStatements[classBodyStart]);
  83186. classBodyStart++;
  83187. // Add the class alias following the declaration.
  83188. statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
  83189. }
  83190. // Find the trailing 'return' statement (4)
  83191. while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
  83192. classBodyEnd--;
  83193. }
  83194. // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
  83195. // as we already have one that has been introduced by the 'ts' transformer.
  83196. ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
  83197. if (classBodyEnd < -1) {
  83198. // If there were any hoisted declarations following the return statement, we should
  83199. // append them.
  83200. ts.addRange(statements, funcStatements, classBodyEnd + 1);
  83201. }
  83202. // Add the remaining statements of the outer wrapper.
  83203. ts.addRange(statements, remainingStatements);
  83204. // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
  83205. // after the remaining statements from the 'ts' transformer.
  83206. ts.addRange(statements, classStatements, /*start*/ 1);
  83207. // Recreate any outer parentheses or partially-emitted expressions to preserve source map
  83208. // and comment locations.
  83209. return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func,
  83210. /*modifiers*/ undefined,
  83211. /*asteriskToken*/ undefined,
  83212. /*name*/ undefined,
  83213. /*typeParameters*/ undefined, func.parameters,
  83214. /*type*/ undefined, ts.updateBlock(func.body, statements))),
  83215. /*typeArguments*/ undefined, call.arguments))));
  83216. }
  83217. function visitImmediateSuperCallInBody(node) {
  83218. return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
  83219. }
  83220. function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
  83221. // We are here either because SuperKeyword was used somewhere in the expression, or
  83222. // because we contain a SpreadElementExpression.
  83223. if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
  83224. node.expression.kind === 102 /* SuperKeyword */ ||
  83225. ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
  83226. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
  83227. if (node.expression.kind === 102 /* SuperKeyword */) {
  83228. ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
  83229. }
  83230. var resultingCall = void 0;
  83231. if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
  83232. // [source]
  83233. // f(...a, b)
  83234. // x.m(...a, b)
  83235. // super(...a, b)
  83236. // super.m(...a, b) // in static
  83237. // super.m(...a, b) // in instance
  83238. //
  83239. // [output]
  83240. // f.apply(void 0, a.concat([b]))
  83241. // (_a = x).m.apply(_a, a.concat([b]))
  83242. // _super.apply(this, a.concat([b]))
  83243. // _super.m.apply(this, a.concat([b]))
  83244. // _super.prototype.m.apply(this, a.concat([b]))
  83245. resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 102 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
  83246. }
  83247. else {
  83248. // [source]
  83249. // super(a)
  83250. // super.m(a) // in static
  83251. // super.m(a) // in instance
  83252. //
  83253. // [output]
  83254. // _super.call(this, a)
  83255. // _super.m.call(this, a)
  83256. // _super.prototype.m.call(this, a)
  83257. resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 102 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
  83258. /*location*/ node);
  83259. }
  83260. if (node.expression.kind === 102 /* SuperKeyword */) {
  83261. var initializer = ts.createLogicalOr(resultingCall, createActualThis());
  83262. resultingCall = assignToCapturedThis
  83263. ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
  83264. : initializer;
  83265. }
  83266. return ts.setOriginalNode(resultingCall, node);
  83267. }
  83268. return ts.visitEachChild(node, visitor, context);
  83269. }
  83270. /**
  83271. * Visits a NewExpression that contains a spread element.
  83272. *
  83273. * @param node A NewExpression node.
  83274. */
  83275. function visitNewExpression(node) {
  83276. if (ts.some(node.arguments, ts.isSpreadElement)) {
  83277. // We are here because we contain a SpreadElementExpression.
  83278. // [source]
  83279. // new C(...a)
  83280. //
  83281. // [output]
  83282. // new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
  83283. var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
  83284. return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray(__spreadArrays([ts.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)),
  83285. /*typeArguments*/ undefined, []);
  83286. }
  83287. return ts.visitEachChild(node, visitor, context);
  83288. }
  83289. /**
  83290. * Transforms an array of Expression nodes that contains a SpreadExpression.
  83291. *
  83292. * @param elements The array of Expression nodes.
  83293. * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
  83294. * @param multiLine A value indicating whether the result should be emitted on multiple lines.
  83295. */
  83296. function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
  83297. // [source]
  83298. // [a, ...b, c]
  83299. //
  83300. // [output (downlevelIteration)]
  83301. // __spread([a], b, [c])
  83302. //
  83303. // [output]
  83304. // __spreadArrays([a], b, [c])
  83305. // Map spans of spread expressions into their expressions and spans of other
  83306. // expressions into an array literal.
  83307. var numElements = elements.length;
  83308. var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
  83309. return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
  83310. }));
  83311. if (compilerOptions.downlevelIteration) {
  83312. if (segments.length === 1) {
  83313. var firstSegment = segments[0];
  83314. if (isCallToHelper(firstSegment, "___spread")) {
  83315. return segments[0];
  83316. }
  83317. }
  83318. return ts.createSpreadHelper(context, segments);
  83319. }
  83320. else {
  83321. if (segments.length === 1) {
  83322. var firstSegment = segments[0];
  83323. if (!needsUniqueCopy
  83324. || isPackedArrayLiteral(firstSegment)
  83325. || isCallToHelper(firstSegment, "___spreadArrays")) {
  83326. return segments[0];
  83327. }
  83328. }
  83329. return ts.createSpreadArraysHelper(context, segments);
  83330. }
  83331. }
  83332. function isPackedElement(node) {
  83333. return !ts.isOmittedExpression(node);
  83334. }
  83335. function isPackedArrayLiteral(node) {
  83336. return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
  83337. }
  83338. function isCallToHelper(firstSegment, helperName) {
  83339. return ts.isCallExpression(firstSegment)
  83340. && ts.isIdentifier(firstSegment.expression)
  83341. && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
  83342. && firstSegment.expression.escapedText === helperName;
  83343. }
  83344. function partitionSpread(node) {
  83345. return ts.isSpreadElement(node)
  83346. ? visitSpanOfSpreads
  83347. : visitSpanOfNonSpreads;
  83348. }
  83349. function visitSpanOfSpreads(chunk) {
  83350. return ts.map(chunk, visitExpressionOfSpread);
  83351. }
  83352. function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
  83353. return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
  83354. }
  83355. function visitSpreadElement(node) {
  83356. return ts.visitNode(node.expression, visitor, ts.isExpression);
  83357. }
  83358. /**
  83359. * Transforms the expression of a SpreadExpression node.
  83360. *
  83361. * @param node A SpreadExpression node.
  83362. */
  83363. function visitExpressionOfSpread(node) {
  83364. return ts.visitNode(node.expression, visitor, ts.isExpression);
  83365. }
  83366. /**
  83367. * Visits a template literal.
  83368. *
  83369. * @param node A template literal.
  83370. */
  83371. function visitTemplateLiteral(node) {
  83372. return ts.setTextRange(ts.createLiteral(node.text), node);
  83373. }
  83374. /**
  83375. * Visits a string literal with an extended unicode escape.
  83376. *
  83377. * @param node A string literal.
  83378. */
  83379. function visitStringLiteral(node) {
  83380. if (node.hasExtendedUnicodeEscape) {
  83381. return ts.setTextRange(ts.createLiteral(node.text), node);
  83382. }
  83383. return node;
  83384. }
  83385. /**
  83386. * Visits a binary or octal (ES6) numeric literal.
  83387. *
  83388. * @param node A string literal.
  83389. */
  83390. function visitNumericLiteral(node) {
  83391. if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
  83392. return ts.setTextRange(ts.createNumericLiteral(node.text), node);
  83393. }
  83394. return node;
  83395. }
  83396. /**
  83397. * Visits a TaggedTemplateExpression node.
  83398. *
  83399. * @param node A TaggedTemplateExpression node.
  83400. */
  83401. function visitTaggedTemplateExpression(node) {
  83402. // Visit the tag expression
  83403. var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
  83404. // Build up the template arguments and the raw and cooked strings for the template.
  83405. // We start out with 'undefined' for the first argument and revisit later
  83406. // to avoid walking over the template string twice and shifting all our arguments over after the fact.
  83407. var templateArguments = [undefined];
  83408. var cookedStrings = [];
  83409. var rawStrings = [];
  83410. var template = node.template;
  83411. if (ts.isNoSubstitutionTemplateLiteral(template)) {
  83412. cookedStrings.push(ts.createLiteral(template.text));
  83413. rawStrings.push(getRawLiteral(template));
  83414. }
  83415. else {
  83416. cookedStrings.push(ts.createLiteral(template.head.text));
  83417. rawStrings.push(getRawLiteral(template.head));
  83418. for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
  83419. var templateSpan = _a[_i];
  83420. cookedStrings.push(ts.createLiteral(templateSpan.literal.text));
  83421. rawStrings.push(getRawLiteral(templateSpan.literal));
  83422. templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
  83423. }
  83424. }
  83425. var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
  83426. // Create a variable to cache the template object if we're in a module.
  83427. // Do not do this in the global scope, as any variable we currently generate could conflict with
  83428. // variables from outside of the current compilation. In the future, we can revisit this behavior.
  83429. if (ts.isExternalModule(currentSourceFile)) {
  83430. var tempVar = ts.createUniqueName("templateObject");
  83431. recordTaggedTemplateString(tempVar);
  83432. templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
  83433. }
  83434. else {
  83435. templateArguments[0] = helperCall;
  83436. }
  83437. return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
  83438. }
  83439. /**
  83440. * Creates an ES5 compatible literal from an ES6 template literal.
  83441. *
  83442. * @param node The ES6 template literal.
  83443. */
  83444. function getRawLiteral(node) {
  83445. // Find original source text, since we need to emit the raw strings of the tagged template.
  83446. // The raw strings contain the (escaped) strings of what the user wrote.
  83447. // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
  83448. var text = node.rawText;
  83449. if (text === undefined) {
  83450. text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
  83451. // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
  83452. // thus we need to remove those characters.
  83453. // First template piece starts with "`", others with "}"
  83454. // Last template piece ends with "`", others with "${"
  83455. var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
  83456. text = text.substring(1, text.length - (isLast ? 1 : 2));
  83457. }
  83458. // Newline normalization:
  83459. // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
  83460. // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
  83461. text = text.replace(/\r\n?/g, "\n");
  83462. return ts.setTextRange(ts.createLiteral(text), node);
  83463. }
  83464. /**
  83465. * Visits a TemplateExpression node.
  83466. *
  83467. * @param node A TemplateExpression node.
  83468. */
  83469. function visitTemplateExpression(node) {
  83470. var expressions = [];
  83471. addTemplateHead(expressions, node);
  83472. addTemplateSpans(expressions, node);
  83473. // createAdd will check if each expression binds less closely than binary '+'.
  83474. // If it does, it wraps the expression in parentheses. Otherwise, something like
  83475. // `abc${ 1 << 2 }`
  83476. // becomes
  83477. // "abc" + 1 << 2 + ""
  83478. // which is really
  83479. // ("abc" + 1) << (2 + "")
  83480. // rather than
  83481. // "abc" + (1 << 2) + ""
  83482. var expression = ts.reduceLeft(expressions, ts.createAdd);
  83483. if (ts.nodeIsSynthesized(expression)) {
  83484. expression.pos = node.pos;
  83485. expression.end = node.end;
  83486. }
  83487. return expression;
  83488. }
  83489. /**
  83490. * Gets a value indicating whether we need to include the head of a TemplateExpression.
  83491. *
  83492. * @param node A TemplateExpression node.
  83493. */
  83494. function shouldAddTemplateHead(node) {
  83495. // If this expression has an empty head literal and the first template span has a non-empty
  83496. // literal, then emitting the empty head literal is not necessary.
  83497. // `${ foo } and ${ bar }`
  83498. // can be emitted as
  83499. // foo + " and " + bar
  83500. // This is because it is only required that one of the first two operands in the emit
  83501. // output must be a string literal, so that the other operand and all following operands
  83502. // are forced into strings.
  83503. //
  83504. // If the first template span has an empty literal, then the head must still be emitted.
  83505. // `${ foo }${ bar }`
  83506. // must still be emitted as
  83507. // "" + foo + bar
  83508. // There is always atleast one templateSpan in this code path, since
  83509. // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
  83510. ts.Debug.assert(node.templateSpans.length !== 0);
  83511. return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
  83512. }
  83513. /**
  83514. * Adds the head of a TemplateExpression to an array of expressions.
  83515. *
  83516. * @param expressions An array of expressions.
  83517. * @param node A TemplateExpression node.
  83518. */
  83519. function addTemplateHead(expressions, node) {
  83520. if (!shouldAddTemplateHead(node)) {
  83521. return;
  83522. }
  83523. expressions.push(ts.createLiteral(node.head.text));
  83524. }
  83525. /**
  83526. * Visits and adds the template spans of a TemplateExpression to an array of expressions.
  83527. *
  83528. * @param expressions An array of expressions.
  83529. * @param node A TemplateExpression node.
  83530. */
  83531. function addTemplateSpans(expressions, node) {
  83532. for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
  83533. var span = _a[_i];
  83534. expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
  83535. // Only emit if the literal is non-empty.
  83536. // The binary '+' operator is left-associative, so the first string concatenation
  83537. // with the head will force the result up to this point to be a string.
  83538. // Emitting a '+ ""' has no semantic effect for middles and tails.
  83539. if (span.literal.text.length !== 0) {
  83540. expressions.push(ts.createLiteral(span.literal.text));
  83541. }
  83542. }
  83543. }
  83544. /**
  83545. * Visits the `super` keyword
  83546. */
  83547. function visitSuperKeyword(isExpressionOfCall) {
  83548. return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
  83549. ts.createFileLevelUniqueName("_super");
  83550. }
  83551. function visitMetaProperty(node) {
  83552. if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
  83553. hierarchyFacts |= 16384 /* NewTarget */;
  83554. return ts.createFileLevelUniqueName("_newTarget");
  83555. }
  83556. return node;
  83557. }
  83558. /**
  83559. * Called by the printer just before a node is printed.
  83560. *
  83561. * @param hint A hint as to the intended usage of the node.
  83562. * @param node The node to be printed.
  83563. * @param emitCallback The callback used to emit the node.
  83564. */
  83565. function onEmitNode(hint, node, emitCallback) {
  83566. if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
  83567. // If we are tracking a captured `this`, keep track of the enclosing function.
  83568. var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
  83569. ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
  83570. : 65 /* FunctionIncludes */);
  83571. previousOnEmitNode(hint, node, emitCallback);
  83572. exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
  83573. return;
  83574. }
  83575. previousOnEmitNode(hint, node, emitCallback);
  83576. }
  83577. /**
  83578. * Enables a more costly code path for substitutions when we determine a source file
  83579. * contains block-scoped bindings (e.g. `let` or `const`).
  83580. */
  83581. function enableSubstitutionsForBlockScopedBindings() {
  83582. if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
  83583. enabledSubstitutions |= 2 /* BlockScopedBindings */;
  83584. context.enableSubstitution(75 /* Identifier */);
  83585. }
  83586. }
  83587. /**
  83588. * Enables a more costly code path for substitutions when we determine a source file
  83589. * contains a captured `this`.
  83590. */
  83591. function enableSubstitutionsForCapturedThis() {
  83592. if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
  83593. enabledSubstitutions |= 1 /* CapturedThis */;
  83594. context.enableSubstitution(104 /* ThisKeyword */);
  83595. context.enableEmitNotification(162 /* Constructor */);
  83596. context.enableEmitNotification(161 /* MethodDeclaration */);
  83597. context.enableEmitNotification(163 /* GetAccessor */);
  83598. context.enableEmitNotification(164 /* SetAccessor */);
  83599. context.enableEmitNotification(202 /* ArrowFunction */);
  83600. context.enableEmitNotification(201 /* FunctionExpression */);
  83601. context.enableEmitNotification(244 /* FunctionDeclaration */);
  83602. }
  83603. }
  83604. /**
  83605. * Hooks node substitutions.
  83606. *
  83607. * @param hint The context for the emitter.
  83608. * @param node The node to substitute.
  83609. */
  83610. function onSubstituteNode(hint, node) {
  83611. node = previousOnSubstituteNode(hint, node);
  83612. if (hint === 1 /* Expression */) {
  83613. return substituteExpression(node);
  83614. }
  83615. if (ts.isIdentifier(node)) {
  83616. return substituteIdentifier(node);
  83617. }
  83618. return node;
  83619. }
  83620. /**
  83621. * Hooks substitutions for non-expression identifiers.
  83622. */
  83623. function substituteIdentifier(node) {
  83624. // Only substitute the identifier if we have enabled substitutions for block-scoped
  83625. // bindings.
  83626. if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
  83627. var original = ts.getParseTreeNode(node, ts.isIdentifier);
  83628. if (original && isNameOfDeclarationWithCollidingName(original)) {
  83629. return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
  83630. }
  83631. }
  83632. return node;
  83633. }
  83634. /**
  83635. * Determines whether a name is the name of a declaration with a colliding name.
  83636. * NOTE: This function expects to be called with an original source tree node.
  83637. *
  83638. * @param node An original source tree node.
  83639. */
  83640. function isNameOfDeclarationWithCollidingName(node) {
  83641. switch (node.parent.kind) {
  83642. case 191 /* BindingElement */:
  83643. case 245 /* ClassDeclaration */:
  83644. case 248 /* EnumDeclaration */:
  83645. case 242 /* VariableDeclaration */:
  83646. return node.parent.name === node
  83647. && resolver.isDeclarationWithCollidingName(node.parent);
  83648. }
  83649. return false;
  83650. }
  83651. /**
  83652. * Substitutes an expression.
  83653. *
  83654. * @param node An Expression node.
  83655. */
  83656. function substituteExpression(node) {
  83657. switch (node.kind) {
  83658. case 75 /* Identifier */:
  83659. return substituteExpressionIdentifier(node);
  83660. case 104 /* ThisKeyword */:
  83661. return substituteThisKeyword(node);
  83662. }
  83663. return node;
  83664. }
  83665. /**
  83666. * Substitutes an expression identifier.
  83667. *
  83668. * @param node An Identifier node.
  83669. */
  83670. function substituteExpressionIdentifier(node) {
  83671. if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
  83672. var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
  83673. if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
  83674. return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
  83675. }
  83676. }
  83677. return node;
  83678. }
  83679. function isPartOfClassBody(declaration, node) {
  83680. var currentNode = ts.getParseTreeNode(node);
  83681. if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
  83682. // if the node has no correlation to a parse tree node, its definitely not
  83683. // part of the body.
  83684. // if the node is outside of the document range of the declaration, its
  83685. // definitely not part of the body.
  83686. return false;
  83687. }
  83688. var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
  83689. while (currentNode) {
  83690. if (currentNode === blockScope || currentNode === declaration) {
  83691. // if we are in the enclosing block scope of the declaration, we are definitely
  83692. // not inside the class body.
  83693. return false;
  83694. }
  83695. if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
  83696. return true;
  83697. }
  83698. currentNode = currentNode.parent;
  83699. }
  83700. return false;
  83701. }
  83702. /**
  83703. * Substitutes `this` when contained within an arrow function.
  83704. *
  83705. * @param node The ThisKeyword node.
  83706. */
  83707. function substituteThisKeyword(node) {
  83708. if (enabledSubstitutions & 1 /* CapturedThis */
  83709. && hierarchyFacts & 16 /* CapturesThis */) {
  83710. return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
  83711. }
  83712. return node;
  83713. }
  83714. function getClassMemberPrefix(node, member) {
  83715. return ts.hasModifier(member, 32 /* Static */)
  83716. ? ts.getInternalName(node)
  83717. : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
  83718. }
  83719. function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
  83720. if (!constructor || !hasExtendsClause) {
  83721. return false;
  83722. }
  83723. if (ts.some(constructor.parameters)) {
  83724. return false;
  83725. }
  83726. var statement = ts.firstOrUndefined(constructor.body.statements);
  83727. if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
  83728. return false;
  83729. }
  83730. var statementExpression = statement.expression;
  83731. if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
  83732. return false;
  83733. }
  83734. var callTarget = statementExpression.expression;
  83735. if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
  83736. return false;
  83737. }
  83738. var callArgument = ts.singleOrUndefined(statementExpression.arguments);
  83739. if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
  83740. return false;
  83741. }
  83742. var expression = callArgument.expression;
  83743. return ts.isIdentifier(expression) && expression.escapedText === "arguments";
  83744. }
  83745. }
  83746. ts.transformES2015 = transformES2015;
  83747. function createExtendsHelper(context, name) {
  83748. context.requestEmitHelper(ts.extendsHelper);
  83749. return ts.createCall(ts.getUnscopedHelperName("__extends"),
  83750. /*typeArguments*/ undefined, [
  83751. name,
  83752. ts.createFileLevelUniqueName("_super")
  83753. ]);
  83754. }
  83755. function createTemplateObjectHelper(context, cooked, raw) {
  83756. context.requestEmitHelper(ts.templateObjectHelper);
  83757. return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"),
  83758. /*typeArguments*/ undefined, [
  83759. cooked,
  83760. raw
  83761. ]);
  83762. }
  83763. ts.extendsHelper = {
  83764. name: "typescript:extends",
  83765. importName: "__extends",
  83766. scoped: false,
  83767. priority: 0,
  83768. text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
  83769. };
  83770. ts.templateObjectHelper = {
  83771. name: "typescript:makeTemplateObject",
  83772. importName: "__makeTemplateObject",
  83773. scoped: false,
  83774. priority: 0,
  83775. text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };"
  83776. };
  83777. })(ts || (ts = {}));
  83778. /*@internal*/
  83779. var ts;
  83780. (function (ts) {
  83781. /**
  83782. * Transforms ES5 syntax into ES3 syntax.
  83783. *
  83784. * @param context Context and state information for the transformation.
  83785. */
  83786. function transformES5(context) {
  83787. var compilerOptions = context.getCompilerOptions();
  83788. // enable emit notification only if using --jsx preserve or react-native
  83789. var previousOnEmitNode;
  83790. var noSubstitution;
  83791. if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
  83792. previousOnEmitNode = context.onEmitNode;
  83793. context.onEmitNode = onEmitNode;
  83794. context.enableEmitNotification(268 /* JsxOpeningElement */);
  83795. context.enableEmitNotification(269 /* JsxClosingElement */);
  83796. context.enableEmitNotification(267 /* JsxSelfClosingElement */);
  83797. noSubstitution = [];
  83798. }
  83799. var previousOnSubstituteNode = context.onSubstituteNode;
  83800. context.onSubstituteNode = onSubstituteNode;
  83801. context.enableSubstitution(194 /* PropertyAccessExpression */);
  83802. context.enableSubstitution(281 /* PropertyAssignment */);
  83803. return ts.chainBundle(transformSourceFile);
  83804. /**
  83805. * Transforms an ES5 source file to ES3.
  83806. *
  83807. * @param node A SourceFile
  83808. */
  83809. function transformSourceFile(node) {
  83810. return node;
  83811. }
  83812. /**
  83813. * Called by the printer just before a node is printed.
  83814. *
  83815. * @param hint A hint as to the intended usage of the node.
  83816. * @param node The node to emit.
  83817. * @param emitCallback A callback used to emit the node.
  83818. */
  83819. function onEmitNode(hint, node, emitCallback) {
  83820. switch (node.kind) {
  83821. case 268 /* JsxOpeningElement */:
  83822. case 269 /* JsxClosingElement */:
  83823. case 267 /* JsxSelfClosingElement */:
  83824. var tagName = node.tagName;
  83825. noSubstitution[ts.getOriginalNodeId(tagName)] = true;
  83826. break;
  83827. }
  83828. previousOnEmitNode(hint, node, emitCallback);
  83829. }
  83830. /**
  83831. * Hooks node substitutions.
  83832. *
  83833. * @param hint A hint as to the intended usage of the node.
  83834. * @param node The node to substitute.
  83835. */
  83836. function onSubstituteNode(hint, node) {
  83837. if (node.id && noSubstitution && noSubstitution[node.id]) {
  83838. return previousOnSubstituteNode(hint, node);
  83839. }
  83840. node = previousOnSubstituteNode(hint, node);
  83841. if (ts.isPropertyAccessExpression(node)) {
  83842. return substitutePropertyAccessExpression(node);
  83843. }
  83844. else if (ts.isPropertyAssignment(node)) {
  83845. return substitutePropertyAssignment(node);
  83846. }
  83847. return node;
  83848. }
  83849. /**
  83850. * Substitutes a PropertyAccessExpression whose name is a reserved word.
  83851. *
  83852. * @param node A PropertyAccessExpression
  83853. */
  83854. function substitutePropertyAccessExpression(node) {
  83855. if (ts.isPrivateIdentifier(node.name)) {
  83856. return node;
  83857. }
  83858. var literalName = trySubstituteReservedName(node.name);
  83859. if (literalName) {
  83860. return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
  83861. }
  83862. return node;
  83863. }
  83864. /**
  83865. * Substitutes a PropertyAssignment whose name is a reserved word.
  83866. *
  83867. * @param node A PropertyAssignment
  83868. */
  83869. function substitutePropertyAssignment(node) {
  83870. var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
  83871. if (literalName) {
  83872. return ts.updatePropertyAssignment(node, literalName, node.initializer);
  83873. }
  83874. return node;
  83875. }
  83876. /**
  83877. * If an identifier name is a reserved word, returns a string literal for the name.
  83878. *
  83879. * @param name An Identifier
  83880. */
  83881. function trySubstituteReservedName(name) {
  83882. var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
  83883. if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
  83884. return ts.setTextRange(ts.createLiteral(name), name);
  83885. }
  83886. return undefined;
  83887. }
  83888. }
  83889. ts.transformES5 = transformES5;
  83890. })(ts || (ts = {}));
  83891. // Transforms generator functions into a compatible ES5 representation with similar runtime
  83892. // semantics. This is accomplished by first transforming the body of each generator
  83893. // function into an intermediate representation that is the compiled into a JavaScript
  83894. // switch statement.
  83895. //
  83896. // Many functions in this transformer will contain comments indicating the expected
  83897. // intermediate representation. For illustrative purposes, the following intermediate
  83898. // language is used to define this intermediate representation:
  83899. //
  83900. // .nop - Performs no operation.
  83901. // .local NAME, ... - Define local variable declarations.
  83902. // .mark LABEL - Mark the location of a label.
  83903. // .br LABEL - Jump to a label. If jumping out of a protected
  83904. // region, all .finally blocks are executed.
  83905. // .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy.
  83906. // If jumping out of a protected region, all .finally
  83907. // blocks are executed.
  83908. // .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey.
  83909. // If jumping out of a protected region, all .finally
  83910. // blocks are executed.
  83911. // .yield (x) - Yield the value of the optional expression `x`.
  83912. // Resume at the next label.
  83913. // .yieldstar (x) - Delegate yield to the value of the optional
  83914. // expression `x`. Resume at the next label.
  83915. // NOTE: `x` must be an Iterator, not an Iterable.
  83916. // .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or
  83917. // "break" abrupt completions jump to the CONTINUE or
  83918. // BREAK labels, respectively.
  83919. // .endloop - Marks the end of a loop.
  83920. // .with (x) - Marks the beginning of a WithStatement block, using
  83921. // the supplied expression.
  83922. // .endwith - Marks the end of a WithStatement.
  83923. // .switch - Marks the beginning of a SwitchStatement.
  83924. // .endswitch - Marks the end of a SwitchStatement.
  83925. // .labeled NAME - Marks the beginning of a LabeledStatement with the
  83926. // supplied name.
  83927. // .endlabeled - Marks the end of a LabeledStatement.
  83928. // .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the
  83929. // labels for each block.
  83930. // .catch (x) - Marks the beginning of a catch block.
  83931. // .finally - Marks the beginning of a finally block.
  83932. // .endfinally - Marks the end of a finally block.
  83933. // .endtry - Marks the end of a protected region.
  83934. // .throw (x) - Throws the value of the expression `x`.
  83935. // .return (x) - Returns the value of the expression `x`.
  83936. //
  83937. // In addition, the illustrative intermediate representation introduces some special
  83938. // variables:
  83939. //
  83940. // %sent% - Either returns the next value sent to the generator,
  83941. // returns the result of a delegated yield, or throws
  83942. // the exception sent to the generator.
  83943. // %error% - Returns the value of the current exception in a
  83944. // catch block.
  83945. //
  83946. // This intermediate representation is then compiled into JavaScript syntax. The resulting
  83947. // compilation output looks something like the following:
  83948. //
  83949. // function f() {
  83950. // var /*locals*/;
  83951. // /*functions*/
  83952. // return __generator(function (state) {
  83953. // switch (state.label) {
  83954. // /*cases per label*/
  83955. // }
  83956. // });
  83957. // }
  83958. //
  83959. // Each of the above instructions corresponds to JavaScript emit similar to the following:
  83960. //
  83961. // .local NAME | var NAME;
  83962. // -------------------------------|----------------------------------------------
  83963. // .mark LABEL | case LABEL:
  83964. // -------------------------------|----------------------------------------------
  83965. // .br LABEL | return [3 /*break*/, LABEL];
  83966. // -------------------------------|----------------------------------------------
  83967. // .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL];
  83968. // -------------------------------|----------------------------------------------
  83969. // .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL];
  83970. // -------------------------------|----------------------------------------------
  83971. // .yield (x) | return [4 /*yield*/, x];
  83972. // .mark RESUME | case RESUME:
  83973. // a = %sent%; | a = state.sent();
  83974. // -------------------------------|----------------------------------------------
  83975. // .yieldstar (x) | return [5 /*yield**/, x];
  83976. // .mark RESUME | case RESUME:
  83977. // a = %sent%; | a = state.sent();
  83978. // -------------------------------|----------------------------------------------
  83979. // .with (_a) | with (_a) {
  83980. // a(); | a();
  83981. // | }
  83982. // | state.label = LABEL;
  83983. // .mark LABEL | case LABEL:
  83984. // | with (_a) {
  83985. // b(); | b();
  83986. // | }
  83987. // .endwith |
  83988. // -------------------------------|----------------------------------------------
  83989. // | case 0:
  83990. // | state.trys = [];
  83991. // | ...
  83992. // .try TRY, CATCH, FINALLY, END |
  83993. // .mark TRY | case TRY:
  83994. // | state.trys.push([TRY, CATCH, FINALLY, END]);
  83995. // .nop |
  83996. // a(); | a();
  83997. // .br END | return [3 /*break*/, END];
  83998. // .catch (e) |
  83999. // .mark CATCH | case CATCH:
  84000. // | e = state.sent();
  84001. // b(); | b();
  84002. // .br END | return [3 /*break*/, END];
  84003. // .finally |
  84004. // .mark FINALLY | case FINALLY:
  84005. // c(); | c();
  84006. // .endfinally | return [7 /*endfinally*/];
  84007. // .endtry |
  84008. // .mark END | case END:
  84009. /*@internal*/
  84010. var ts;
  84011. (function (ts) {
  84012. var OpCode;
  84013. (function (OpCode) {
  84014. OpCode[OpCode["Nop"] = 0] = "Nop";
  84015. OpCode[OpCode["Statement"] = 1] = "Statement";
  84016. OpCode[OpCode["Assign"] = 2] = "Assign";
  84017. OpCode[OpCode["Break"] = 3] = "Break";
  84018. OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
  84019. OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
  84020. OpCode[OpCode["Yield"] = 6] = "Yield";
  84021. OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
  84022. OpCode[OpCode["Return"] = 8] = "Return";
  84023. OpCode[OpCode["Throw"] = 9] = "Throw";
  84024. OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
  84025. })(OpCode || (OpCode = {}));
  84026. // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
  84027. var BlockAction;
  84028. (function (BlockAction) {
  84029. BlockAction[BlockAction["Open"] = 0] = "Open";
  84030. BlockAction[BlockAction["Close"] = 1] = "Close";
  84031. })(BlockAction || (BlockAction = {}));
  84032. // the kind for a generated code block in a FunctionBuilder
  84033. var CodeBlockKind;
  84034. (function (CodeBlockKind) {
  84035. CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
  84036. CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
  84037. CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
  84038. CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
  84039. CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
  84040. })(CodeBlockKind || (CodeBlockKind = {}));
  84041. // the state for a generated code exception block
  84042. var ExceptionBlockState;
  84043. (function (ExceptionBlockState) {
  84044. ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
  84045. ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
  84046. ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
  84047. ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
  84048. })(ExceptionBlockState || (ExceptionBlockState = {}));
  84049. // NOTE: changes to this enum should be reflected in the __generator helper.
  84050. var Instruction;
  84051. (function (Instruction) {
  84052. Instruction[Instruction["Next"] = 0] = "Next";
  84053. Instruction[Instruction["Throw"] = 1] = "Throw";
  84054. Instruction[Instruction["Return"] = 2] = "Return";
  84055. Instruction[Instruction["Break"] = 3] = "Break";
  84056. Instruction[Instruction["Yield"] = 4] = "Yield";
  84057. Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
  84058. Instruction[Instruction["Catch"] = 6] = "Catch";
  84059. Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
  84060. })(Instruction || (Instruction = {}));
  84061. function getInstructionName(instruction) {
  84062. switch (instruction) {
  84063. case 2 /* Return */: return "return";
  84064. case 3 /* Break */: return "break";
  84065. case 4 /* Yield */: return "yield";
  84066. case 5 /* YieldStar */: return "yield*";
  84067. case 7 /* Endfinally */: return "endfinally";
  84068. default: return undefined; // TODO: GH#18217
  84069. }
  84070. }
  84071. function transformGenerators(context) {
  84072. var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
  84073. var compilerOptions = context.getCompilerOptions();
  84074. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  84075. var resolver = context.getEmitResolver();
  84076. var previousOnSubstituteNode = context.onSubstituteNode;
  84077. context.onSubstituteNode = onSubstituteNode;
  84078. var renamedCatchVariables;
  84079. var renamedCatchVariableDeclarations;
  84080. var inGeneratorFunctionBody;
  84081. var inStatementContainingYield;
  84082. // The following three arrays store information about generated code blocks.
  84083. // All three arrays are correlated by their index. This approach is used over allocating
  84084. // objects to store the same information to avoid GC overhead.
  84085. //
  84086. var blocks; // Information about the code block
  84087. var blockOffsets; // The operation offset at which a code block begins or ends
  84088. var blockActions; // Whether the code block is opened or closed
  84089. var blockStack; // A stack of currently open code blocks
  84090. // Labels are used to mark locations in the code that can be the target of a Break (jump)
  84091. // operation. These are translated into case clauses in a switch statement.
  84092. // The following two arrays are correlated by their index. This approach is used over
  84093. // allocating objects to store the same information to avoid GC overhead.
  84094. //
  84095. var labelOffsets; // The operation offset at which the label is defined.
  84096. var labelExpressions; // The NumericLiteral nodes bound to each label.
  84097. var nextLabelId = 1; // The next label id to use.
  84098. // Operations store information about generated code for the function body. This
  84099. // Includes things like statements, assignments, breaks (jumps), and yields.
  84100. // The following three arrays are correlated by their index. This approach is used over
  84101. // allocating objects to store the same information to avoid GC overhead.
  84102. //
  84103. var operations; // The operation to perform.
  84104. var operationArguments; // The arguments to the operation.
  84105. var operationLocations; // The source map location for the operation.
  84106. var state; // The name of the state object used by the generator at runtime.
  84107. // The following variables store information used by the `build` function:
  84108. //
  84109. var blockIndex = 0; // The index of the current block.
  84110. var labelNumber = 0; // The current label number.
  84111. var labelNumbers;
  84112. var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
  84113. var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
  84114. var clauses; // The case clauses generated for labels.
  84115. var statements; // The statements for the current label.
  84116. var exceptionBlockStack; // A stack of containing exception blocks.
  84117. var currentExceptionBlock; // The current exception block.
  84118. var withBlockStack; // A stack containing `with` blocks.
  84119. return ts.chainBundle(transformSourceFile);
  84120. function transformSourceFile(node) {
  84121. if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
  84122. return node;
  84123. }
  84124. var visited = ts.visitEachChild(node, visitor, context);
  84125. ts.addEmitHelpers(visited, context.readEmitHelpers());
  84126. return visited;
  84127. }
  84128. /**
  84129. * Visits a node.
  84130. *
  84131. * @param node The node to visit.
  84132. */
  84133. function visitor(node) {
  84134. var transformFlags = node.transformFlags;
  84135. if (inStatementContainingYield) {
  84136. return visitJavaScriptInStatementContainingYield(node);
  84137. }
  84138. else if (inGeneratorFunctionBody) {
  84139. return visitJavaScriptInGeneratorFunctionBody(node);
  84140. }
  84141. else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
  84142. return visitGenerator(node);
  84143. }
  84144. else if (transformFlags & 512 /* ContainsGenerator */) {
  84145. return ts.visitEachChild(node, visitor, context);
  84146. }
  84147. else {
  84148. return node;
  84149. }
  84150. }
  84151. /**
  84152. * Visits a node that is contained within a statement that contains yield.
  84153. *
  84154. * @param node The node to visit.
  84155. */
  84156. function visitJavaScriptInStatementContainingYield(node) {
  84157. switch (node.kind) {
  84158. case 228 /* DoStatement */:
  84159. return visitDoStatement(node);
  84160. case 229 /* WhileStatement */:
  84161. return visitWhileStatement(node);
  84162. case 237 /* SwitchStatement */:
  84163. return visitSwitchStatement(node);
  84164. case 238 /* LabeledStatement */:
  84165. return visitLabeledStatement(node);
  84166. default:
  84167. return visitJavaScriptInGeneratorFunctionBody(node);
  84168. }
  84169. }
  84170. /**
  84171. * Visits a node that is contained within a generator function.
  84172. *
  84173. * @param node The node to visit.
  84174. */
  84175. function visitJavaScriptInGeneratorFunctionBody(node) {
  84176. switch (node.kind) {
  84177. case 244 /* FunctionDeclaration */:
  84178. return visitFunctionDeclaration(node);
  84179. case 201 /* FunctionExpression */:
  84180. return visitFunctionExpression(node);
  84181. case 163 /* GetAccessor */:
  84182. case 164 /* SetAccessor */:
  84183. return visitAccessorDeclaration(node);
  84184. case 225 /* VariableStatement */:
  84185. return visitVariableStatement(node);
  84186. case 230 /* ForStatement */:
  84187. return visitForStatement(node);
  84188. case 231 /* ForInStatement */:
  84189. return visitForInStatement(node);
  84190. case 234 /* BreakStatement */:
  84191. return visitBreakStatement(node);
  84192. case 233 /* ContinueStatement */:
  84193. return visitContinueStatement(node);
  84194. case 235 /* ReturnStatement */:
  84195. return visitReturnStatement(node);
  84196. default:
  84197. if (node.transformFlags & 262144 /* ContainsYield */) {
  84198. return visitJavaScriptContainingYield(node);
  84199. }
  84200. else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
  84201. return ts.visitEachChild(node, visitor, context);
  84202. }
  84203. else {
  84204. return node;
  84205. }
  84206. }
  84207. }
  84208. /**
  84209. * Visits a node that contains a YieldExpression.
  84210. *
  84211. * @param node The node to visit.
  84212. */
  84213. function visitJavaScriptContainingYield(node) {
  84214. switch (node.kind) {
  84215. case 209 /* BinaryExpression */:
  84216. return visitBinaryExpression(node);
  84217. case 210 /* ConditionalExpression */:
  84218. return visitConditionalExpression(node);
  84219. case 212 /* YieldExpression */:
  84220. return visitYieldExpression(node);
  84221. case 192 /* ArrayLiteralExpression */:
  84222. return visitArrayLiteralExpression(node);
  84223. case 193 /* ObjectLiteralExpression */:
  84224. return visitObjectLiteralExpression(node);
  84225. case 195 /* ElementAccessExpression */:
  84226. return visitElementAccessExpression(node);
  84227. case 196 /* CallExpression */:
  84228. return visitCallExpression(node);
  84229. case 197 /* NewExpression */:
  84230. return visitNewExpression(node);
  84231. default:
  84232. return ts.visitEachChild(node, visitor, context);
  84233. }
  84234. }
  84235. /**
  84236. * Visits a generator function.
  84237. *
  84238. * @param node The node to visit.
  84239. */
  84240. function visitGenerator(node) {
  84241. switch (node.kind) {
  84242. case 244 /* FunctionDeclaration */:
  84243. return visitFunctionDeclaration(node);
  84244. case 201 /* FunctionExpression */:
  84245. return visitFunctionExpression(node);
  84246. default:
  84247. return ts.Debug.failBadSyntaxKind(node);
  84248. }
  84249. }
  84250. /**
  84251. * Visits a function declaration.
  84252. *
  84253. * This will be called when one of the following conditions are met:
  84254. * - The function declaration is a generator function.
  84255. * - The function declaration is contained within the body of a generator function.
  84256. *
  84257. * @param node The node to visit.
  84258. */
  84259. function visitFunctionDeclaration(node) {
  84260. // Currently, we only support generators that were originally async functions.
  84261. if (node.asteriskToken) {
  84262. node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
  84263. /*decorators*/ undefined, node.modifiers,
  84264. /*asteriskToken*/ undefined, node.name,
  84265. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  84266. /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
  84267. /*location*/ node), node);
  84268. }
  84269. else {
  84270. var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
  84271. var savedInStatementContainingYield = inStatementContainingYield;
  84272. inGeneratorFunctionBody = false;
  84273. inStatementContainingYield = false;
  84274. node = ts.visitEachChild(node, visitor, context);
  84275. inGeneratorFunctionBody = savedInGeneratorFunctionBody;
  84276. inStatementContainingYield = savedInStatementContainingYield;
  84277. }
  84278. if (inGeneratorFunctionBody) {
  84279. // Function declarations in a generator function body are hoisted
  84280. // to the top of the lexical scope and elided from the current statement.
  84281. hoistFunctionDeclaration(node);
  84282. return undefined;
  84283. }
  84284. else {
  84285. return node;
  84286. }
  84287. }
  84288. /**
  84289. * Visits a function expression.
  84290. *
  84291. * This will be called when one of the following conditions are met:
  84292. * - The function expression is a generator function.
  84293. * - The function expression is contained within the body of a generator function.
  84294. *
  84295. * @param node The node to visit.
  84296. */
  84297. function visitFunctionExpression(node) {
  84298. // Currently, we only support generators that were originally async functions.
  84299. if (node.asteriskToken) {
  84300. node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
  84301. /*modifiers*/ undefined,
  84302. /*asteriskToken*/ undefined, node.name,
  84303. /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
  84304. /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
  84305. /*location*/ node), node);
  84306. }
  84307. else {
  84308. var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
  84309. var savedInStatementContainingYield = inStatementContainingYield;
  84310. inGeneratorFunctionBody = false;
  84311. inStatementContainingYield = false;
  84312. node = ts.visitEachChild(node, visitor, context);
  84313. inGeneratorFunctionBody = savedInGeneratorFunctionBody;
  84314. inStatementContainingYield = savedInStatementContainingYield;
  84315. }
  84316. return node;
  84317. }
  84318. /**
  84319. * Visits a get or set accessor declaration.
  84320. *
  84321. * This will be called when one of the following conditions are met:
  84322. * - The accessor is contained within the body of a generator function.
  84323. *
  84324. * @param node The node to visit.
  84325. */
  84326. function visitAccessorDeclaration(node) {
  84327. var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
  84328. var savedInStatementContainingYield = inStatementContainingYield;
  84329. inGeneratorFunctionBody = false;
  84330. inStatementContainingYield = false;
  84331. node = ts.visitEachChild(node, visitor, context);
  84332. inGeneratorFunctionBody = savedInGeneratorFunctionBody;
  84333. inStatementContainingYield = savedInStatementContainingYield;
  84334. return node;
  84335. }
  84336. /**
  84337. * Transforms the body of a generator function declaration.
  84338. *
  84339. * @param node The function body to transform.
  84340. */
  84341. function transformGeneratorFunctionBody(body) {
  84342. // Save existing generator state
  84343. var statements = [];
  84344. var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
  84345. var savedInStatementContainingYield = inStatementContainingYield;
  84346. var savedBlocks = blocks;
  84347. var savedBlockOffsets = blockOffsets;
  84348. var savedBlockActions = blockActions;
  84349. var savedBlockStack = blockStack;
  84350. var savedLabelOffsets = labelOffsets;
  84351. var savedLabelExpressions = labelExpressions;
  84352. var savedNextLabelId = nextLabelId;
  84353. var savedOperations = operations;
  84354. var savedOperationArguments = operationArguments;
  84355. var savedOperationLocations = operationLocations;
  84356. var savedState = state;
  84357. // Initialize generator state
  84358. inGeneratorFunctionBody = true;
  84359. inStatementContainingYield = false;
  84360. blocks = undefined;
  84361. blockOffsets = undefined;
  84362. blockActions = undefined;
  84363. blockStack = undefined;
  84364. labelOffsets = undefined;
  84365. labelExpressions = undefined;
  84366. nextLabelId = 1;
  84367. operations = undefined;
  84368. operationArguments = undefined;
  84369. operationLocations = undefined;
  84370. state = ts.createTempVariable(/*recordTempVariable*/ undefined);
  84371. // Build the generator
  84372. resumeLexicalEnvironment();
  84373. var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
  84374. transformAndEmitStatements(body.statements, statementOffset);
  84375. var buildResult = build();
  84376. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  84377. statements.push(ts.createReturn(buildResult));
  84378. // Restore previous generator state
  84379. inGeneratorFunctionBody = savedInGeneratorFunctionBody;
  84380. inStatementContainingYield = savedInStatementContainingYield;
  84381. blocks = savedBlocks;
  84382. blockOffsets = savedBlockOffsets;
  84383. blockActions = savedBlockActions;
  84384. blockStack = savedBlockStack;
  84385. labelOffsets = savedLabelOffsets;
  84386. labelExpressions = savedLabelExpressions;
  84387. nextLabelId = savedNextLabelId;
  84388. operations = savedOperations;
  84389. operationArguments = savedOperationArguments;
  84390. operationLocations = savedOperationLocations;
  84391. state = savedState;
  84392. return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
  84393. }
  84394. /**
  84395. * Visits a variable statement.
  84396. *
  84397. * This will be called when one of the following conditions are met:
  84398. * - The variable statement is contained within the body of a generator function.
  84399. *
  84400. * @param node The node to visit.
  84401. */
  84402. function visitVariableStatement(node) {
  84403. if (node.transformFlags & 262144 /* ContainsYield */) {
  84404. transformAndEmitVariableDeclarationList(node.declarationList);
  84405. return undefined;
  84406. }
  84407. else {
  84408. // Do not hoist custom prologues.
  84409. if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
  84410. return node;
  84411. }
  84412. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  84413. var variable = _a[_i];
  84414. hoistVariableDeclaration(variable.name);
  84415. }
  84416. var variables = ts.getInitializedVariables(node.declarationList);
  84417. if (variables.length === 0) {
  84418. return undefined;
  84419. }
  84420. return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
  84421. }
  84422. }
  84423. /**
  84424. * Visits a binary expression.
  84425. *
  84426. * This will be called when one of the following conditions are met:
  84427. * - The node contains a YieldExpression.
  84428. *
  84429. * @param node The node to visit.
  84430. */
  84431. function visitBinaryExpression(node) {
  84432. var assoc = ts.getExpressionAssociativity(node);
  84433. switch (assoc) {
  84434. case 0 /* Left */:
  84435. return visitLeftAssociativeBinaryExpression(node);
  84436. case 1 /* Right */:
  84437. return visitRightAssociativeBinaryExpression(node);
  84438. default:
  84439. return ts.Debug.assertNever(assoc);
  84440. }
  84441. }
  84442. /**
  84443. * Visits a right-associative binary expression containing `yield`.
  84444. *
  84445. * @param node The node to visit.
  84446. */
  84447. function visitRightAssociativeBinaryExpression(node) {
  84448. var left = node.left, right = node.right;
  84449. if (containsYield(right)) {
  84450. var target = void 0;
  84451. switch (left.kind) {
  84452. case 194 /* PropertyAccessExpression */:
  84453. // [source]
  84454. // a.b = yield;
  84455. //
  84456. // [intermediate]
  84457. // .local _a
  84458. // _a = a;
  84459. // .yield resumeLabel
  84460. // .mark resumeLabel
  84461. // _a.b = %sent%;
  84462. target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
  84463. break;
  84464. case 195 /* ElementAccessExpression */:
  84465. // [source]
  84466. // a[b] = yield;
  84467. //
  84468. // [intermediate]
  84469. // .local _a, _b
  84470. // _a = a;
  84471. // _b = b;
  84472. // .yield resumeLabel
  84473. // .mark resumeLabel
  84474. // _a[_b] = %sent%;
  84475. target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
  84476. break;
  84477. default:
  84478. target = ts.visitNode(left, visitor, ts.isExpression);
  84479. break;
  84480. }
  84481. var operator = node.operatorToken.kind;
  84482. if (ts.isCompoundAssignment(operator)) {
  84483. return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
  84484. }
  84485. else {
  84486. return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
  84487. }
  84488. }
  84489. return ts.visitEachChild(node, visitor, context);
  84490. }
  84491. function visitLeftAssociativeBinaryExpression(node) {
  84492. if (containsYield(node.right)) {
  84493. if (ts.isLogicalOperator(node.operatorToken.kind)) {
  84494. return visitLogicalBinaryExpression(node);
  84495. }
  84496. else if (node.operatorToken.kind === 27 /* CommaToken */) {
  84497. return visitCommaExpression(node);
  84498. }
  84499. // [source]
  84500. // a() + (yield) + c()
  84501. //
  84502. // [intermediate]
  84503. // .local _a
  84504. // _a = a();
  84505. // .yield resumeLabel
  84506. // _a + %sent% + c()
  84507. var clone_6 = ts.getMutableClone(node);
  84508. clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
  84509. clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
  84510. return clone_6;
  84511. }
  84512. return ts.visitEachChild(node, visitor, context);
  84513. }
  84514. /**
  84515. * Visits a logical binary expression containing `yield`.
  84516. *
  84517. * @param node A node to visit.
  84518. */
  84519. function visitLogicalBinaryExpression(node) {
  84520. // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
  84521. // to be transformed as such:
  84522. //
  84523. // [source]
  84524. // x = a() && yield;
  84525. //
  84526. // [intermediate]
  84527. // .local _a
  84528. // _a = a();
  84529. // .brfalse resultLabel, (_a)
  84530. // .yield resumeLabel
  84531. // .mark resumeLabel
  84532. // _a = %sent%;
  84533. // .mark resultLabel
  84534. // x = _a;
  84535. //
  84536. // [source]
  84537. // x = a() || yield;
  84538. //
  84539. // [intermediate]
  84540. // .local _a
  84541. // _a = a();
  84542. // .brtrue resultLabel, (_a)
  84543. // .yield resumeLabel
  84544. // .mark resumeLabel
  84545. // _a = %sent%;
  84546. // .mark resultLabel
  84547. // x = _a;
  84548. var resultLabel = defineLabel();
  84549. var resultLocal = declareLocal();
  84550. emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
  84551. if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
  84552. // Logical `&&` shortcuts when the left-hand operand is falsey.
  84553. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
  84554. }
  84555. else {
  84556. // Logical `||` shortcuts when the left-hand operand is truthy.
  84557. emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
  84558. }
  84559. emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
  84560. markLabel(resultLabel);
  84561. return resultLocal;
  84562. }
  84563. /**
  84564. * Visits a comma expression containing `yield`.
  84565. *
  84566. * @param node The node to visit.
  84567. */
  84568. function visitCommaExpression(node) {
  84569. // [source]
  84570. // x = a(), yield, b();
  84571. //
  84572. // [intermediate]
  84573. // a();
  84574. // .yield resumeLabel
  84575. // .mark resumeLabel
  84576. // x = %sent%, b();
  84577. var pendingExpressions = [];
  84578. visit(node.left);
  84579. visit(node.right);
  84580. return ts.inlineExpressions(pendingExpressions);
  84581. function visit(node) {
  84582. if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
  84583. visit(node.left);
  84584. visit(node.right);
  84585. }
  84586. else {
  84587. if (containsYield(node) && pendingExpressions.length > 0) {
  84588. emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
  84589. pendingExpressions = [];
  84590. }
  84591. pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
  84592. }
  84593. }
  84594. }
  84595. /**
  84596. * Visits a conditional expression containing `yield`.
  84597. *
  84598. * @param node The node to visit.
  84599. */
  84600. function visitConditionalExpression(node) {
  84601. // [source]
  84602. // x = a() ? yield : b();
  84603. //
  84604. // [intermediate]
  84605. // .local _a
  84606. // .brfalse whenFalseLabel, (a())
  84607. // .yield resumeLabel
  84608. // .mark resumeLabel
  84609. // _a = %sent%;
  84610. // .br resultLabel
  84611. // .mark whenFalseLabel
  84612. // _a = b();
  84613. // .mark resultLabel
  84614. // x = _a;
  84615. // We only need to perform a specific transformation if a `yield` expression exists
  84616. // in either the `whenTrue` or `whenFalse` branches.
  84617. // A `yield` in the condition will be handled by the normal visitor.
  84618. if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
  84619. var whenFalseLabel = defineLabel();
  84620. var resultLabel = defineLabel();
  84621. var resultLocal = declareLocal();
  84622. emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
  84623. emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
  84624. emitBreak(resultLabel);
  84625. markLabel(whenFalseLabel);
  84626. emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
  84627. markLabel(resultLabel);
  84628. return resultLocal;
  84629. }
  84630. return ts.visitEachChild(node, visitor, context);
  84631. }
  84632. /**
  84633. * Visits a `yield` expression.
  84634. *
  84635. * @param node The node to visit.
  84636. */
  84637. function visitYieldExpression(node) {
  84638. // [source]
  84639. // x = yield a();
  84640. //
  84641. // [intermediate]
  84642. // .yield resumeLabel, (a())
  84643. // .mark resumeLabel
  84644. // x = %sent%;
  84645. var resumeLabel = defineLabel();
  84646. var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
  84647. if (node.asteriskToken) {
  84648. var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
  84649. ? ts.createValuesHelper(context, expression, /*location*/ node)
  84650. : expression;
  84651. emitYieldStar(iterator, /*location*/ node);
  84652. }
  84653. else {
  84654. emitYield(expression, /*location*/ node);
  84655. }
  84656. markLabel(resumeLabel);
  84657. return createGeneratorResume(/*location*/ node);
  84658. }
  84659. /**
  84660. * Visits an ArrayLiteralExpression that contains a YieldExpression.
  84661. *
  84662. * @param node The node to visit.
  84663. */
  84664. function visitArrayLiteralExpression(node) {
  84665. return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
  84666. }
  84667. /**
  84668. * Visits an array of expressions containing one or more YieldExpression nodes
  84669. * and returns an expression for the resulting value.
  84670. *
  84671. * @param elements The elements to visit.
  84672. * @param multiLine Whether array literals created should be emitted on multiple lines.
  84673. */
  84674. function visitElements(elements, leadingElement, location, multiLine) {
  84675. // [source]
  84676. // ar = [1, yield, 2];
  84677. //
  84678. // [intermediate]
  84679. // .local _a
  84680. // _a = [1];
  84681. // .yield resumeLabel
  84682. // .mark resumeLabel
  84683. // ar = _a.concat([%sent%, 2]);
  84684. var numInitialElements = countInitialNodesWithoutYield(elements);
  84685. var temp;
  84686. if (numInitialElements > 0) {
  84687. temp = declareLocal();
  84688. var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
  84689. emitAssignment(temp, ts.createArrayLiteral(leadingElement
  84690. ? __spreadArrays([leadingElement], initialElements) : initialElements));
  84691. leadingElement = undefined;
  84692. }
  84693. var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
  84694. return temp
  84695. ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
  84696. : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
  84697. function reduceElement(expressions, element) {
  84698. if (containsYield(element) && expressions.length > 0) {
  84699. var hasAssignedTemp = temp !== undefined;
  84700. if (!temp) {
  84701. temp = declareLocal();
  84702. }
  84703. emitAssignment(temp, hasAssignedTemp
  84704. ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
  84705. : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
  84706. leadingElement = undefined;
  84707. expressions = [];
  84708. }
  84709. expressions.push(ts.visitNode(element, visitor, ts.isExpression));
  84710. return expressions;
  84711. }
  84712. }
  84713. function visitObjectLiteralExpression(node) {
  84714. // [source]
  84715. // o = {
  84716. // a: 1,
  84717. // b: yield,
  84718. // c: 2
  84719. // };
  84720. //
  84721. // [intermediate]
  84722. // .local _a
  84723. // _a = {
  84724. // a: 1
  84725. // };
  84726. // .yield resumeLabel
  84727. // .mark resumeLabel
  84728. // o = (_a.b = %sent%,
  84729. // _a.c = 2,
  84730. // _a);
  84731. var properties = node.properties;
  84732. var multiLine = node.multiLine;
  84733. var numInitialProperties = countInitialNodesWithoutYield(properties);
  84734. var temp = declareLocal();
  84735. emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
  84736. var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
  84737. expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
  84738. return ts.inlineExpressions(expressions);
  84739. function reduceProperty(expressions, property) {
  84740. if (containsYield(property) && expressions.length > 0) {
  84741. emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
  84742. expressions = [];
  84743. }
  84744. var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
  84745. var visited = ts.visitNode(expression, visitor, ts.isExpression);
  84746. if (visited) {
  84747. if (multiLine) {
  84748. ts.startOnNewLine(visited);
  84749. }
  84750. expressions.push(visited);
  84751. }
  84752. return expressions;
  84753. }
  84754. }
  84755. /**
  84756. * Visits an ElementAccessExpression that contains a YieldExpression.
  84757. *
  84758. * @param node The node to visit.
  84759. */
  84760. function visitElementAccessExpression(node) {
  84761. if (containsYield(node.argumentExpression)) {
  84762. // [source]
  84763. // a = x[yield];
  84764. //
  84765. // [intermediate]
  84766. // .local _a
  84767. // _a = x;
  84768. // .yield resumeLabel
  84769. // .mark resumeLabel
  84770. // a = _a[%sent%]
  84771. var clone_7 = ts.getMutableClone(node);
  84772. clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
  84773. clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
  84774. return clone_7;
  84775. }
  84776. return ts.visitEachChild(node, visitor, context);
  84777. }
  84778. function visitCallExpression(node) {
  84779. if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
  84780. // [source]
  84781. // a.b(1, yield, 2);
  84782. //
  84783. // [intermediate]
  84784. // .local _a, _b, _c
  84785. // _b = (_a = a).b;
  84786. // _c = [1];
  84787. // .yield resumeLabel
  84788. // .mark resumeLabel
  84789. // _b.apply(_a, _c.concat([%sent%, 2]));
  84790. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
  84791. return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments),
  84792. /*location*/ node), node);
  84793. }
  84794. return ts.visitEachChild(node, visitor, context);
  84795. }
  84796. function visitNewExpression(node) {
  84797. if (ts.forEach(node.arguments, containsYield)) {
  84798. // [source]
  84799. // new a.b(1, yield, 2);
  84800. //
  84801. // [intermediate]
  84802. // .local _a, _b, _c
  84803. // _b = (_a = a.b).bind;
  84804. // _c = [1];
  84805. // .yield resumeLabel
  84806. // .mark resumeLabel
  84807. // new (_b.apply(_a, _c.concat([%sent%, 2])));
  84808. var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
  84809. return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments,
  84810. /*leadingElement*/ ts.createVoidZero())),
  84811. /*typeArguments*/ undefined, []), node), node);
  84812. }
  84813. return ts.visitEachChild(node, visitor, context);
  84814. }
  84815. function transformAndEmitStatements(statements, start) {
  84816. if (start === void 0) { start = 0; }
  84817. var numStatements = statements.length;
  84818. for (var i = start; i < numStatements; i++) {
  84819. transformAndEmitStatement(statements[i]);
  84820. }
  84821. }
  84822. function transformAndEmitEmbeddedStatement(node) {
  84823. if (ts.isBlock(node)) {
  84824. transformAndEmitStatements(node.statements);
  84825. }
  84826. else {
  84827. transformAndEmitStatement(node);
  84828. }
  84829. }
  84830. function transformAndEmitStatement(node) {
  84831. var savedInStatementContainingYield = inStatementContainingYield;
  84832. if (!inStatementContainingYield) {
  84833. inStatementContainingYield = containsYield(node);
  84834. }
  84835. transformAndEmitStatementWorker(node);
  84836. inStatementContainingYield = savedInStatementContainingYield;
  84837. }
  84838. function transformAndEmitStatementWorker(node) {
  84839. switch (node.kind) {
  84840. case 223 /* Block */:
  84841. return transformAndEmitBlock(node);
  84842. case 226 /* ExpressionStatement */:
  84843. return transformAndEmitExpressionStatement(node);
  84844. case 227 /* IfStatement */:
  84845. return transformAndEmitIfStatement(node);
  84846. case 228 /* DoStatement */:
  84847. return transformAndEmitDoStatement(node);
  84848. case 229 /* WhileStatement */:
  84849. return transformAndEmitWhileStatement(node);
  84850. case 230 /* ForStatement */:
  84851. return transformAndEmitForStatement(node);
  84852. case 231 /* ForInStatement */:
  84853. return transformAndEmitForInStatement(node);
  84854. case 233 /* ContinueStatement */:
  84855. return transformAndEmitContinueStatement(node);
  84856. case 234 /* BreakStatement */:
  84857. return transformAndEmitBreakStatement(node);
  84858. case 235 /* ReturnStatement */:
  84859. return transformAndEmitReturnStatement(node);
  84860. case 236 /* WithStatement */:
  84861. return transformAndEmitWithStatement(node);
  84862. case 237 /* SwitchStatement */:
  84863. return transformAndEmitSwitchStatement(node);
  84864. case 238 /* LabeledStatement */:
  84865. return transformAndEmitLabeledStatement(node);
  84866. case 239 /* ThrowStatement */:
  84867. return transformAndEmitThrowStatement(node);
  84868. case 240 /* TryStatement */:
  84869. return transformAndEmitTryStatement(node);
  84870. default:
  84871. return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  84872. }
  84873. }
  84874. function transformAndEmitBlock(node) {
  84875. if (containsYield(node)) {
  84876. transformAndEmitStatements(node.statements);
  84877. }
  84878. else {
  84879. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  84880. }
  84881. }
  84882. function transformAndEmitExpressionStatement(node) {
  84883. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  84884. }
  84885. function transformAndEmitVariableDeclarationList(node) {
  84886. for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
  84887. var variable = _a[_i];
  84888. var name = ts.getSynthesizedClone(variable.name);
  84889. ts.setCommentRange(name, variable.name);
  84890. hoistVariableDeclaration(name);
  84891. }
  84892. var variables = ts.getInitializedVariables(node);
  84893. var numVariables = variables.length;
  84894. var variablesWritten = 0;
  84895. var pendingExpressions = [];
  84896. while (variablesWritten < numVariables) {
  84897. for (var i = variablesWritten; i < numVariables; i++) {
  84898. var variable = variables[i];
  84899. if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
  84900. break;
  84901. }
  84902. pendingExpressions.push(transformInitializedVariable(variable));
  84903. }
  84904. if (pendingExpressions.length) {
  84905. emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
  84906. variablesWritten += pendingExpressions.length;
  84907. pendingExpressions = [];
  84908. }
  84909. }
  84910. return undefined;
  84911. }
  84912. function transformInitializedVariable(node) {
  84913. return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
  84914. }
  84915. function transformAndEmitIfStatement(node) {
  84916. if (containsYield(node)) {
  84917. // [source]
  84918. // if (x)
  84919. // /*thenStatement*/
  84920. // else
  84921. // /*elseStatement*/
  84922. //
  84923. // [intermediate]
  84924. // .brfalse elseLabel, (x)
  84925. // /*thenStatement*/
  84926. // .br endLabel
  84927. // .mark elseLabel
  84928. // /*elseStatement*/
  84929. // .mark endLabel
  84930. if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
  84931. var endLabel = defineLabel();
  84932. var elseLabel = node.elseStatement ? defineLabel() : undefined;
  84933. emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
  84934. transformAndEmitEmbeddedStatement(node.thenStatement);
  84935. if (node.elseStatement) {
  84936. emitBreak(endLabel);
  84937. markLabel(elseLabel);
  84938. transformAndEmitEmbeddedStatement(node.elseStatement);
  84939. }
  84940. markLabel(endLabel);
  84941. }
  84942. else {
  84943. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  84944. }
  84945. }
  84946. else {
  84947. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  84948. }
  84949. }
  84950. function transformAndEmitDoStatement(node) {
  84951. if (containsYield(node)) {
  84952. // [source]
  84953. // do {
  84954. // /*body*/
  84955. // }
  84956. // while (i < 10);
  84957. //
  84958. // [intermediate]
  84959. // .loop conditionLabel, endLabel
  84960. // .mark loopLabel
  84961. // /*body*/
  84962. // .mark conditionLabel
  84963. // .brtrue loopLabel, (i < 10)
  84964. // .endloop
  84965. // .mark endLabel
  84966. var conditionLabel = defineLabel();
  84967. var loopLabel = defineLabel();
  84968. beginLoopBlock(/*continueLabel*/ conditionLabel);
  84969. markLabel(loopLabel);
  84970. transformAndEmitEmbeddedStatement(node.statement);
  84971. markLabel(conditionLabel);
  84972. emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
  84973. endLoopBlock();
  84974. }
  84975. else {
  84976. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  84977. }
  84978. }
  84979. function visitDoStatement(node) {
  84980. if (inStatementContainingYield) {
  84981. beginScriptLoopBlock();
  84982. node = ts.visitEachChild(node, visitor, context);
  84983. endLoopBlock();
  84984. return node;
  84985. }
  84986. else {
  84987. return ts.visitEachChild(node, visitor, context);
  84988. }
  84989. }
  84990. function transformAndEmitWhileStatement(node) {
  84991. if (containsYield(node)) {
  84992. // [source]
  84993. // while (i < 10) {
  84994. // /*body*/
  84995. // }
  84996. //
  84997. // [intermediate]
  84998. // .loop loopLabel, endLabel
  84999. // .mark loopLabel
  85000. // .brfalse endLabel, (i < 10)
  85001. // /*body*/
  85002. // .br loopLabel
  85003. // .endloop
  85004. // .mark endLabel
  85005. var loopLabel = defineLabel();
  85006. var endLabel = beginLoopBlock(loopLabel);
  85007. markLabel(loopLabel);
  85008. emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
  85009. transformAndEmitEmbeddedStatement(node.statement);
  85010. emitBreak(loopLabel);
  85011. endLoopBlock();
  85012. }
  85013. else {
  85014. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  85015. }
  85016. }
  85017. function visitWhileStatement(node) {
  85018. if (inStatementContainingYield) {
  85019. beginScriptLoopBlock();
  85020. node = ts.visitEachChild(node, visitor, context);
  85021. endLoopBlock();
  85022. return node;
  85023. }
  85024. else {
  85025. return ts.visitEachChild(node, visitor, context);
  85026. }
  85027. }
  85028. function transformAndEmitForStatement(node) {
  85029. if (containsYield(node)) {
  85030. // [source]
  85031. // for (var i = 0; i < 10; i++) {
  85032. // /*body*/
  85033. // }
  85034. //
  85035. // [intermediate]
  85036. // .local i
  85037. // i = 0;
  85038. // .loop incrementLabel, endLoopLabel
  85039. // .mark conditionLabel
  85040. // .brfalse endLoopLabel, (i < 10)
  85041. // /*body*/
  85042. // .mark incrementLabel
  85043. // i++;
  85044. // .br conditionLabel
  85045. // .endloop
  85046. // .mark endLoopLabel
  85047. var conditionLabel = defineLabel();
  85048. var incrementLabel = defineLabel();
  85049. var endLabel = beginLoopBlock(incrementLabel);
  85050. if (node.initializer) {
  85051. var initializer = node.initializer;
  85052. if (ts.isVariableDeclarationList(initializer)) {
  85053. transformAndEmitVariableDeclarationList(initializer);
  85054. }
  85055. else {
  85056. emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
  85057. }
  85058. }
  85059. markLabel(conditionLabel);
  85060. if (node.condition) {
  85061. emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
  85062. }
  85063. transformAndEmitEmbeddedStatement(node.statement);
  85064. markLabel(incrementLabel);
  85065. if (node.incrementor) {
  85066. emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
  85067. }
  85068. emitBreak(conditionLabel);
  85069. endLoopBlock();
  85070. }
  85071. else {
  85072. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  85073. }
  85074. }
  85075. function visitForStatement(node) {
  85076. if (inStatementContainingYield) {
  85077. beginScriptLoopBlock();
  85078. }
  85079. var initializer = node.initializer;
  85080. if (initializer && ts.isVariableDeclarationList(initializer)) {
  85081. for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
  85082. var variable = _a[_i];
  85083. hoistVariableDeclaration(variable.name);
  85084. }
  85085. var variables = ts.getInitializedVariables(initializer);
  85086. node = ts.updateFor(node, variables.length > 0
  85087. ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
  85088. : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  85089. }
  85090. else {
  85091. node = ts.visitEachChild(node, visitor, context);
  85092. }
  85093. if (inStatementContainingYield) {
  85094. endLoopBlock();
  85095. }
  85096. return node;
  85097. }
  85098. function transformAndEmitForInStatement(node) {
  85099. // TODO(rbuckton): Source map locations
  85100. if (containsYield(node)) {
  85101. // [source]
  85102. // for (var p in o) {
  85103. // /*body*/
  85104. // }
  85105. //
  85106. // [intermediate]
  85107. // .local _a, _b, _i
  85108. // _a = [];
  85109. // for (_b in o) _a.push(_b);
  85110. // _i = 0;
  85111. // .loop incrementLabel, endLoopLabel
  85112. // .mark conditionLabel
  85113. // .brfalse endLoopLabel, (_i < _a.length)
  85114. // p = _a[_i];
  85115. // /*body*/
  85116. // .mark incrementLabel
  85117. // _b++;
  85118. // .br conditionLabel
  85119. // .endloop
  85120. // .mark endLoopLabel
  85121. var keysArray = declareLocal(); // _a
  85122. var key = declareLocal(); // _b
  85123. var keysIndex = ts.createLoopVariable(); // _i
  85124. var initializer = node.initializer;
  85125. hoistVariableDeclaration(keysIndex);
  85126. emitAssignment(keysArray, ts.createArrayLiteral());
  85127. emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"),
  85128. /*typeArguments*/ undefined, [key]))));
  85129. emitAssignment(keysIndex, ts.createLiteral(0));
  85130. var conditionLabel = defineLabel();
  85131. var incrementLabel = defineLabel();
  85132. var endLabel = beginLoopBlock(incrementLabel);
  85133. markLabel(conditionLabel);
  85134. emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
  85135. var variable = void 0;
  85136. if (ts.isVariableDeclarationList(initializer)) {
  85137. for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
  85138. var variable_1 = _a[_i];
  85139. hoistVariableDeclaration(variable_1.name);
  85140. }
  85141. variable = ts.getSynthesizedClone(initializer.declarations[0].name);
  85142. }
  85143. else {
  85144. variable = ts.visitNode(initializer, visitor, ts.isExpression);
  85145. ts.Debug.assert(ts.isLeftHandSideExpression(variable));
  85146. }
  85147. emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
  85148. transformAndEmitEmbeddedStatement(node.statement);
  85149. markLabel(incrementLabel);
  85150. emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
  85151. emitBreak(conditionLabel);
  85152. endLoopBlock();
  85153. }
  85154. else {
  85155. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  85156. }
  85157. }
  85158. function visitForInStatement(node) {
  85159. // [source]
  85160. // for (var x in a) {
  85161. // /*body*/
  85162. // }
  85163. //
  85164. // [intermediate]
  85165. // .local x
  85166. // .loop
  85167. // for (x in a) {
  85168. // /*body*/
  85169. // }
  85170. // .endloop
  85171. if (inStatementContainingYield) {
  85172. beginScriptLoopBlock();
  85173. }
  85174. var initializer = node.initializer;
  85175. if (ts.isVariableDeclarationList(initializer)) {
  85176. for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
  85177. var variable = _a[_i];
  85178. hoistVariableDeclaration(variable.name);
  85179. }
  85180. node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
  85181. }
  85182. else {
  85183. node = ts.visitEachChild(node, visitor, context);
  85184. }
  85185. if (inStatementContainingYield) {
  85186. endLoopBlock();
  85187. }
  85188. return node;
  85189. }
  85190. function transformAndEmitContinueStatement(node) {
  85191. var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
  85192. if (label > 0) {
  85193. emitBreak(label, /*location*/ node);
  85194. }
  85195. else {
  85196. // invalid continue without a containing loop. Leave the node as is, per #17875.
  85197. emitStatement(node);
  85198. }
  85199. }
  85200. function visitContinueStatement(node) {
  85201. if (inStatementContainingYield) {
  85202. var label = findContinueTarget(node.label && ts.idText(node.label));
  85203. if (label > 0) {
  85204. return createInlineBreak(label, /*location*/ node);
  85205. }
  85206. }
  85207. return ts.visitEachChild(node, visitor, context);
  85208. }
  85209. function transformAndEmitBreakStatement(node) {
  85210. var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
  85211. if (label > 0) {
  85212. emitBreak(label, /*location*/ node);
  85213. }
  85214. else {
  85215. // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
  85216. emitStatement(node);
  85217. }
  85218. }
  85219. function visitBreakStatement(node) {
  85220. if (inStatementContainingYield) {
  85221. var label = findBreakTarget(node.label && ts.idText(node.label));
  85222. if (label > 0) {
  85223. return createInlineBreak(label, /*location*/ node);
  85224. }
  85225. }
  85226. return ts.visitEachChild(node, visitor, context);
  85227. }
  85228. function transformAndEmitReturnStatement(node) {
  85229. emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
  85230. /*location*/ node);
  85231. }
  85232. function visitReturnStatement(node) {
  85233. return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
  85234. /*location*/ node);
  85235. }
  85236. function transformAndEmitWithStatement(node) {
  85237. if (containsYield(node)) {
  85238. // [source]
  85239. // with (x) {
  85240. // /*body*/
  85241. // }
  85242. //
  85243. // [intermediate]
  85244. // .with (x)
  85245. // /*body*/
  85246. // .endwith
  85247. beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
  85248. transformAndEmitEmbeddedStatement(node.statement);
  85249. endWithBlock();
  85250. }
  85251. else {
  85252. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  85253. }
  85254. }
  85255. function transformAndEmitSwitchStatement(node) {
  85256. if (containsYield(node.caseBlock)) {
  85257. // [source]
  85258. // switch (x) {
  85259. // case a:
  85260. // /*caseStatements*/
  85261. // case b:
  85262. // /*caseStatements*/
  85263. // default:
  85264. // /*defaultStatements*/
  85265. // }
  85266. //
  85267. // [intermediate]
  85268. // .local _a
  85269. // .switch endLabel
  85270. // _a = x;
  85271. // switch (_a) {
  85272. // case a:
  85273. // .br clauseLabels[0]
  85274. // }
  85275. // switch (_a) {
  85276. // case b:
  85277. // .br clauseLabels[1]
  85278. // }
  85279. // .br clauseLabels[2]
  85280. // .mark clauseLabels[0]
  85281. // /*caseStatements*/
  85282. // .mark clauseLabels[1]
  85283. // /*caseStatements*/
  85284. // .mark clauseLabels[2]
  85285. // /*caseStatements*/
  85286. // .endswitch
  85287. // .mark endLabel
  85288. var caseBlock = node.caseBlock;
  85289. var numClauses = caseBlock.clauses.length;
  85290. var endLabel = beginSwitchBlock();
  85291. var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
  85292. // Create labels for each clause and find the index of the first default clause.
  85293. var clauseLabels = [];
  85294. var defaultClauseIndex = -1;
  85295. for (var i = 0; i < numClauses; i++) {
  85296. var clause = caseBlock.clauses[i];
  85297. clauseLabels.push(defineLabel());
  85298. if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
  85299. defaultClauseIndex = i;
  85300. }
  85301. }
  85302. // Emit switch statements for each run of case clauses either from the first case
  85303. // clause or the next case clause with a `yield` in its expression, up to the next
  85304. // case clause with a `yield` in its expression.
  85305. var clausesWritten = 0;
  85306. var pendingClauses = [];
  85307. while (clausesWritten < numClauses) {
  85308. var defaultClausesSkipped = 0;
  85309. for (var i = clausesWritten; i < numClauses; i++) {
  85310. var clause = caseBlock.clauses[i];
  85311. if (clause.kind === 277 /* CaseClause */) {
  85312. if (containsYield(clause.expression) && pendingClauses.length > 0) {
  85313. break;
  85314. }
  85315. pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
  85316. createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
  85317. ]));
  85318. }
  85319. else {
  85320. defaultClausesSkipped++;
  85321. }
  85322. }
  85323. if (pendingClauses.length) {
  85324. emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
  85325. clausesWritten += pendingClauses.length;
  85326. pendingClauses = [];
  85327. }
  85328. if (defaultClausesSkipped > 0) {
  85329. clausesWritten += defaultClausesSkipped;
  85330. defaultClausesSkipped = 0;
  85331. }
  85332. }
  85333. if (defaultClauseIndex >= 0) {
  85334. emitBreak(clauseLabels[defaultClauseIndex]);
  85335. }
  85336. else {
  85337. emitBreak(endLabel);
  85338. }
  85339. for (var i = 0; i < numClauses; i++) {
  85340. markLabel(clauseLabels[i]);
  85341. transformAndEmitStatements(caseBlock.clauses[i].statements);
  85342. }
  85343. endSwitchBlock();
  85344. }
  85345. else {
  85346. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  85347. }
  85348. }
  85349. function visitSwitchStatement(node) {
  85350. if (inStatementContainingYield) {
  85351. beginScriptSwitchBlock();
  85352. }
  85353. node = ts.visitEachChild(node, visitor, context);
  85354. if (inStatementContainingYield) {
  85355. endSwitchBlock();
  85356. }
  85357. return node;
  85358. }
  85359. function transformAndEmitLabeledStatement(node) {
  85360. if (containsYield(node)) {
  85361. // [source]
  85362. // x: {
  85363. // /*body*/
  85364. // }
  85365. //
  85366. // [intermediate]
  85367. // .labeled "x", endLabel
  85368. // /*body*/
  85369. // .endlabeled
  85370. // .mark endLabel
  85371. beginLabeledBlock(ts.idText(node.label));
  85372. transformAndEmitEmbeddedStatement(node.statement);
  85373. endLabeledBlock();
  85374. }
  85375. else {
  85376. emitStatement(ts.visitNode(node, visitor, ts.isStatement));
  85377. }
  85378. }
  85379. function visitLabeledStatement(node) {
  85380. if (inStatementContainingYield) {
  85381. beginScriptLabeledBlock(ts.idText(node.label));
  85382. }
  85383. node = ts.visitEachChild(node, visitor, context);
  85384. if (inStatementContainingYield) {
  85385. endLabeledBlock();
  85386. }
  85387. return node;
  85388. }
  85389. function transformAndEmitThrowStatement(node) {
  85390. emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression),
  85391. /*location*/ node);
  85392. }
  85393. function transformAndEmitTryStatement(node) {
  85394. if (containsYield(node)) {
  85395. // [source]
  85396. // try {
  85397. // /*tryBlock*/
  85398. // }
  85399. // catch (e) {
  85400. // /*catchBlock*/
  85401. // }
  85402. // finally {
  85403. // /*finallyBlock*/
  85404. // }
  85405. //
  85406. // [intermediate]
  85407. // .local _a
  85408. // .try tryLabel, catchLabel, finallyLabel, endLabel
  85409. // .mark tryLabel
  85410. // .nop
  85411. // /*tryBlock*/
  85412. // .br endLabel
  85413. // .catch
  85414. // .mark catchLabel
  85415. // _a = %error%;
  85416. // /*catchBlock*/
  85417. // .br endLabel
  85418. // .finally
  85419. // .mark finallyLabel
  85420. // /*finallyBlock*/
  85421. // .endfinally
  85422. // .endtry
  85423. // .mark endLabel
  85424. beginExceptionBlock();
  85425. transformAndEmitEmbeddedStatement(node.tryBlock);
  85426. if (node.catchClause) {
  85427. beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
  85428. transformAndEmitEmbeddedStatement(node.catchClause.block);
  85429. }
  85430. if (node.finallyBlock) {
  85431. beginFinallyBlock();
  85432. transformAndEmitEmbeddedStatement(node.finallyBlock);
  85433. }
  85434. endExceptionBlock();
  85435. }
  85436. else {
  85437. emitStatement(ts.visitEachChild(node, visitor, context));
  85438. }
  85439. }
  85440. function containsYield(node) {
  85441. return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
  85442. }
  85443. function countInitialNodesWithoutYield(nodes) {
  85444. var numNodes = nodes.length;
  85445. for (var i = 0; i < numNodes; i++) {
  85446. if (containsYield(nodes[i])) {
  85447. return i;
  85448. }
  85449. }
  85450. return -1;
  85451. }
  85452. function onSubstituteNode(hint, node) {
  85453. node = previousOnSubstituteNode(hint, node);
  85454. if (hint === 1 /* Expression */) {
  85455. return substituteExpression(node);
  85456. }
  85457. return node;
  85458. }
  85459. function substituteExpression(node) {
  85460. if (ts.isIdentifier(node)) {
  85461. return substituteExpressionIdentifier(node);
  85462. }
  85463. return node;
  85464. }
  85465. function substituteExpressionIdentifier(node) {
  85466. if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
  85467. var original = ts.getOriginalNode(node);
  85468. if (ts.isIdentifier(original) && original.parent) {
  85469. var declaration = resolver.getReferencedValueDeclaration(original);
  85470. if (declaration) {
  85471. var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
  85472. if (name) {
  85473. var clone_8 = ts.getMutableClone(name);
  85474. ts.setSourceMapRange(clone_8, node);
  85475. ts.setCommentRange(clone_8, node);
  85476. return clone_8;
  85477. }
  85478. }
  85479. }
  85480. }
  85481. return node;
  85482. }
  85483. function cacheExpression(node) {
  85484. if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
  85485. return node;
  85486. }
  85487. var temp = ts.createTempVariable(hoistVariableDeclaration);
  85488. emitAssignment(temp, node, /*location*/ node);
  85489. return temp;
  85490. }
  85491. function declareLocal(name) {
  85492. var temp = name
  85493. ? ts.createUniqueName(name)
  85494. : ts.createTempVariable(/*recordTempVariable*/ undefined);
  85495. hoistVariableDeclaration(temp);
  85496. return temp;
  85497. }
  85498. /**
  85499. * Defines a label, uses as the target of a Break operation.
  85500. */
  85501. function defineLabel() {
  85502. if (!labelOffsets) {
  85503. labelOffsets = [];
  85504. }
  85505. var label = nextLabelId;
  85506. nextLabelId++;
  85507. labelOffsets[label] = -1;
  85508. return label;
  85509. }
  85510. /**
  85511. * Marks the current operation with the specified label.
  85512. */
  85513. function markLabel(label) {
  85514. ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
  85515. labelOffsets[label] = operations ? operations.length : 0;
  85516. }
  85517. /**
  85518. * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
  85519. *
  85520. * @param block Information about the block.
  85521. */
  85522. function beginBlock(block) {
  85523. if (!blocks) {
  85524. blocks = [];
  85525. blockActions = [];
  85526. blockOffsets = [];
  85527. blockStack = [];
  85528. }
  85529. var index = blockActions.length;
  85530. blockActions[index] = 0 /* Open */;
  85531. blockOffsets[index] = operations ? operations.length : 0;
  85532. blocks[index] = block;
  85533. blockStack.push(block);
  85534. return index;
  85535. }
  85536. /**
  85537. * Ends the current block operation.
  85538. */
  85539. function endBlock() {
  85540. var block = peekBlock();
  85541. if (block === undefined)
  85542. return ts.Debug.fail("beginBlock was never called.");
  85543. var index = blockActions.length;
  85544. blockActions[index] = 1 /* Close */;
  85545. blockOffsets[index] = operations ? operations.length : 0;
  85546. blocks[index] = block;
  85547. blockStack.pop();
  85548. return block;
  85549. }
  85550. /**
  85551. * Gets the current open block.
  85552. */
  85553. function peekBlock() {
  85554. return ts.lastOrUndefined(blockStack);
  85555. }
  85556. /**
  85557. * Gets the kind of the current open block.
  85558. */
  85559. function peekBlockKind() {
  85560. var block = peekBlock();
  85561. return block && block.kind;
  85562. }
  85563. /**
  85564. * Begins a code block for a generated `with` statement.
  85565. *
  85566. * @param expression An identifier representing expression for the `with` block.
  85567. */
  85568. function beginWithBlock(expression) {
  85569. var startLabel = defineLabel();
  85570. var endLabel = defineLabel();
  85571. markLabel(startLabel);
  85572. beginBlock({
  85573. kind: 1 /* With */,
  85574. expression: expression,
  85575. startLabel: startLabel,
  85576. endLabel: endLabel
  85577. });
  85578. }
  85579. /**
  85580. * Ends a code block for a generated `with` statement.
  85581. */
  85582. function endWithBlock() {
  85583. ts.Debug.assert(peekBlockKind() === 1 /* With */);
  85584. var block = endBlock();
  85585. markLabel(block.endLabel);
  85586. }
  85587. /**
  85588. * Begins a code block for a generated `try` statement.
  85589. */
  85590. function beginExceptionBlock() {
  85591. var startLabel = defineLabel();
  85592. var endLabel = defineLabel();
  85593. markLabel(startLabel);
  85594. beginBlock({
  85595. kind: 0 /* Exception */,
  85596. state: 0 /* Try */,
  85597. startLabel: startLabel,
  85598. endLabel: endLabel
  85599. });
  85600. emitNop();
  85601. return endLabel;
  85602. }
  85603. /**
  85604. * Enters the `catch` clause of a generated `try` statement.
  85605. *
  85606. * @param variable The catch variable.
  85607. */
  85608. function beginCatchBlock(variable) {
  85609. ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
  85610. // generated identifiers should already be unique within a file
  85611. var name;
  85612. if (ts.isGeneratedIdentifier(variable.name)) {
  85613. name = variable.name;
  85614. hoistVariableDeclaration(variable.name);
  85615. }
  85616. else {
  85617. var text = ts.idText(variable.name);
  85618. name = declareLocal(text);
  85619. if (!renamedCatchVariables) {
  85620. renamedCatchVariables = ts.createMap();
  85621. renamedCatchVariableDeclarations = [];
  85622. context.enableSubstitution(75 /* Identifier */);
  85623. }
  85624. renamedCatchVariables.set(text, true);
  85625. renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
  85626. }
  85627. var exception = peekBlock();
  85628. ts.Debug.assert(exception.state < 1 /* Catch */);
  85629. var endLabel = exception.endLabel;
  85630. emitBreak(endLabel);
  85631. var catchLabel = defineLabel();
  85632. markLabel(catchLabel);
  85633. exception.state = 1 /* Catch */;
  85634. exception.catchVariable = name;
  85635. exception.catchLabel = catchLabel;
  85636. emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
  85637. emitNop();
  85638. }
  85639. /**
  85640. * Enters the `finally` block of a generated `try` statement.
  85641. */
  85642. function beginFinallyBlock() {
  85643. ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
  85644. var exception = peekBlock();
  85645. ts.Debug.assert(exception.state < 2 /* Finally */);
  85646. var endLabel = exception.endLabel;
  85647. emitBreak(endLabel);
  85648. var finallyLabel = defineLabel();
  85649. markLabel(finallyLabel);
  85650. exception.state = 2 /* Finally */;
  85651. exception.finallyLabel = finallyLabel;
  85652. }
  85653. /**
  85654. * Ends the code block for a generated `try` statement.
  85655. */
  85656. function endExceptionBlock() {
  85657. ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
  85658. var exception = endBlock();
  85659. var state = exception.state;
  85660. if (state < 2 /* Finally */) {
  85661. emitBreak(exception.endLabel);
  85662. }
  85663. else {
  85664. emitEndfinally();
  85665. }
  85666. markLabel(exception.endLabel);
  85667. emitNop();
  85668. exception.state = 3 /* Done */;
  85669. }
  85670. /**
  85671. * Begins a code block that supports `break` or `continue` statements that are defined in
  85672. * the source tree and not from generated code.
  85673. *
  85674. * @param labelText Names from containing labeled statements.
  85675. */
  85676. function beginScriptLoopBlock() {
  85677. beginBlock({
  85678. kind: 3 /* Loop */,
  85679. isScript: true,
  85680. breakLabel: -1,
  85681. continueLabel: -1
  85682. });
  85683. }
  85684. /**
  85685. * Begins a code block that supports `break` or `continue` statements that are defined in
  85686. * generated code. Returns a label used to mark the operation to which to jump when a
  85687. * `break` statement targets this block.
  85688. *
  85689. * @param continueLabel A Label used to mark the operation to which to jump when a
  85690. * `continue` statement targets this block.
  85691. */
  85692. function beginLoopBlock(continueLabel) {
  85693. var breakLabel = defineLabel();
  85694. beginBlock({
  85695. kind: 3 /* Loop */,
  85696. isScript: false,
  85697. breakLabel: breakLabel,
  85698. continueLabel: continueLabel,
  85699. });
  85700. return breakLabel;
  85701. }
  85702. /**
  85703. * Ends a code block that supports `break` or `continue` statements that are defined in
  85704. * generated code or in the source tree.
  85705. */
  85706. function endLoopBlock() {
  85707. ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
  85708. var block = endBlock();
  85709. var breakLabel = block.breakLabel;
  85710. if (!block.isScript) {
  85711. markLabel(breakLabel);
  85712. }
  85713. }
  85714. /**
  85715. * Begins a code block that supports `break` statements that are defined in the source
  85716. * tree and not from generated code.
  85717. *
  85718. */
  85719. function beginScriptSwitchBlock() {
  85720. beginBlock({
  85721. kind: 2 /* Switch */,
  85722. isScript: true,
  85723. breakLabel: -1
  85724. });
  85725. }
  85726. /**
  85727. * Begins a code block that supports `break` statements that are defined in generated code.
  85728. * Returns a label used to mark the operation to which to jump when a `break` statement
  85729. * targets this block.
  85730. */
  85731. function beginSwitchBlock() {
  85732. var breakLabel = defineLabel();
  85733. beginBlock({
  85734. kind: 2 /* Switch */,
  85735. isScript: false,
  85736. breakLabel: breakLabel,
  85737. });
  85738. return breakLabel;
  85739. }
  85740. /**
  85741. * Ends a code block that supports `break` statements that are defined in generated code.
  85742. */
  85743. function endSwitchBlock() {
  85744. ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
  85745. var block = endBlock();
  85746. var breakLabel = block.breakLabel;
  85747. if (!block.isScript) {
  85748. markLabel(breakLabel);
  85749. }
  85750. }
  85751. function beginScriptLabeledBlock(labelText) {
  85752. beginBlock({
  85753. kind: 4 /* Labeled */,
  85754. isScript: true,
  85755. labelText: labelText,
  85756. breakLabel: -1
  85757. });
  85758. }
  85759. function beginLabeledBlock(labelText) {
  85760. var breakLabel = defineLabel();
  85761. beginBlock({
  85762. kind: 4 /* Labeled */,
  85763. isScript: false,
  85764. labelText: labelText,
  85765. breakLabel: breakLabel
  85766. });
  85767. }
  85768. function endLabeledBlock() {
  85769. ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
  85770. var block = endBlock();
  85771. if (!block.isScript) {
  85772. markLabel(block.breakLabel);
  85773. }
  85774. }
  85775. /**
  85776. * Indicates whether the provided block supports `break` statements.
  85777. *
  85778. * @param block A code block.
  85779. */
  85780. function supportsUnlabeledBreak(block) {
  85781. return block.kind === 2 /* Switch */
  85782. || block.kind === 3 /* Loop */;
  85783. }
  85784. /**
  85785. * Indicates whether the provided block supports `break` statements with labels.
  85786. *
  85787. * @param block A code block.
  85788. */
  85789. function supportsLabeledBreakOrContinue(block) {
  85790. return block.kind === 4 /* Labeled */;
  85791. }
  85792. /**
  85793. * Indicates whether the provided block supports `continue` statements.
  85794. *
  85795. * @param block A code block.
  85796. */
  85797. function supportsUnlabeledContinue(block) {
  85798. return block.kind === 3 /* Loop */;
  85799. }
  85800. function hasImmediateContainingLabeledBlock(labelText, start) {
  85801. for (var j = start; j >= 0; j--) {
  85802. var containingBlock = blockStack[j];
  85803. if (supportsLabeledBreakOrContinue(containingBlock)) {
  85804. if (containingBlock.labelText === labelText) {
  85805. return true;
  85806. }
  85807. }
  85808. else {
  85809. break;
  85810. }
  85811. }
  85812. return false;
  85813. }
  85814. /**
  85815. * Finds the label that is the target for a `break` statement.
  85816. *
  85817. * @param labelText An optional name of a containing labeled statement.
  85818. */
  85819. function findBreakTarget(labelText) {
  85820. if (blockStack) {
  85821. if (labelText) {
  85822. for (var i = blockStack.length - 1; i >= 0; i--) {
  85823. var block = blockStack[i];
  85824. if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
  85825. return block.breakLabel;
  85826. }
  85827. else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
  85828. return block.breakLabel;
  85829. }
  85830. }
  85831. }
  85832. else {
  85833. for (var i = blockStack.length - 1; i >= 0; i--) {
  85834. var block = blockStack[i];
  85835. if (supportsUnlabeledBreak(block)) {
  85836. return block.breakLabel;
  85837. }
  85838. }
  85839. }
  85840. }
  85841. return 0;
  85842. }
  85843. /**
  85844. * Finds the label that is the target for a `continue` statement.
  85845. *
  85846. * @param labelText An optional name of a containing labeled statement.
  85847. */
  85848. function findContinueTarget(labelText) {
  85849. if (blockStack) {
  85850. if (labelText) {
  85851. for (var i = blockStack.length - 1; i >= 0; i--) {
  85852. var block = blockStack[i];
  85853. if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
  85854. return block.continueLabel;
  85855. }
  85856. }
  85857. }
  85858. else {
  85859. for (var i = blockStack.length - 1; i >= 0; i--) {
  85860. var block = blockStack[i];
  85861. if (supportsUnlabeledContinue(block)) {
  85862. return block.continueLabel;
  85863. }
  85864. }
  85865. }
  85866. }
  85867. return 0;
  85868. }
  85869. /**
  85870. * Creates an expression that can be used to indicate the value for a label.
  85871. *
  85872. * @param label A label.
  85873. */
  85874. function createLabel(label) {
  85875. if (label !== undefined && label > 0) {
  85876. if (labelExpressions === undefined) {
  85877. labelExpressions = [];
  85878. }
  85879. var expression = ts.createLiteral(-1);
  85880. if (labelExpressions[label] === undefined) {
  85881. labelExpressions[label] = [expression];
  85882. }
  85883. else {
  85884. labelExpressions[label].push(expression);
  85885. }
  85886. return expression;
  85887. }
  85888. return ts.createOmittedExpression();
  85889. }
  85890. /**
  85891. * Creates a numeric literal for the provided instruction.
  85892. */
  85893. function createInstruction(instruction) {
  85894. var literal = ts.createLiteral(instruction);
  85895. ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
  85896. return literal;
  85897. }
  85898. /**
  85899. * Creates a statement that can be used indicate a Break operation to the provided label.
  85900. *
  85901. * @param label A label.
  85902. * @param location An optional source map location for the statement.
  85903. */
  85904. function createInlineBreak(label, location) {
  85905. ts.Debug.assertLessThan(0, label, "Invalid label");
  85906. return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
  85907. createInstruction(3 /* Break */),
  85908. createLabel(label)
  85909. ])), location);
  85910. }
  85911. /**
  85912. * Creates a statement that can be used indicate a Return operation.
  85913. *
  85914. * @param expression The expression for the return statement.
  85915. * @param location An optional source map location for the statement.
  85916. */
  85917. function createInlineReturn(expression, location) {
  85918. return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
  85919. ? [createInstruction(2 /* Return */), expression]
  85920. : [createInstruction(2 /* Return */)])), location);
  85921. }
  85922. /**
  85923. * Creates an expression that can be used to resume from a Yield operation.
  85924. */
  85925. function createGeneratorResume(location) {
  85926. return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"),
  85927. /*typeArguments*/ undefined, []), location);
  85928. }
  85929. /**
  85930. * Emits an empty instruction.
  85931. */
  85932. function emitNop() {
  85933. emitWorker(0 /* Nop */);
  85934. }
  85935. /**
  85936. * Emits a Statement.
  85937. *
  85938. * @param node A statement.
  85939. */
  85940. function emitStatement(node) {
  85941. if (node) {
  85942. emitWorker(1 /* Statement */, [node]);
  85943. }
  85944. else {
  85945. emitNop();
  85946. }
  85947. }
  85948. /**
  85949. * Emits an Assignment operation.
  85950. *
  85951. * @param left The left-hand side of the assignment.
  85952. * @param right The right-hand side of the assignment.
  85953. * @param location An optional source map location for the assignment.
  85954. */
  85955. function emitAssignment(left, right, location) {
  85956. emitWorker(2 /* Assign */, [left, right], location);
  85957. }
  85958. /**
  85959. * Emits a Break operation to the specified label.
  85960. *
  85961. * @param label A label.
  85962. * @param location An optional source map location for the assignment.
  85963. */
  85964. function emitBreak(label, location) {
  85965. emitWorker(3 /* Break */, [label], location);
  85966. }
  85967. /**
  85968. * Emits a Break operation to the specified label when a condition evaluates to a truthy
  85969. * value at runtime.
  85970. *
  85971. * @param label A label.
  85972. * @param condition The condition.
  85973. * @param location An optional source map location for the assignment.
  85974. */
  85975. function emitBreakWhenTrue(label, condition, location) {
  85976. emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
  85977. }
  85978. /**
  85979. * Emits a Break to the specified label when a condition evaluates to a falsey value at
  85980. * runtime.
  85981. *
  85982. * @param label A label.
  85983. * @param condition The condition.
  85984. * @param location An optional source map location for the assignment.
  85985. */
  85986. function emitBreakWhenFalse(label, condition, location) {
  85987. emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
  85988. }
  85989. /**
  85990. * Emits a YieldStar operation for the provided expression.
  85991. *
  85992. * @param expression An optional value for the yield operation.
  85993. * @param location An optional source map location for the assignment.
  85994. */
  85995. function emitYieldStar(expression, location) {
  85996. emitWorker(7 /* YieldStar */, [expression], location);
  85997. }
  85998. /**
  85999. * Emits a Yield operation for the provided expression.
  86000. *
  86001. * @param expression An optional value for the yield operation.
  86002. * @param location An optional source map location for the assignment.
  86003. */
  86004. function emitYield(expression, location) {
  86005. emitWorker(6 /* Yield */, [expression], location);
  86006. }
  86007. /**
  86008. * Emits a Return operation for the provided expression.
  86009. *
  86010. * @param expression An optional value for the operation.
  86011. * @param location An optional source map location for the assignment.
  86012. */
  86013. function emitReturn(expression, location) {
  86014. emitWorker(8 /* Return */, [expression], location);
  86015. }
  86016. /**
  86017. * Emits a Throw operation for the provided expression.
  86018. *
  86019. * @param expression A value for the operation.
  86020. * @param location An optional source map location for the assignment.
  86021. */
  86022. function emitThrow(expression, location) {
  86023. emitWorker(9 /* Throw */, [expression], location);
  86024. }
  86025. /**
  86026. * Emits an Endfinally operation. This is used to handle `finally` block semantics.
  86027. */
  86028. function emitEndfinally() {
  86029. emitWorker(10 /* Endfinally */);
  86030. }
  86031. /**
  86032. * Emits an operation.
  86033. *
  86034. * @param code The OpCode for the operation.
  86035. * @param args The optional arguments for the operation.
  86036. */
  86037. function emitWorker(code, args, location) {
  86038. if (operations === undefined) {
  86039. operations = [];
  86040. operationArguments = [];
  86041. operationLocations = [];
  86042. }
  86043. if (labelOffsets === undefined) {
  86044. // mark entry point
  86045. markLabel(defineLabel());
  86046. }
  86047. var operationIndex = operations.length;
  86048. operations[operationIndex] = code;
  86049. operationArguments[operationIndex] = args;
  86050. operationLocations[operationIndex] = location;
  86051. }
  86052. /**
  86053. * Builds the generator function body.
  86054. */
  86055. function build() {
  86056. blockIndex = 0;
  86057. labelNumber = 0;
  86058. labelNumbers = undefined;
  86059. lastOperationWasAbrupt = false;
  86060. lastOperationWasCompletion = false;
  86061. clauses = undefined;
  86062. statements = undefined;
  86063. exceptionBlockStack = undefined;
  86064. currentExceptionBlock = undefined;
  86065. withBlockStack = undefined;
  86066. var buildResult = buildStatements();
  86067. return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
  86068. /*modifiers*/ undefined,
  86069. /*asteriskToken*/ undefined,
  86070. /*name*/ undefined,
  86071. /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)],
  86072. /*type*/ undefined, ts.createBlock(buildResult,
  86073. /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
  86074. }
  86075. /**
  86076. * Builds the statements for the generator function body.
  86077. */
  86078. function buildStatements() {
  86079. if (operations) {
  86080. for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
  86081. writeOperation(operationIndex);
  86082. }
  86083. flushFinalLabel(operations.length);
  86084. }
  86085. else {
  86086. flushFinalLabel(0);
  86087. }
  86088. if (clauses) {
  86089. var labelExpression = ts.createPropertyAccess(state, "label");
  86090. var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
  86091. return [ts.startOnNewLine(switchStatement)];
  86092. }
  86093. if (statements) {
  86094. return statements;
  86095. }
  86096. return [];
  86097. }
  86098. /**
  86099. * Flush the current label and advance to a new label.
  86100. */
  86101. function flushLabel() {
  86102. if (!statements) {
  86103. return;
  86104. }
  86105. appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
  86106. lastOperationWasAbrupt = false;
  86107. lastOperationWasCompletion = false;
  86108. labelNumber++;
  86109. }
  86110. /**
  86111. * Flush the final label of the generator function body.
  86112. */
  86113. function flushFinalLabel(operationIndex) {
  86114. if (isFinalLabelReachable(operationIndex)) {
  86115. tryEnterLabel(operationIndex);
  86116. withBlockStack = undefined;
  86117. writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
  86118. }
  86119. if (statements && clauses) {
  86120. appendLabel(/*markLabelEnd*/ false);
  86121. }
  86122. updateLabelExpressions();
  86123. }
  86124. /**
  86125. * Tests whether the final label of the generator function body
  86126. * is reachable by user code.
  86127. */
  86128. function isFinalLabelReachable(operationIndex) {
  86129. // if the last operation was *not* a completion (return/throw) then
  86130. // the final label is reachable.
  86131. if (!lastOperationWasCompletion) {
  86132. return true;
  86133. }
  86134. // if there are no labels defined or referenced, then the final label is
  86135. // not reachable.
  86136. if (!labelOffsets || !labelExpressions) {
  86137. return false;
  86138. }
  86139. // if the label for this offset is referenced, then the final label
  86140. // is reachable.
  86141. for (var label = 0; label < labelOffsets.length; label++) {
  86142. if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
  86143. return true;
  86144. }
  86145. }
  86146. return false;
  86147. }
  86148. /**
  86149. * Appends a case clause for the last label and sets the new label.
  86150. *
  86151. * @param markLabelEnd Indicates that the transition between labels was a fall-through
  86152. * from a previous case clause and the change in labels should be
  86153. * reflected on the `state` object.
  86154. */
  86155. function appendLabel(markLabelEnd) {
  86156. if (!clauses) {
  86157. clauses = [];
  86158. }
  86159. if (statements) {
  86160. if (withBlockStack) {
  86161. // The previous label was nested inside one or more `with` blocks, so we
  86162. // surround the statements in generated `with` blocks to create the same environment.
  86163. for (var i = withBlockStack.length - 1; i >= 0; i--) {
  86164. var withBlock = withBlockStack[i];
  86165. statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
  86166. }
  86167. }
  86168. if (currentExceptionBlock) {
  86169. // The previous label was nested inside of an exception block, so we must
  86170. // indicate entry into a protected region by pushing the label numbers
  86171. // for each block in the protected region.
  86172. var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
  86173. statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"),
  86174. /*typeArguments*/ undefined, [
  86175. ts.createArrayLiteral([
  86176. createLabel(startLabel),
  86177. createLabel(catchLabel),
  86178. createLabel(finallyLabel),
  86179. createLabel(endLabel)
  86180. ])
  86181. ])));
  86182. currentExceptionBlock = undefined;
  86183. }
  86184. if (markLabelEnd) {
  86185. // The case clause for the last label falls through to this label, so we
  86186. // add an assignment statement to reflect the change in labels.
  86187. statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
  86188. }
  86189. }
  86190. clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
  86191. statements = undefined;
  86192. }
  86193. /**
  86194. * Tries to enter into a new label at the current operation index.
  86195. */
  86196. function tryEnterLabel(operationIndex) {
  86197. if (!labelOffsets) {
  86198. return;
  86199. }
  86200. for (var label = 0; label < labelOffsets.length; label++) {
  86201. if (labelOffsets[label] === operationIndex) {
  86202. flushLabel();
  86203. if (labelNumbers === undefined) {
  86204. labelNumbers = [];
  86205. }
  86206. if (labelNumbers[labelNumber] === undefined) {
  86207. labelNumbers[labelNumber] = [label];
  86208. }
  86209. else {
  86210. labelNumbers[labelNumber].push(label);
  86211. }
  86212. }
  86213. }
  86214. }
  86215. /**
  86216. * Updates literal expressions for labels with actual label numbers.
  86217. */
  86218. function updateLabelExpressions() {
  86219. if (labelExpressions !== undefined && labelNumbers !== undefined) {
  86220. for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
  86221. var labels = labelNumbers[labelNumber_1];
  86222. if (labels !== undefined) {
  86223. for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
  86224. var label = labels_1[_i];
  86225. var expressions = labelExpressions[label];
  86226. if (expressions !== undefined) {
  86227. for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
  86228. var expression = expressions_1[_a];
  86229. expression.text = String(labelNumber_1);
  86230. }
  86231. }
  86232. }
  86233. }
  86234. }
  86235. }
  86236. }
  86237. /**
  86238. * Tries to enter or leave a code block.
  86239. */
  86240. function tryEnterOrLeaveBlock(operationIndex) {
  86241. if (blocks) {
  86242. for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
  86243. var block = blocks[blockIndex];
  86244. var blockAction = blockActions[blockIndex];
  86245. switch (block.kind) {
  86246. case 0 /* Exception */:
  86247. if (blockAction === 0 /* Open */) {
  86248. if (!exceptionBlockStack) {
  86249. exceptionBlockStack = [];
  86250. }
  86251. if (!statements) {
  86252. statements = [];
  86253. }
  86254. exceptionBlockStack.push(currentExceptionBlock);
  86255. currentExceptionBlock = block;
  86256. }
  86257. else if (blockAction === 1 /* Close */) {
  86258. currentExceptionBlock = exceptionBlockStack.pop();
  86259. }
  86260. break;
  86261. case 1 /* With */:
  86262. if (blockAction === 0 /* Open */) {
  86263. if (!withBlockStack) {
  86264. withBlockStack = [];
  86265. }
  86266. withBlockStack.push(block);
  86267. }
  86268. else if (blockAction === 1 /* Close */) {
  86269. withBlockStack.pop();
  86270. }
  86271. break;
  86272. // default: do nothing
  86273. }
  86274. }
  86275. }
  86276. }
  86277. /**
  86278. * Writes an operation as a statement to the current label's statement list.
  86279. *
  86280. * @param operation The OpCode of the operation
  86281. */
  86282. function writeOperation(operationIndex) {
  86283. tryEnterLabel(operationIndex);
  86284. tryEnterOrLeaveBlock(operationIndex);
  86285. // early termination, nothing else to process in this label
  86286. if (lastOperationWasAbrupt) {
  86287. return;
  86288. }
  86289. lastOperationWasAbrupt = false;
  86290. lastOperationWasCompletion = false;
  86291. var opcode = operations[operationIndex];
  86292. if (opcode === 0 /* Nop */) {
  86293. return;
  86294. }
  86295. else if (opcode === 10 /* Endfinally */) {
  86296. return writeEndfinally();
  86297. }
  86298. var args = operationArguments[operationIndex];
  86299. if (opcode === 1 /* Statement */) {
  86300. return writeStatement(args[0]);
  86301. }
  86302. var location = operationLocations[operationIndex];
  86303. switch (opcode) {
  86304. case 2 /* Assign */:
  86305. return writeAssign(args[0], args[1], location);
  86306. case 3 /* Break */:
  86307. return writeBreak(args[0], location);
  86308. case 4 /* BreakWhenTrue */:
  86309. return writeBreakWhenTrue(args[0], args[1], location);
  86310. case 5 /* BreakWhenFalse */:
  86311. return writeBreakWhenFalse(args[0], args[1], location);
  86312. case 6 /* Yield */:
  86313. return writeYield(args[0], location);
  86314. case 7 /* YieldStar */:
  86315. return writeYieldStar(args[0], location);
  86316. case 8 /* Return */:
  86317. return writeReturn(args[0], location);
  86318. case 9 /* Throw */:
  86319. return writeThrow(args[0], location);
  86320. }
  86321. }
  86322. /**
  86323. * Writes a statement to the current label's statement list.
  86324. *
  86325. * @param statement A statement to write.
  86326. */
  86327. function writeStatement(statement) {
  86328. if (statement) {
  86329. if (!statements) {
  86330. statements = [statement];
  86331. }
  86332. else {
  86333. statements.push(statement);
  86334. }
  86335. }
  86336. }
  86337. /**
  86338. * Writes an Assign operation to the current label's statement list.
  86339. *
  86340. * @param left The left-hand side of the assignment.
  86341. * @param right The right-hand side of the assignment.
  86342. * @param operationLocation The source map location for the operation.
  86343. */
  86344. function writeAssign(left, right, operationLocation) {
  86345. writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
  86346. }
  86347. /**
  86348. * Writes a Throw operation to the current label's statement list.
  86349. *
  86350. * @param expression The value to throw.
  86351. * @param operationLocation The source map location for the operation.
  86352. */
  86353. function writeThrow(expression, operationLocation) {
  86354. lastOperationWasAbrupt = true;
  86355. lastOperationWasCompletion = true;
  86356. writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
  86357. }
  86358. /**
  86359. * Writes a Return operation to the current label's statement list.
  86360. *
  86361. * @param expression The value to return.
  86362. * @param operationLocation The source map location for the operation.
  86363. */
  86364. function writeReturn(expression, operationLocation) {
  86365. lastOperationWasAbrupt = true;
  86366. lastOperationWasCompletion = true;
  86367. writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
  86368. ? [createInstruction(2 /* Return */), expression]
  86369. : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
  86370. }
  86371. /**
  86372. * Writes a Break operation to the current label's statement list.
  86373. *
  86374. * @param label The label for the Break.
  86375. * @param operationLocation The source map location for the operation.
  86376. */
  86377. function writeBreak(label, operationLocation) {
  86378. lastOperationWasAbrupt = true;
  86379. writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
  86380. createInstruction(3 /* Break */),
  86381. createLabel(label)
  86382. ])), operationLocation), 384 /* NoTokenSourceMaps */));
  86383. }
  86384. /**
  86385. * Writes a BreakWhenTrue operation to the current label's statement list.
  86386. *
  86387. * @param label The label for the Break.
  86388. * @param condition The condition for the Break.
  86389. * @param operationLocation The source map location for the operation.
  86390. */
  86391. function writeBreakWhenTrue(label, condition, operationLocation) {
  86392. writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
  86393. createInstruction(3 /* Break */),
  86394. createLabel(label)
  86395. ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
  86396. }
  86397. /**
  86398. * Writes a BreakWhenFalse operation to the current label's statement list.
  86399. *
  86400. * @param label The label for the Break.
  86401. * @param condition The condition for the Break.
  86402. * @param operationLocation The source map location for the operation.
  86403. */
  86404. function writeBreakWhenFalse(label, condition, operationLocation) {
  86405. writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
  86406. createInstruction(3 /* Break */),
  86407. createLabel(label)
  86408. ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
  86409. }
  86410. /**
  86411. * Writes a Yield operation to the current label's statement list.
  86412. *
  86413. * @param expression The expression to yield.
  86414. * @param operationLocation The source map location for the operation.
  86415. */
  86416. function writeYield(expression, operationLocation) {
  86417. lastOperationWasAbrupt = true;
  86418. writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
  86419. ? [createInstruction(4 /* Yield */), expression]
  86420. : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
  86421. }
  86422. /**
  86423. * Writes a YieldStar instruction to the current label's statement list.
  86424. *
  86425. * @param expression The expression to yield.
  86426. * @param operationLocation The source map location for the operation.
  86427. */
  86428. function writeYieldStar(expression, operationLocation) {
  86429. lastOperationWasAbrupt = true;
  86430. writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
  86431. createInstruction(5 /* YieldStar */),
  86432. expression
  86433. ])), operationLocation), 384 /* NoTokenSourceMaps */));
  86434. }
  86435. /**
  86436. * Writes an Endfinally instruction to the current label's statement list.
  86437. */
  86438. function writeEndfinally() {
  86439. lastOperationWasAbrupt = true;
  86440. writeStatement(ts.createReturn(ts.createArrayLiteral([
  86441. createInstruction(7 /* Endfinally */)
  86442. ])));
  86443. }
  86444. }
  86445. ts.transformGenerators = transformGenerators;
  86446. function createGeneratorHelper(context, body) {
  86447. context.requestEmitHelper(ts.generatorHelper);
  86448. return ts.createCall(ts.getUnscopedHelperName("__generator"),
  86449. /*typeArguments*/ undefined, [ts.createThis(), body]);
  86450. }
  86451. // The __generator helper is used by down-level transformations to emulate the runtime
  86452. // semantics of an ES2015 generator function. When called, this helper returns an
  86453. // object that implements the Iterator protocol, in that it has `next`, `return`, and
  86454. // `throw` methods that step through the generator when invoked.
  86455. //
  86456. // parameters:
  86457. // @param thisArg The value to use as the `this` binding for the transformed generator body.
  86458. // @param body A function that acts as the transformed generator body.
  86459. //
  86460. // variables:
  86461. // _ Persistent state for the generator that is shared between the helper and the
  86462. // generator body. The state object has the following members:
  86463. // sent() - A method that returns or throws the current completion value.
  86464. // label - The next point at which to resume evaluation of the generator body.
  86465. // trys - A stack of protected regions (try/catch/finally blocks).
  86466. // ops - A stack of pending instructions when inside of a finally block.
  86467. // f A value indicating whether the generator is executing.
  86468. // y An iterator to delegate for a yield*.
  86469. // t A temporary variable that holds one of the following values (note that these
  86470. // cases do not overlap):
  86471. // - The completion value when resuming from a `yield` or `yield*`.
  86472. // - The error value for a catch block.
  86473. // - The current protected region (array of try/catch/finally/end labels).
  86474. // - The verb (`next`, `throw`, or `return` method) to delegate to the expression
  86475. // of a `yield*`.
  86476. // - The result of evaluating the verb delegated to the expression of a `yield*`.
  86477. //
  86478. // functions:
  86479. // verb(n) Creates a bound callback to the `step` function for opcode `n`.
  86480. // step(op) Evaluates opcodes in a generator body until execution is suspended or
  86481. // completed.
  86482. //
  86483. // The __generator helper understands a limited set of instructions:
  86484. // 0: next(value?) - Start or resume the generator with the specified value.
  86485. // 1: throw(error) - Resume the generator with an exception. If the generator is
  86486. // suspended inside of one or more protected regions, evaluates
  86487. // any intervening finally blocks between the current label and
  86488. // the nearest catch block or function boundary. If uncaught, the
  86489. // exception is thrown to the caller.
  86490. // 2: return(value?) - Resume the generator as if with a return. If the generator is
  86491. // suspended inside of one or more protected regions, evaluates any
  86492. // intervening finally blocks.
  86493. // 3: break(label) - Jump to the specified label. If the label is outside of the
  86494. // current protected region, evaluates any intervening finally
  86495. // blocks.
  86496. // 4: yield(value?) - Yield execution to the caller with an optional value. When
  86497. // resumed, the generator will continue at the next label.
  86498. // 5: yield*(value) - Delegates evaluation to the supplied iterator. When
  86499. // delegation completes, the generator will continue at the next
  86500. // label.
  86501. // 6: catch(error) - Handles an exception thrown from within the generator body. If
  86502. // the current label is inside of one or more protected regions,
  86503. // evaluates any intervening finally blocks between the current
  86504. // label and the nearest catch block or function boundary. If
  86505. // uncaught, the exception is thrown to the caller.
  86506. // 7: endfinally - Ends a finally block, resuming the last instruction prior to
  86507. // entering a finally block.
  86508. //
  86509. // For examples of how these are used, see the comments in ./transformers/generators.ts
  86510. ts.generatorHelper = {
  86511. name: "typescript:generator",
  86512. importName: "__generator",
  86513. scoped: false,
  86514. priority: 6,
  86515. text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };"
  86516. };
  86517. })(ts || (ts = {}));
  86518. /*@internal*/
  86519. var ts;
  86520. (function (ts) {
  86521. function transformModule(context) {
  86522. function getTransformModuleDelegate(moduleKind) {
  86523. switch (moduleKind) {
  86524. case ts.ModuleKind.AMD: return transformAMDModule;
  86525. case ts.ModuleKind.UMD: return transformUMDModule;
  86526. default: return transformCommonJSModule;
  86527. }
  86528. }
  86529. var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
  86530. var compilerOptions = context.getCompilerOptions();
  86531. var resolver = context.getEmitResolver();
  86532. var host = context.getEmitHost();
  86533. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  86534. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  86535. var previousOnSubstituteNode = context.onSubstituteNode;
  86536. var previousOnEmitNode = context.onEmitNode;
  86537. context.onSubstituteNode = onSubstituteNode;
  86538. context.onEmitNode = onEmitNode;
  86539. context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
  86540. context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
  86541. context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
  86542. context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
  86543. context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
  86544. context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
  86545. var moduleInfoMap = []; // The ExternalModuleInfo for each file.
  86546. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
  86547. var currentSourceFile; // The current file.
  86548. var currentModuleInfo; // The ExternalModuleInfo for the current file.
  86549. var noSubstitution; // Set of nodes for which substitution rules should be ignored.
  86550. var needUMDDynamicImportHelper;
  86551. return ts.chainBundle(transformSourceFile);
  86552. /**
  86553. * Transforms the module aspects of a SourceFile.
  86554. *
  86555. * @param node The SourceFile node.
  86556. */
  86557. function transformSourceFile(node) {
  86558. if (node.isDeclarationFile ||
  86559. !(ts.isEffectiveExternalModule(node, compilerOptions) ||
  86560. node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
  86561. (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
  86562. return node;
  86563. }
  86564. currentSourceFile = node;
  86565. currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
  86566. moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
  86567. // Perform the transformation.
  86568. var transformModule = getTransformModuleDelegate(moduleKind);
  86569. var updated = transformModule(node);
  86570. currentSourceFile = undefined;
  86571. currentModuleInfo = undefined;
  86572. needUMDDynamicImportHelper = false;
  86573. return ts.aggregateTransformFlags(updated);
  86574. }
  86575. function shouldEmitUnderscoreUnderscoreESModule() {
  86576. if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
  86577. return true;
  86578. }
  86579. return false;
  86580. }
  86581. /**
  86582. * Transforms a SourceFile into a CommonJS module.
  86583. *
  86584. * @param node The SourceFile node.
  86585. */
  86586. function transformCommonJSModule(node) {
  86587. startLexicalEnvironment();
  86588. var statements = [];
  86589. var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
  86590. var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
  86591. if (shouldEmitUnderscoreUnderscoreESModule()) {
  86592. ts.append(statements, createUnderscoreUnderscoreESModule());
  86593. }
  86594. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
  86595. ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
  86596. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
  86597. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  86598. var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
  86599. if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
  86600. // If we have any `export * from ...` declarations
  86601. // we need to inform the emitter to add the __export helper.
  86602. ts.addEmitHelper(updated, exportStarHelper);
  86603. }
  86604. ts.addEmitHelpers(updated, context.readEmitHelpers());
  86605. return updated;
  86606. }
  86607. /**
  86608. * Transforms a SourceFile into an AMD module.
  86609. *
  86610. * @param node The SourceFile node.
  86611. */
  86612. function transformAMDModule(node) {
  86613. var define = ts.createIdentifier("define");
  86614. var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
  86615. var jsonSourceFile = ts.isJsonSourceFile(node) && node;
  86616. // An AMD define function has the following shape:
  86617. //
  86618. // define(id?, dependencies?, factory);
  86619. //
  86620. // This has the shape of the following:
  86621. //
  86622. // define(name, ["module1", "module2"], function (module1Alias) { ... }
  86623. //
  86624. // The location of the alias in the parameter list in the factory function needs to
  86625. // match the position of the module name in the dependency list.
  86626. //
  86627. // To ensure this is true in cases of modules with no aliases, e.g.:
  86628. //
  86629. // import "module"
  86630. //
  86631. // or
  86632. //
  86633. // /// <amd-dependency path= "a.css" />
  86634. //
  86635. // we need to add modules without alias names to the end of the dependencies list
  86636. var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
  86637. // Create an updated SourceFile:
  86638. //
  86639. // define(moduleName?, ["module1", "module2"], function ...
  86640. var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
  86641. ts.createExpressionStatement(ts.createCall(define,
  86642. /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
  86643. // Add the dependency array argument:
  86644. //
  86645. // ["require", "exports", module1", "module2", ...]
  86646. ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
  86647. ts.createLiteral("require"),
  86648. ts.createLiteral("exports")
  86649. ], aliasedModuleNames, unaliasedModuleNames)),
  86650. // Add the module body function argument:
  86651. //
  86652. // function (require, exports, module1, module2) ...
  86653. jsonSourceFile ?
  86654. jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
  86655. ts.createFunctionExpression(
  86656. /*modifiers*/ undefined,
  86657. /*asteriskToken*/ undefined,
  86658. /*name*/ undefined,
  86659. /*typeParameters*/ undefined, __spreadArrays([
  86660. ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
  86661. ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
  86662. ], importAliasNames),
  86663. /*type*/ undefined, transformAsynchronousModuleBody(node))
  86664. ])))
  86665. ]),
  86666. /*location*/ node.statements));
  86667. ts.addEmitHelpers(updated, context.readEmitHelpers());
  86668. return updated;
  86669. }
  86670. /**
  86671. * Transforms a SourceFile into a UMD module.
  86672. *
  86673. * @param node The SourceFile node.
  86674. */
  86675. function transformUMDModule(node) {
  86676. var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
  86677. var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
  86678. var umdHeader = ts.createFunctionExpression(
  86679. /*modifiers*/ undefined,
  86680. /*asteriskToken*/ undefined,
  86681. /*name*/ undefined,
  86682. /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")],
  86683. /*type*/ undefined, ts.setTextRange(ts.createBlock([
  86684. ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
  86685. ts.createVariableStatement(
  86686. /*modifiers*/ undefined, [
  86687. ts.createVariableDeclaration("v",
  86688. /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"),
  86689. /*typeArguments*/ undefined, [
  86690. ts.createIdentifier("require"),
  86691. ts.createIdentifier("exports")
  86692. ]))
  86693. ]),
  86694. ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */)
  86695. ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
  86696. ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"),
  86697. /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
  86698. ts.createArrayLiteral(__spreadArrays([
  86699. ts.createLiteral("require"),
  86700. ts.createLiteral("exports")
  86701. ], aliasedModuleNames, unaliasedModuleNames)),
  86702. ts.createIdentifier("factory")
  86703. ])))
  86704. ])))
  86705. ],
  86706. /*multiLine*/ true),
  86707. /*location*/ undefined));
  86708. // Create an updated SourceFile:
  86709. //
  86710. // (function (factory) {
  86711. // if (typeof module === "object" && typeof module.exports === "object") {
  86712. // var v = factory(require, exports);
  86713. // if (v !== undefined) module.exports = v;
  86714. // }
  86715. // else if (typeof define === 'function' && define.amd) {
  86716. // define(["require", "exports"], factory);
  86717. // }
  86718. // })(function ...)
  86719. var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
  86720. ts.createExpressionStatement(ts.createCall(umdHeader,
  86721. /*typeArguments*/ undefined, [
  86722. // Add the module body function argument:
  86723. //
  86724. // function (require, exports) ...
  86725. ts.createFunctionExpression(
  86726. /*modifiers*/ undefined,
  86727. /*asteriskToken*/ undefined,
  86728. /*name*/ undefined,
  86729. /*typeParameters*/ undefined, __spreadArrays([
  86730. ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
  86731. ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
  86732. ], importAliasNames),
  86733. /*type*/ undefined, transformAsynchronousModuleBody(node))
  86734. ]))
  86735. ]),
  86736. /*location*/ node.statements));
  86737. ts.addEmitHelpers(updated, context.readEmitHelpers());
  86738. return updated;
  86739. }
  86740. /**
  86741. * Collect the additional asynchronous dependencies for the module.
  86742. *
  86743. * @param node The source file.
  86744. * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
  86745. */
  86746. function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
  86747. // names of modules with corresponding parameter in the factory function
  86748. var aliasedModuleNames = [];
  86749. // names of modules with no corresponding parameters in factory function
  86750. var unaliasedModuleNames = [];
  86751. // names of the parameters in the factory function; these
  86752. // parameters need to match the indexes of the corresponding
  86753. // module names in aliasedModuleNames.
  86754. var importAliasNames = [];
  86755. // Fill in amd-dependency tags
  86756. for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
  86757. var amdDependency = _a[_i];
  86758. if (amdDependency.name) {
  86759. aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
  86760. importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
  86761. }
  86762. else {
  86763. unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
  86764. }
  86765. }
  86766. for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
  86767. var importNode = _c[_b];
  86768. // Find the name of the external module
  86769. var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
  86770. // Find the name of the module alias, if there is one
  86771. var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
  86772. // It is possible that externalModuleName is undefined if it is not string literal.
  86773. // This can happen in the invalid import syntax.
  86774. // E.g : "import * from alias from 'someLib';"
  86775. if (externalModuleName) {
  86776. if (includeNonAmdDependencies && importAliasName) {
  86777. // Set emitFlags on the name of the classDeclaration
  86778. // This is so that when printer will not substitute the identifier
  86779. ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
  86780. aliasedModuleNames.push(externalModuleName);
  86781. importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
  86782. }
  86783. else {
  86784. unaliasedModuleNames.push(externalModuleName);
  86785. }
  86786. }
  86787. }
  86788. return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
  86789. }
  86790. function getAMDImportExpressionForImport(node) {
  86791. if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
  86792. return undefined;
  86793. }
  86794. var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
  86795. var expr = getHelperExpressionForImport(node, name);
  86796. if (expr === name) {
  86797. return undefined;
  86798. }
  86799. return ts.createExpressionStatement(ts.createAssignment(name, expr));
  86800. }
  86801. /**
  86802. * Transforms a SourceFile into an AMD or UMD module body.
  86803. *
  86804. * @param node The SourceFile node.
  86805. */
  86806. function transformAsynchronousModuleBody(node) {
  86807. startLexicalEnvironment();
  86808. var statements = [];
  86809. var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
  86810. if (shouldEmitUnderscoreUnderscoreESModule()) {
  86811. ts.append(statements, createUnderscoreUnderscoreESModule());
  86812. }
  86813. // Visit each statement of the module body.
  86814. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
  86815. if (moduleKind === ts.ModuleKind.AMD) {
  86816. ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
  86817. }
  86818. ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
  86819. // Append the 'export =' statement if provided.
  86820. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
  86821. // End the lexical environment for the module body
  86822. // and merge any new lexical declarations.
  86823. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  86824. var body = ts.createBlock(statements, /*multiLine*/ true);
  86825. if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
  86826. // If we have any `export * from ...` declarations
  86827. // we need to inform the emitter to add the __export helper.
  86828. ts.addEmitHelper(body, exportStarHelper);
  86829. }
  86830. if (needUMDDynamicImportHelper) {
  86831. ts.addEmitHelper(body, dynamicImportUMDHelper);
  86832. }
  86833. return body;
  86834. }
  86835. /**
  86836. * Adds the down-level representation of `export=` to the statement list if one exists
  86837. * in the source file.
  86838. *
  86839. * @param statements The Statement list to modify.
  86840. * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
  86841. * return statement.
  86842. */
  86843. function addExportEqualsIfNeeded(statements, emitAsReturn) {
  86844. if (currentModuleInfo.exportEquals) {
  86845. var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
  86846. if (expressionResult) {
  86847. if (emitAsReturn) {
  86848. var statement = ts.createReturn(expressionResult);
  86849. ts.setTextRange(statement, currentModuleInfo.exportEquals);
  86850. ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
  86851. statements.push(statement);
  86852. }
  86853. else {
  86854. var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
  86855. ts.setTextRange(statement, currentModuleInfo.exportEquals);
  86856. ts.setEmitFlags(statement, 1536 /* NoComments */);
  86857. statements.push(statement);
  86858. }
  86859. }
  86860. }
  86861. }
  86862. //
  86863. // Top-Level Source Element Visitors
  86864. //
  86865. /**
  86866. * Visits a node at the top level of the source file.
  86867. *
  86868. * @param node The node to visit.
  86869. */
  86870. function sourceElementVisitor(node) {
  86871. switch (node.kind) {
  86872. case 254 /* ImportDeclaration */:
  86873. return visitImportDeclaration(node);
  86874. case 253 /* ImportEqualsDeclaration */:
  86875. return visitImportEqualsDeclaration(node);
  86876. case 260 /* ExportDeclaration */:
  86877. return visitExportDeclaration(node);
  86878. case 259 /* ExportAssignment */:
  86879. return visitExportAssignment(node);
  86880. case 225 /* VariableStatement */:
  86881. return visitVariableStatement(node);
  86882. case 244 /* FunctionDeclaration */:
  86883. return visitFunctionDeclaration(node);
  86884. case 245 /* ClassDeclaration */:
  86885. return visitClassDeclaration(node);
  86886. case 327 /* MergeDeclarationMarker */:
  86887. return visitMergeDeclarationMarker(node);
  86888. case 328 /* EndOfDeclarationMarker */:
  86889. return visitEndOfDeclarationMarker(node);
  86890. default:
  86891. return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
  86892. }
  86893. }
  86894. function moduleExpressionElementVisitor(node) {
  86895. // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
  86896. // as export/import statements are only transformed at the top level of a file.
  86897. if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
  86898. return node;
  86899. }
  86900. if (ts.isImportCall(node)) {
  86901. return visitImportCallExpression(node);
  86902. }
  86903. else if (ts.isDestructuringAssignment(node)) {
  86904. return visitDestructuringAssignment(node);
  86905. }
  86906. else {
  86907. return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
  86908. }
  86909. }
  86910. function destructuringNeedsFlattening(node) {
  86911. if (ts.isObjectLiteralExpression(node)) {
  86912. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  86913. var elem = _a[_i];
  86914. switch (elem.kind) {
  86915. case 281 /* PropertyAssignment */:
  86916. if (destructuringNeedsFlattening(elem.initializer)) {
  86917. return true;
  86918. }
  86919. break;
  86920. case 282 /* ShorthandPropertyAssignment */:
  86921. if (destructuringNeedsFlattening(elem.name)) {
  86922. return true;
  86923. }
  86924. break;
  86925. case 283 /* SpreadAssignment */:
  86926. if (destructuringNeedsFlattening(elem.expression)) {
  86927. return true;
  86928. }
  86929. break;
  86930. case 161 /* MethodDeclaration */:
  86931. case 163 /* GetAccessor */:
  86932. case 164 /* SetAccessor */:
  86933. return false;
  86934. default: ts.Debug.assertNever(elem, "Unhandled object member kind");
  86935. }
  86936. }
  86937. }
  86938. else if (ts.isArrayLiteralExpression(node)) {
  86939. for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
  86940. var elem = _c[_b];
  86941. if (ts.isSpreadElement(elem)) {
  86942. if (destructuringNeedsFlattening(elem.expression)) {
  86943. return true;
  86944. }
  86945. }
  86946. else if (destructuringNeedsFlattening(elem)) {
  86947. return true;
  86948. }
  86949. }
  86950. }
  86951. else if (ts.isIdentifier(node)) {
  86952. return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
  86953. }
  86954. return false;
  86955. }
  86956. function visitDestructuringAssignment(node) {
  86957. if (destructuringNeedsFlattening(node.left)) {
  86958. return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
  86959. }
  86960. return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
  86961. }
  86962. function visitImportCallExpression(node) {
  86963. var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
  86964. var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
  86965. switch (compilerOptions.module) {
  86966. case ts.ModuleKind.AMD:
  86967. return createImportCallExpressionAMD(argument, containsLexicalThis);
  86968. case ts.ModuleKind.UMD:
  86969. return createImportCallExpressionUMD(argument, containsLexicalThis);
  86970. case ts.ModuleKind.CommonJS:
  86971. default:
  86972. return createImportCallExpressionCommonJS(argument, containsLexicalThis);
  86973. }
  86974. }
  86975. function createImportCallExpressionUMD(arg, containsLexicalThis) {
  86976. // (function (factory) {
  86977. // ... (regular UMD)
  86978. // }
  86979. // })(function (require, exports, useSyncRequire) {
  86980. // "use strict";
  86981. // Object.defineProperty(exports, "__esModule", { value: true });
  86982. // var __syncRequire = typeof module === "object" && typeof module.exports === "object";
  86983. // var __resolved = new Promise(function (resolve) { resolve(); });
  86984. // .....
  86985. // __syncRequire
  86986. // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
  86987. // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
  86988. // });
  86989. needUMDDynamicImportHelper = true;
  86990. if (ts.isSimpleCopiableExpression(arg)) {
  86991. var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
  86992. return ts.createConditional(
  86993. /*condition*/ ts.createIdentifier("__syncRequire"),
  86994. /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis),
  86995. /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
  86996. }
  86997. else {
  86998. var temp = ts.createTempVariable(hoistVariableDeclaration);
  86999. return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
  87000. /*condition*/ ts.createIdentifier("__syncRequire"),
  87001. /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis),
  87002. /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
  87003. }
  87004. }
  87005. function createImportCallExpressionAMD(arg, containsLexicalThis) {
  87006. // improt("./blah")
  87007. // emit as
  87008. // define(["require", "exports", "blah"], function (require, exports) {
  87009. // ...
  87010. // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
  87011. // });
  87012. var resolve = ts.createUniqueName("resolve");
  87013. var reject = ts.createUniqueName("reject");
  87014. var parameters = [
  87015. ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
  87016. ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
  87017. ];
  87018. var body = ts.createBlock([
  87019. ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"),
  87020. /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
  87021. ]);
  87022. var func;
  87023. if (languageVersion >= 2 /* ES2015 */) {
  87024. func = ts.createArrowFunction(
  87025. /*modifiers*/ undefined,
  87026. /*typeParameters*/ undefined, parameters,
  87027. /*type*/ undefined,
  87028. /*equalsGreaterThanToken*/ undefined, body);
  87029. }
  87030. else {
  87031. func = ts.createFunctionExpression(
  87032. /*modifiers*/ undefined,
  87033. /*asteriskToken*/ undefined,
  87034. /*name*/ undefined,
  87035. /*typeParameters*/ undefined, parameters,
  87036. /*type*/ undefined, body);
  87037. // if there is a lexical 'this' in the import call arguments, ensure we indicate
  87038. // that this new function expression indicates it captures 'this' so that the
  87039. // es2015 transformer will properly substitute 'this' with '_this'.
  87040. if (containsLexicalThis) {
  87041. ts.setEmitFlags(func, 8 /* CapturesThis */);
  87042. }
  87043. }
  87044. var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
  87045. if (compilerOptions.esModuleInterop) {
  87046. context.requestEmitHelper(ts.importStarHelper);
  87047. return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
  87048. }
  87049. return promise;
  87050. }
  87051. function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
  87052. // import("./blah")
  87053. // emit as
  87054. // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
  87055. // We have to wrap require in then callback so that require is done in asynchronously
  87056. // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
  87057. var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
  87058. var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
  87059. if (compilerOptions.esModuleInterop) {
  87060. context.requestEmitHelper(ts.importStarHelper);
  87061. requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
  87062. }
  87063. var func;
  87064. if (languageVersion >= 2 /* ES2015 */) {
  87065. func = ts.createArrowFunction(
  87066. /*modifiers*/ undefined,
  87067. /*typeParameters*/ undefined,
  87068. /*parameters*/ [],
  87069. /*type*/ undefined,
  87070. /*equalsGreaterThanToken*/ undefined, requireCall);
  87071. }
  87072. else {
  87073. func = ts.createFunctionExpression(
  87074. /*modifiers*/ undefined,
  87075. /*asteriskToken*/ undefined,
  87076. /*name*/ undefined,
  87077. /*typeParameters*/ undefined,
  87078. /*parameters*/ [],
  87079. /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
  87080. // if there is a lexical 'this' in the import call arguments, ensure we indicate
  87081. // that this new function expression indicates it captures 'this' so that the
  87082. // es2015 transformer will properly substitute 'this' with '_this'.
  87083. if (containsLexicalThis) {
  87084. ts.setEmitFlags(func, 8 /* CapturesThis */);
  87085. }
  87086. }
  87087. return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
  87088. }
  87089. function getHelperExpressionForExport(node, innerExpr) {
  87090. if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
  87091. return innerExpr;
  87092. }
  87093. if (ts.getExportNeedsImportStarHelper(node)) {
  87094. context.requestEmitHelper(ts.importStarHelper);
  87095. return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
  87096. }
  87097. return innerExpr;
  87098. }
  87099. function getHelperExpressionForImport(node, innerExpr) {
  87100. if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
  87101. return innerExpr;
  87102. }
  87103. if (ts.getImportNeedsImportStarHelper(node)) {
  87104. context.requestEmitHelper(ts.importStarHelper);
  87105. return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
  87106. }
  87107. if (ts.getImportNeedsImportDefaultHelper(node)) {
  87108. context.requestEmitHelper(ts.importDefaultHelper);
  87109. return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
  87110. }
  87111. return innerExpr;
  87112. }
  87113. /**
  87114. * Visits an ImportDeclaration node.
  87115. *
  87116. * @param node The node to visit.
  87117. */
  87118. function visitImportDeclaration(node) {
  87119. var statements;
  87120. var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
  87121. if (moduleKind !== ts.ModuleKind.AMD) {
  87122. if (!node.importClause) {
  87123. // import "mod";
  87124. return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
  87125. }
  87126. else {
  87127. var variables = [];
  87128. if (namespaceDeclaration && !ts.isDefaultImport(node)) {
  87129. // import * as n from "mod";
  87130. variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
  87131. /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
  87132. }
  87133. else {
  87134. // import d from "mod";
  87135. // import { x, y } from "mod";
  87136. // import d, { x, y } from "mod";
  87137. // import d, * as n from "mod";
  87138. variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node),
  87139. /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
  87140. if (namespaceDeclaration && ts.isDefaultImport(node)) {
  87141. variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
  87142. /*type*/ undefined, ts.getGeneratedNameForNode(node)));
  87143. }
  87144. }
  87145. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
  87146. /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)),
  87147. /*location*/ node),
  87148. /*original*/ node));
  87149. }
  87150. }
  87151. else if (namespaceDeclaration && ts.isDefaultImport(node)) {
  87152. // import d, * as n from "mod";
  87153. statements = ts.append(statements, ts.createVariableStatement(
  87154. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  87155. ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
  87156. /*type*/ undefined, ts.getGeneratedNameForNode(node)),
  87157. /*location*/ node),
  87158. /*original*/ node)
  87159. ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
  87160. }
  87161. if (hasAssociatedEndOfDeclarationMarker(node)) {
  87162. // Defer exports until we encounter an EndOfDeclarationMarker node
  87163. var id = ts.getOriginalNodeId(node);
  87164. deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
  87165. }
  87166. else {
  87167. statements = appendExportsOfImportDeclaration(statements, node);
  87168. }
  87169. return ts.singleOrMany(statements);
  87170. }
  87171. /**
  87172. * Creates a `require()` call to import an external module.
  87173. *
  87174. * @param importNode The declararation to import.
  87175. */
  87176. function createRequireCall(importNode) {
  87177. var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
  87178. var args = [];
  87179. if (moduleName) {
  87180. args.push(moduleName);
  87181. }
  87182. return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
  87183. }
  87184. /**
  87185. * Visits an ImportEqualsDeclaration node.
  87186. *
  87187. * @param node The node to visit.
  87188. */
  87189. function visitImportEqualsDeclaration(node) {
  87190. ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
  87191. var statements;
  87192. if (moduleKind !== ts.ModuleKind.AMD) {
  87193. if (ts.hasModifier(node, 1 /* Export */)) {
  87194. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
  87195. }
  87196. else {
  87197. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
  87198. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  87199. ts.createVariableDeclaration(ts.getSynthesizedClone(node.name),
  87200. /*type*/ undefined, createRequireCall(node))
  87201. ],
  87202. /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
  87203. }
  87204. }
  87205. else {
  87206. if (ts.hasModifier(node, 1 /* Export */)) {
  87207. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
  87208. }
  87209. }
  87210. if (hasAssociatedEndOfDeclarationMarker(node)) {
  87211. // Defer exports until we encounter an EndOfDeclarationMarker node
  87212. var id = ts.getOriginalNodeId(node);
  87213. deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
  87214. }
  87215. else {
  87216. statements = appendExportsOfImportEqualsDeclaration(statements, node);
  87217. }
  87218. return ts.singleOrMany(statements);
  87219. }
  87220. /**
  87221. * Visits an ExportDeclaration node.
  87222. *
  87223. * @param The node to visit.
  87224. */
  87225. function visitExportDeclaration(node) {
  87226. if (!node.moduleSpecifier) {
  87227. // Elide export declarations with no module specifier as they are handled
  87228. // elsewhere.
  87229. return undefined;
  87230. }
  87231. var generatedName = ts.getGeneratedNameForNode(node);
  87232. if (node.exportClause && ts.isNamedExports(node.exportClause)) {
  87233. var statements = [];
  87234. // export { x, y } from "mod";
  87235. if (moduleKind !== ts.ModuleKind.AMD) {
  87236. statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
  87237. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  87238. ts.createVariableDeclaration(generatedName,
  87239. /*type*/ undefined, createRequireCall(node))
  87240. ])),
  87241. /*location*/ node),
  87242. /* original */ node));
  87243. }
  87244. for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
  87245. var specifier = _a[_i];
  87246. var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
  87247. statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier));
  87248. }
  87249. return ts.singleOrMany(statements);
  87250. }
  87251. else if (node.exportClause) {
  87252. var statements = [];
  87253. // export * as ns from "mod";
  87254. statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
  87255. getHelperExpressionForExport(node, createRequireCall(node)) :
  87256. ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
  87257. return ts.singleOrMany(statements);
  87258. }
  87259. else {
  87260. // export * from "mod";
  87261. return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
  87262. }
  87263. }
  87264. /**
  87265. * Visits an ExportAssignment node.
  87266. *
  87267. * @param node The node to visit.
  87268. */
  87269. function visitExportAssignment(node) {
  87270. if (node.isExportEquals) {
  87271. return undefined;
  87272. }
  87273. var statements;
  87274. var original = node.original;
  87275. if (original && hasAssociatedEndOfDeclarationMarker(original)) {
  87276. // Defer exports until we encounter an EndOfDeclarationMarker node
  87277. var id = ts.getOriginalNodeId(node);
  87278. deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
  87279. }
  87280. else {
  87281. statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
  87282. }
  87283. return ts.singleOrMany(statements);
  87284. }
  87285. /**
  87286. * Visits a FunctionDeclaration node.
  87287. *
  87288. * @param node The node to visit.
  87289. */
  87290. function visitFunctionDeclaration(node) {
  87291. var statements;
  87292. if (ts.hasModifier(node, 1 /* Export */)) {
  87293. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
  87294. /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
  87295. /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
  87296. /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
  87297. /*location*/ node),
  87298. /*original*/ node));
  87299. }
  87300. else {
  87301. statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
  87302. }
  87303. if (hasAssociatedEndOfDeclarationMarker(node)) {
  87304. // Defer exports until we encounter an EndOfDeclarationMarker node
  87305. var id = ts.getOriginalNodeId(node);
  87306. deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
  87307. }
  87308. else {
  87309. statements = appendExportsOfHoistedDeclaration(statements, node);
  87310. }
  87311. return ts.singleOrMany(statements);
  87312. }
  87313. /**
  87314. * Visits a ClassDeclaration node.
  87315. *
  87316. * @param node The node to visit.
  87317. */
  87318. function visitClassDeclaration(node) {
  87319. var statements;
  87320. if (ts.hasModifier(node, 1 /* Export */)) {
  87321. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
  87322. /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
  87323. /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
  87324. }
  87325. else {
  87326. statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
  87327. }
  87328. if (hasAssociatedEndOfDeclarationMarker(node)) {
  87329. // Defer exports until we encounter an EndOfDeclarationMarker node
  87330. var id = ts.getOriginalNodeId(node);
  87331. deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
  87332. }
  87333. else {
  87334. statements = appendExportsOfHoistedDeclaration(statements, node);
  87335. }
  87336. return ts.singleOrMany(statements);
  87337. }
  87338. /**
  87339. * Visits a VariableStatement node.
  87340. *
  87341. * @param node The node to visit.
  87342. */
  87343. function visitVariableStatement(node) {
  87344. var statements;
  87345. var variables;
  87346. var expressions;
  87347. if (ts.hasModifier(node, 1 /* Export */)) {
  87348. var modifiers = void 0;
  87349. // If we're exporting these variables, then these just become assignments to 'exports.x'.
  87350. // We only want to emit assignments for variables with initializers.
  87351. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  87352. var variable = _a[_i];
  87353. if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
  87354. if (!modifiers) {
  87355. modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
  87356. }
  87357. variables = ts.append(variables, variable);
  87358. }
  87359. else if (variable.initializer) {
  87360. expressions = ts.append(expressions, transformInitializedVariable(variable));
  87361. }
  87362. }
  87363. if (variables) {
  87364. statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
  87365. }
  87366. if (expressions) {
  87367. statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
  87368. }
  87369. }
  87370. else {
  87371. statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
  87372. }
  87373. if (hasAssociatedEndOfDeclarationMarker(node)) {
  87374. // Defer exports until we encounter an EndOfDeclarationMarker node
  87375. var id = ts.getOriginalNodeId(node);
  87376. deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
  87377. }
  87378. else {
  87379. statements = appendExportsOfVariableStatement(statements, node);
  87380. }
  87381. return ts.singleOrMany(statements);
  87382. }
  87383. function createAllExportExpressions(name, value, location) {
  87384. var exportedNames = getExports(name);
  87385. if (exportedNames) {
  87386. // For each additional export of the declaration, apply an export assignment.
  87387. var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
  87388. for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
  87389. var exportName = exportedNames_1[_i];
  87390. // Mark the node to prevent triggering substitution.
  87391. ts.setEmitFlags(expression, 4 /* NoSubstitution */);
  87392. expression = createExportExpression(exportName, expression, /*location*/ location);
  87393. }
  87394. return expression;
  87395. }
  87396. return ts.createAssignment(name, value);
  87397. }
  87398. /**
  87399. * Transforms an exported variable with an initializer into an expression.
  87400. *
  87401. * @param node The node to transform.
  87402. */
  87403. function transformInitializedVariable(node) {
  87404. if (ts.isBindingPattern(node.name)) {
  87405. return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
  87406. /*visitor*/ undefined, context, 0 /* All */,
  87407. /*needsValue*/ false, createAllExportExpressions);
  87408. }
  87409. else {
  87410. return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
  87411. /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
  87412. }
  87413. }
  87414. /**
  87415. * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
  87416. * and transformed declaration.
  87417. *
  87418. * @param node The node to visit.
  87419. */
  87420. function visitMergeDeclarationMarker(node) {
  87421. // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
  87422. // declaration we do not emit a leading variable declaration. To preserve the
  87423. // begin/end semantics of the declararation and to properly handle exports
  87424. // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
  87425. //
  87426. // To balance the declaration, add the exports of the elided variable
  87427. // statement.
  87428. if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
  87429. var id = ts.getOriginalNodeId(node);
  87430. deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
  87431. }
  87432. return node;
  87433. }
  87434. /**
  87435. * Determines whether a node has an associated EndOfDeclarationMarker.
  87436. *
  87437. * @param node The node to test.
  87438. */
  87439. function hasAssociatedEndOfDeclarationMarker(node) {
  87440. return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
  87441. }
  87442. /**
  87443. * Visits a DeclarationMarker used as a placeholder for the end of a transformed
  87444. * declaration.
  87445. *
  87446. * @param node The node to visit.
  87447. */
  87448. function visitEndOfDeclarationMarker(node) {
  87449. // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
  87450. // end of the transformed declaration. We use this marker to emit any deferred exports
  87451. // of the declaration.
  87452. var id = ts.getOriginalNodeId(node);
  87453. var statements = deferredExports[id];
  87454. if (statements) {
  87455. delete deferredExports[id];
  87456. return ts.append(statements, node);
  87457. }
  87458. return node;
  87459. }
  87460. /**
  87461. * Appends the exports of an ImportDeclaration to a statement list, returning the
  87462. * statement list.
  87463. *
  87464. * @param statements A statement list to which the down-level export statements are to be
  87465. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87466. * appended.
  87467. * @param decl The declaration whose exports are to be recorded.
  87468. */
  87469. function appendExportsOfImportDeclaration(statements, decl) {
  87470. if (currentModuleInfo.exportEquals) {
  87471. return statements;
  87472. }
  87473. var importClause = decl.importClause;
  87474. if (!importClause) {
  87475. return statements;
  87476. }
  87477. if (importClause.name) {
  87478. statements = appendExportsOfDeclaration(statements, importClause);
  87479. }
  87480. var namedBindings = importClause.namedBindings;
  87481. if (namedBindings) {
  87482. switch (namedBindings.kind) {
  87483. case 256 /* NamespaceImport */:
  87484. statements = appendExportsOfDeclaration(statements, namedBindings);
  87485. break;
  87486. case 257 /* NamedImports */:
  87487. for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
  87488. var importBinding = _a[_i];
  87489. statements = appendExportsOfDeclaration(statements, importBinding);
  87490. }
  87491. break;
  87492. }
  87493. }
  87494. return statements;
  87495. }
  87496. /**
  87497. * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
  87498. * statement list.
  87499. *
  87500. * @param statements A statement list to which the down-level export statements are to be
  87501. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87502. * appended.
  87503. * @param decl The declaration whose exports are to be recorded.
  87504. */
  87505. function appendExportsOfImportEqualsDeclaration(statements, decl) {
  87506. if (currentModuleInfo.exportEquals) {
  87507. return statements;
  87508. }
  87509. return appendExportsOfDeclaration(statements, decl);
  87510. }
  87511. /**
  87512. * Appends the exports of a VariableStatement to a statement list, returning the statement
  87513. * list.
  87514. *
  87515. * @param statements A statement list to which the down-level export statements are to be
  87516. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87517. * appended.
  87518. * @param node The VariableStatement whose exports are to be recorded.
  87519. */
  87520. function appendExportsOfVariableStatement(statements, node) {
  87521. if (currentModuleInfo.exportEquals) {
  87522. return statements;
  87523. }
  87524. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  87525. var decl = _a[_i];
  87526. statements = appendExportsOfBindingElement(statements, decl);
  87527. }
  87528. return statements;
  87529. }
  87530. /**
  87531. * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
  87532. * returning the statement list.
  87533. *
  87534. * @param statements A statement list to which the down-level export statements are to be
  87535. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87536. * appended.
  87537. * @param decl The declaration whose exports are to be recorded.
  87538. */
  87539. function appendExportsOfBindingElement(statements, decl) {
  87540. if (currentModuleInfo.exportEquals) {
  87541. return statements;
  87542. }
  87543. if (ts.isBindingPattern(decl.name)) {
  87544. for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
  87545. var element = _a[_i];
  87546. if (!ts.isOmittedExpression(element)) {
  87547. statements = appendExportsOfBindingElement(statements, element);
  87548. }
  87549. }
  87550. }
  87551. else if (!ts.isGeneratedIdentifier(decl.name)) {
  87552. statements = appendExportsOfDeclaration(statements, decl);
  87553. }
  87554. return statements;
  87555. }
  87556. /**
  87557. * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
  87558. * returning the statement list.
  87559. *
  87560. * @param statements A statement list to which the down-level export statements are to be
  87561. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87562. * appended.
  87563. * @param decl The declaration whose exports are to be recorded.
  87564. */
  87565. function appendExportsOfHoistedDeclaration(statements, decl) {
  87566. if (currentModuleInfo.exportEquals) {
  87567. return statements;
  87568. }
  87569. if (ts.hasModifier(decl, 1 /* Export */)) {
  87570. var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
  87571. statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
  87572. }
  87573. if (decl.name) {
  87574. statements = appendExportsOfDeclaration(statements, decl);
  87575. }
  87576. return statements;
  87577. }
  87578. /**
  87579. * Appends the exports of a declaration to a statement list, returning the statement list.
  87580. *
  87581. * @param statements A statement list to which the down-level export statements are to be
  87582. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87583. * appended.
  87584. * @param decl The declaration to export.
  87585. */
  87586. function appendExportsOfDeclaration(statements, decl) {
  87587. var name = ts.getDeclarationName(decl);
  87588. var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
  87589. if (exportSpecifiers) {
  87590. for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
  87591. var exportSpecifier = exportSpecifiers_1[_i];
  87592. statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name);
  87593. }
  87594. }
  87595. return statements;
  87596. }
  87597. /**
  87598. * Appends the down-level representation of an export to a statement list, returning the
  87599. * statement list.
  87600. *
  87601. * @param statements A statement list to which the down-level export statements are to be
  87602. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  87603. * appended.
  87604. * @param exportName The name of the export.
  87605. * @param expression The expression to export.
  87606. * @param location The location to use for source maps and comments for the export.
  87607. * @param allowComments Whether to allow comments on the export.
  87608. */
  87609. function appendExportStatement(statements, exportName, expression, location, allowComments) {
  87610. statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments));
  87611. return statements;
  87612. }
  87613. function createUnderscoreUnderscoreESModule() {
  87614. var statement;
  87615. if (languageVersion === 0 /* ES3 */) {
  87616. statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
  87617. }
  87618. else {
  87619. statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
  87620. /*typeArguments*/ undefined, [
  87621. ts.createIdentifier("exports"),
  87622. ts.createLiteral("__esModule"),
  87623. ts.createObjectLiteral([
  87624. ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
  87625. ])
  87626. ]));
  87627. }
  87628. ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
  87629. return statement;
  87630. }
  87631. /**
  87632. * Creates a call to the current file's export function to export a value.
  87633. *
  87634. * @param name The bound name of the export.
  87635. * @param value The exported value.
  87636. * @param location The location to use for source maps and comments for the export.
  87637. * @param allowComments An optional value indicating whether to emit comments for the statement.
  87638. */
  87639. function createExportStatement(name, value, location, allowComments) {
  87640. var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location);
  87641. ts.startOnNewLine(statement);
  87642. if (!allowComments) {
  87643. ts.setEmitFlags(statement, 1536 /* NoComments */);
  87644. }
  87645. return statement;
  87646. }
  87647. /**
  87648. * Creates a call to the current file's export function to export a value.
  87649. *
  87650. * @param name The bound name of the export.
  87651. * @param value The exported value.
  87652. * @param location The location to use for source maps and comments for the export.
  87653. */
  87654. function createExportExpression(name, value, location) {
  87655. return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
  87656. }
  87657. //
  87658. // Modifier Visitors
  87659. //
  87660. /**
  87661. * Visit nodes to elide module-specific modifiers.
  87662. *
  87663. * @param node The node to visit.
  87664. */
  87665. function modifierVisitor(node) {
  87666. // Elide module-specific modifiers.
  87667. switch (node.kind) {
  87668. case 89 /* ExportKeyword */:
  87669. case 84 /* DefaultKeyword */:
  87670. return undefined;
  87671. }
  87672. return node;
  87673. }
  87674. //
  87675. // Emit Notification
  87676. //
  87677. /**
  87678. * Hook for node emit notifications.
  87679. *
  87680. * @param hint A hint as to the intended usage of the node.
  87681. * @param node The node to emit.
  87682. * @param emit A callback used to emit the node in the printer.
  87683. */
  87684. function onEmitNode(hint, node, emitCallback) {
  87685. if (node.kind === 290 /* SourceFile */) {
  87686. currentSourceFile = node;
  87687. currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
  87688. noSubstitution = [];
  87689. previousOnEmitNode(hint, node, emitCallback);
  87690. currentSourceFile = undefined;
  87691. currentModuleInfo = undefined;
  87692. noSubstitution = undefined;
  87693. }
  87694. else {
  87695. previousOnEmitNode(hint, node, emitCallback);
  87696. }
  87697. }
  87698. //
  87699. // Substitutions
  87700. //
  87701. /**
  87702. * Hooks node substitutions.
  87703. *
  87704. * @param hint A hint as to the intended usage of the node.
  87705. * @param node The node to substitute.
  87706. */
  87707. function onSubstituteNode(hint, node) {
  87708. node = previousOnSubstituteNode(hint, node);
  87709. if (node.id && noSubstitution[node.id]) {
  87710. return node;
  87711. }
  87712. if (hint === 1 /* Expression */) {
  87713. return substituteExpression(node);
  87714. }
  87715. else if (ts.isShorthandPropertyAssignment(node)) {
  87716. return substituteShorthandPropertyAssignment(node);
  87717. }
  87718. return node;
  87719. }
  87720. /**
  87721. * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
  87722. * or exported symbol.
  87723. *
  87724. * @param node The node to substitute.
  87725. */
  87726. function substituteShorthandPropertyAssignment(node) {
  87727. var name = node.name;
  87728. var exportedOrImportedName = substituteExpressionIdentifier(name);
  87729. if (exportedOrImportedName !== name) {
  87730. // A shorthand property with an assignment initializer is probably part of a
  87731. // destructuring assignment
  87732. if (node.objectAssignmentInitializer) {
  87733. var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
  87734. return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
  87735. }
  87736. return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
  87737. }
  87738. return node;
  87739. }
  87740. /**
  87741. * Substitution for an Expression that may contain an imported or exported symbol.
  87742. *
  87743. * @param node The node to substitute.
  87744. */
  87745. function substituteExpression(node) {
  87746. switch (node.kind) {
  87747. case 75 /* Identifier */:
  87748. return substituteExpressionIdentifier(node);
  87749. case 209 /* BinaryExpression */:
  87750. return substituteBinaryExpression(node);
  87751. case 208 /* PostfixUnaryExpression */:
  87752. case 207 /* PrefixUnaryExpression */:
  87753. return substituteUnaryExpression(node);
  87754. }
  87755. return node;
  87756. }
  87757. /**
  87758. * Substitution for an Identifier expression that may contain an imported or exported
  87759. * symbol.
  87760. *
  87761. * @param node The node to substitute.
  87762. */
  87763. function substituteExpressionIdentifier(node) {
  87764. if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
  87765. var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
  87766. if (externalHelpersModuleName) {
  87767. return ts.createPropertyAccess(externalHelpersModuleName, node);
  87768. }
  87769. return node;
  87770. }
  87771. if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
  87772. var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
  87773. if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
  87774. return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
  87775. /*location*/ node);
  87776. }
  87777. var importDeclaration = resolver.getReferencedImportDeclaration(node);
  87778. if (importDeclaration) {
  87779. if (ts.isImportClause(importDeclaration)) {
  87780. return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")),
  87781. /*location*/ node);
  87782. }
  87783. else if (ts.isImportSpecifier(importDeclaration)) {
  87784. var name = importDeclaration.propertyName || importDeclaration.name;
  87785. return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)),
  87786. /*location*/ node);
  87787. }
  87788. }
  87789. }
  87790. return node;
  87791. }
  87792. /**
  87793. * Substitution for a BinaryExpression that may contain an imported or exported symbol.
  87794. *
  87795. * @param node The node to substitute.
  87796. */
  87797. function substituteBinaryExpression(node) {
  87798. // When we see an assignment expression whose left-hand side is an exported symbol,
  87799. // we should ensure all exports of that symbol are updated with the correct value.
  87800. //
  87801. // - We do not substitute generated identifiers for any reason.
  87802. // - We do not substitute identifiers tagged with the LocalName flag.
  87803. // - We do not substitute identifiers that were originally the name of an enum or
  87804. // namespace due to how they are transformed in TypeScript.
  87805. // - We only substitute identifiers that are exported at the top level.
  87806. if (ts.isAssignmentOperator(node.operatorToken.kind)
  87807. && ts.isIdentifier(node.left)
  87808. && !ts.isGeneratedIdentifier(node.left)
  87809. && !ts.isLocalName(node.left)
  87810. && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
  87811. var exportedNames = getExports(node.left);
  87812. if (exportedNames) {
  87813. // For each additional export of the declaration, apply an export assignment.
  87814. var expression = node;
  87815. for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
  87816. var exportName = exportedNames_2[_i];
  87817. // Mark the node to prevent triggering this rule again.
  87818. noSubstitution[ts.getNodeId(expression)] = true;
  87819. expression = createExportExpression(exportName, expression, /*location*/ node);
  87820. }
  87821. return expression;
  87822. }
  87823. }
  87824. return node;
  87825. }
  87826. /**
  87827. * Substitution for a UnaryExpression that may contain an imported or exported symbol.
  87828. *
  87829. * @param node The node to substitute.
  87830. */
  87831. function substituteUnaryExpression(node) {
  87832. // When we see a prefix or postfix increment expression whose operand is an exported
  87833. // symbol, we should ensure all exports of that symbol are updated with the correct
  87834. // value.
  87835. //
  87836. // - We do not substitute generated identifiers for any reason.
  87837. // - We do not substitute identifiers tagged with the LocalName flag.
  87838. // - We do not substitute identifiers that were originally the name of an enum or
  87839. // namespace due to how they are transformed in TypeScript.
  87840. // - We only substitute identifiers that are exported at the top level.
  87841. if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
  87842. && ts.isIdentifier(node.operand)
  87843. && !ts.isGeneratedIdentifier(node.operand)
  87844. && !ts.isLocalName(node.operand)
  87845. && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
  87846. var exportedNames = getExports(node.operand);
  87847. if (exportedNames) {
  87848. var expression = node.kind === 208 /* PostfixUnaryExpression */
  87849. ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)),
  87850. /*location*/ node)
  87851. : node;
  87852. for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
  87853. var exportName = exportedNames_3[_i];
  87854. // Mark the node to prevent triggering this rule again.
  87855. noSubstitution[ts.getNodeId(expression)] = true;
  87856. expression = createExportExpression(exportName, expression);
  87857. }
  87858. return expression;
  87859. }
  87860. }
  87861. return node;
  87862. }
  87863. /**
  87864. * Gets the additional exports of a name.
  87865. *
  87866. * @param name The name.
  87867. */
  87868. function getExports(name) {
  87869. if (!ts.isGeneratedIdentifier(name)) {
  87870. var valueDeclaration = resolver.getReferencedImportDeclaration(name)
  87871. || resolver.getReferencedValueDeclaration(name);
  87872. if (valueDeclaration) {
  87873. return currentModuleInfo
  87874. && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
  87875. }
  87876. }
  87877. }
  87878. }
  87879. ts.transformModule = transformModule;
  87880. // emit output for the __export helper function
  87881. var exportStarHelper = {
  87882. name: "typescript:export-star",
  87883. scoped: true,
  87884. text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }"
  87885. };
  87886. function createExportStarHelper(context, module) {
  87887. var compilerOptions = context.getCompilerOptions();
  87888. return compilerOptions.importHelpers
  87889. ? ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")])
  87890. : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]);
  87891. }
  87892. // emit helper for dynamic import
  87893. var dynamicImportUMDHelper = {
  87894. name: "typescript:dynamicimport-sync-require",
  87895. scoped: true,
  87896. text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
  87897. };
  87898. // emit helper for `import * as Name from "foo"`
  87899. ts.importStarHelper = {
  87900. name: "typescript:commonjsimportstar",
  87901. importName: "__importStar",
  87902. scoped: false,
  87903. text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
  87904. };
  87905. // emit helper for `import Name from "foo"`
  87906. ts.importDefaultHelper = {
  87907. name: "typescript:commonjsimportdefault",
  87908. importName: "__importDefault",
  87909. scoped: false,
  87910. text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
  87911. };
  87912. })(ts || (ts = {}));
  87913. /*@internal*/
  87914. var ts;
  87915. (function (ts) {
  87916. function transformSystemModule(context) {
  87917. var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
  87918. var compilerOptions = context.getCompilerOptions();
  87919. var resolver = context.getEmitResolver();
  87920. var host = context.getEmitHost();
  87921. var previousOnSubstituteNode = context.onSubstituteNode;
  87922. var previousOnEmitNode = context.onEmitNode;
  87923. context.onSubstituteNode = onSubstituteNode;
  87924. context.onEmitNode = onEmitNode;
  87925. context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
  87926. context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
  87927. context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
  87928. context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
  87929. context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
  87930. context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
  87931. context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
  87932. var moduleInfoMap = []; // The ExternalModuleInfo for each file.
  87933. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
  87934. var exportFunctionsMap = []; // The export function associated with a source file.
  87935. var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
  87936. var contextObjectMap = []; // The context object associated with a source file.
  87937. var currentSourceFile; // The current file.
  87938. var moduleInfo; // ExternalModuleInfo for the current file.
  87939. var exportFunction; // The export function for the current file.
  87940. var contextObject; // The context object for the current file.
  87941. var hoistedStatements;
  87942. var enclosingBlockScopedContainer;
  87943. var noSubstitution; // Set of nodes for which substitution rules should be ignored.
  87944. return ts.chainBundle(transformSourceFile);
  87945. /**
  87946. * Transforms the module aspects of a SourceFile.
  87947. *
  87948. * @param node The SourceFile node.
  87949. */
  87950. function transformSourceFile(node) {
  87951. if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
  87952. return node;
  87953. }
  87954. var id = ts.getOriginalNodeId(node);
  87955. currentSourceFile = node;
  87956. enclosingBlockScopedContainer = node;
  87957. // System modules have the following shape:
  87958. //
  87959. // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
  87960. //
  87961. // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
  87962. // is used to publish exported values. 'exports' returns its 'value' argument so in
  87963. // most cases expressions that mutate exported values can be rewritten as:
  87964. //
  87965. // expr -> exports('name', expr)
  87966. //
  87967. // The only exception in this rule is postfix unary operators,
  87968. // see comment to 'substitutePostfixUnaryExpression' for more details
  87969. // Collect information about the external module and dependency groups.
  87970. moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
  87971. // Make sure that the name of the 'exports' function does not conflict with
  87972. // existing identifiers.
  87973. exportFunction = ts.createUniqueName("exports");
  87974. exportFunctionsMap[id] = exportFunction;
  87975. contextObject = contextObjectMap[id] = ts.createUniqueName("context");
  87976. // Add the body of the module.
  87977. var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
  87978. var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
  87979. var moduleBodyFunction = ts.createFunctionExpression(
  87980. /*modifiers*/ undefined,
  87981. /*asteriskToken*/ undefined,
  87982. /*name*/ undefined,
  87983. /*typeParameters*/ undefined, [
  87984. ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
  87985. ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
  87986. ],
  87987. /*type*/ undefined, moduleBodyBlock);
  87988. // Write the call to `System.register`
  87989. // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
  87990. // So the helper will be emit at the correct position instead of at the top of the source-file
  87991. var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
  87992. var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
  87993. var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
  87994. ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"),
  87995. /*typeArguments*/ undefined, moduleName
  87996. ? [moduleName, dependencies, moduleBodyFunction]
  87997. : [dependencies, moduleBodyFunction]))
  87998. ]), node.statements)), 1024 /* NoTrailingComments */);
  87999. if (!(compilerOptions.outFile || compilerOptions.out)) {
  88000. ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
  88001. }
  88002. if (noSubstitution) {
  88003. noSubstitutionMap[id] = noSubstitution;
  88004. noSubstitution = undefined;
  88005. }
  88006. currentSourceFile = undefined;
  88007. moduleInfo = undefined;
  88008. exportFunction = undefined;
  88009. contextObject = undefined;
  88010. hoistedStatements = undefined;
  88011. enclosingBlockScopedContainer = undefined;
  88012. return ts.aggregateTransformFlags(updated);
  88013. }
  88014. /**
  88015. * Collects the dependency groups for this files imports.
  88016. *
  88017. * @param externalImports The imports for the file.
  88018. */
  88019. function collectDependencyGroups(externalImports) {
  88020. var groupIndices = ts.createMap();
  88021. var dependencyGroups = [];
  88022. for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
  88023. var externalImport = externalImports_1[_i];
  88024. var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
  88025. if (externalModuleName) {
  88026. var text = externalModuleName.text;
  88027. var groupIndex = groupIndices.get(text);
  88028. if (groupIndex !== undefined) {
  88029. // deduplicate/group entries in dependency list by the dependency name
  88030. dependencyGroups[groupIndex].externalImports.push(externalImport);
  88031. }
  88032. else {
  88033. groupIndices.set(text, dependencyGroups.length);
  88034. dependencyGroups.push({
  88035. name: externalModuleName,
  88036. externalImports: [externalImport]
  88037. });
  88038. }
  88039. }
  88040. }
  88041. return dependencyGroups;
  88042. }
  88043. /**
  88044. * Adds the statements for the module body function for the source file.
  88045. *
  88046. * @param node The source file for the module.
  88047. * @param dependencyGroups The grouped dependencies of the module.
  88048. */
  88049. function createSystemModuleBody(node, dependencyGroups) {
  88050. // Shape of the body in system modules:
  88051. //
  88052. // function (exports) {
  88053. // <list of local aliases for imports>
  88054. // <hoisted variable declarations>
  88055. // <hoisted function declarations>
  88056. // return {
  88057. // setters: [
  88058. // <list of setter function for imports>
  88059. // ],
  88060. // execute: function() {
  88061. // <module statements>
  88062. // }
  88063. // }
  88064. // <temp declarations>
  88065. // }
  88066. //
  88067. // i.e:
  88068. //
  88069. // import {x} from 'file1'
  88070. // var y = 1;
  88071. // export function foo() { return y + x(); }
  88072. // console.log(y);
  88073. //
  88074. // Will be transformed to:
  88075. //
  88076. // function(exports) {
  88077. // function foo() { return y + file_1.x(); }
  88078. // exports("foo", foo);
  88079. // var file_1, y;
  88080. // return {
  88081. // setters: [
  88082. // function(v) { file_1 = v }
  88083. // ],
  88084. // execute(): function() {
  88085. // y = 1;
  88086. // console.log(y);
  88087. // }
  88088. // };
  88089. // }
  88090. var statements = [];
  88091. // We start a new lexical environment in this function body, but *not* in the
  88092. // body of the execute function. This allows us to emit temporary declarations
  88093. // only in the outer module body and not in the inner one.
  88094. startLexicalEnvironment();
  88095. // Add any prologue directives.
  88096. var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
  88097. var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
  88098. // var __moduleName = context_1 && context_1.id;
  88099. statements.push(ts.createVariableStatement(
  88100. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  88101. ts.createVariableDeclaration("__moduleName",
  88102. /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
  88103. ])));
  88104. // Visit the synthetic external helpers import declaration if present
  88105. ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
  88106. // Visit the statements of the source file, emitting any transformations into
  88107. // the `executeStatements` array. We do this *before* we fill the `setters` array
  88108. // as we both emit transformations as well as aggregate some data used when creating
  88109. // setters. This allows us to reduce the number of times we need to loop through the
  88110. // statements of the source file.
  88111. var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
  88112. // Emit early exports for function declarations.
  88113. ts.addRange(statements, hoistedStatements);
  88114. // We emit hoisted variables early to align roughly with our previous emit output.
  88115. // Two key differences in this approach are:
  88116. // - Temporary variables will appear at the top rather than at the bottom of the file
  88117. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
  88118. var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
  88119. var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
  88120. ts.createModifiersFromModifierFlags(256 /* Async */) :
  88121. undefined;
  88122. var moduleObject = ts.createObjectLiteral([
  88123. ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
  88124. ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers,
  88125. /*asteriskToken*/ undefined,
  88126. /*name*/ undefined,
  88127. /*typeParameters*/ undefined,
  88128. /*parameters*/ [],
  88129. /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
  88130. ]);
  88131. moduleObject.multiLine = true;
  88132. statements.push(ts.createReturn(moduleObject));
  88133. return ts.createBlock(statements, /*multiLine*/ true);
  88134. }
  88135. /**
  88136. * Adds an exportStar function to a statement list if it is needed for the file.
  88137. *
  88138. * @param statements A statement list.
  88139. */
  88140. function addExportStarIfNeeded(statements) {
  88141. if (!moduleInfo.hasExportStarsToExportValues) {
  88142. return;
  88143. }
  88144. // when resolving exports local exported entries/indirect exported entries in the module
  88145. // should always win over entries with similar names that were added via star exports
  88146. // to support this we store names of local/indirect exported entries in a set.
  88147. // this set is used to filter names brought by star expors.
  88148. // local names set should only be added if we have anything exported
  88149. if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
  88150. // no exported declarations (export var ...) or export specifiers (export {x})
  88151. // check if we have any non star export declarations.
  88152. var hasExportDeclarationWithExportClause = false;
  88153. for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
  88154. var externalImport = _a[_i];
  88155. if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
  88156. hasExportDeclarationWithExportClause = true;
  88157. break;
  88158. }
  88159. }
  88160. if (!hasExportDeclarationWithExportClause) {
  88161. // we still need to emit exportStar helper
  88162. var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
  88163. statements.push(exportStarFunction_1);
  88164. return exportStarFunction_1.name;
  88165. }
  88166. }
  88167. var exportedNames = [];
  88168. if (moduleInfo.exportedNames) {
  88169. for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
  88170. var exportedLocalName = _c[_b];
  88171. if (exportedLocalName.escapedText === "default") {
  88172. continue;
  88173. }
  88174. // write name of exported declaration, i.e 'export var x...'
  88175. exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
  88176. }
  88177. }
  88178. for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
  88179. var externalImport = _e[_d];
  88180. if (externalImport.kind !== 260 /* ExportDeclaration */) {
  88181. continue;
  88182. }
  88183. if (!externalImport.exportClause) {
  88184. // export * from ...
  88185. continue;
  88186. }
  88187. if (ts.isNamedExports(externalImport.exportClause)) {
  88188. for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
  88189. var element = _g[_f];
  88190. // write name of indirectly exported entry, i.e. 'export {x} from ...'
  88191. exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
  88192. }
  88193. }
  88194. else {
  88195. exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
  88196. }
  88197. }
  88198. var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
  88199. statements.push(ts.createVariableStatement(
  88200. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  88201. ts.createVariableDeclaration(exportedNamesStorageRef,
  88202. /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
  88203. ])));
  88204. var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
  88205. statements.push(exportStarFunction);
  88206. return exportStarFunction.name;
  88207. }
  88208. /**
  88209. * Creates an exportStar function for the file, with an optional set of excluded local
  88210. * names.
  88211. *
  88212. * @param localNames An optional reference to an object containing a set of excluded local
  88213. * names.
  88214. */
  88215. function createExportStarFunction(localNames) {
  88216. var exportStarFunction = ts.createUniqueName("exportStar");
  88217. var m = ts.createIdentifier("m");
  88218. var n = ts.createIdentifier("n");
  88219. var exports = ts.createIdentifier("exports");
  88220. var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
  88221. if (localNames) {
  88222. condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"),
  88223. /*typeArguments*/ undefined, [n])));
  88224. }
  88225. return ts.createFunctionDeclaration(
  88226. /*decorators*/ undefined,
  88227. /*modifiers*/ undefined,
  88228. /*asteriskToken*/ undefined, exportStarFunction,
  88229. /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)],
  88230. /*type*/ undefined, ts.createBlock([
  88231. ts.createVariableStatement(
  88232. /*modifiers*/ undefined, ts.createVariableDeclarationList([
  88233. ts.createVariableDeclaration(exports,
  88234. /*type*/ undefined, ts.createObjectLiteral([]))
  88235. ])),
  88236. ts.createForIn(ts.createVariableDeclarationList([
  88237. ts.createVariableDeclaration(n, /*type*/ undefined)
  88238. ]), m, ts.createBlock([
  88239. ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
  88240. ])),
  88241. ts.createExpressionStatement(ts.createCall(exportFunction,
  88242. /*typeArguments*/ undefined, [exports]))
  88243. ], /*multiline*/ true));
  88244. }
  88245. /**
  88246. * Creates an array setter callbacks for each dependency group.
  88247. *
  88248. * @param exportStarFunction A reference to an exportStarFunction for the file.
  88249. * @param dependencyGroups An array of grouped dependencies.
  88250. */
  88251. function createSettersArray(exportStarFunction, dependencyGroups) {
  88252. var setters = [];
  88253. for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
  88254. var group_2 = dependencyGroups_1[_i];
  88255. // derive a unique name for parameter from the first named entry in the group
  88256. var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
  88257. var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
  88258. var statements = [];
  88259. for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
  88260. var entry = _b[_a];
  88261. var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
  88262. switch (entry.kind) {
  88263. case 254 /* ImportDeclaration */:
  88264. if (!entry.importClause) {
  88265. // 'import "..."' case
  88266. // module is imported only for side-effects, no emit required
  88267. break;
  88268. }
  88269. // falls through
  88270. case 253 /* ImportEqualsDeclaration */:
  88271. ts.Debug.assert(importVariableName !== undefined);
  88272. // save import into the local
  88273. statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
  88274. break;
  88275. case 260 /* ExportDeclaration */:
  88276. ts.Debug.assert(importVariableName !== undefined);
  88277. if (entry.exportClause) {
  88278. if (ts.isNamedExports(entry.exportClause)) {
  88279. // export {a, b as c} from 'foo'
  88280. //
  88281. // emit as:
  88282. //
  88283. // exports_({
  88284. // "a": _["a"],
  88285. // "c": _["b"]
  88286. // });
  88287. var properties = [];
  88288. for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
  88289. var e = _d[_c];
  88290. properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
  88291. }
  88292. statements.push(ts.createExpressionStatement(ts.createCall(exportFunction,
  88293. /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
  88294. }
  88295. else {
  88296. statements.push(ts.createExpressionStatement(ts.createCall(exportFunction,
  88297. /*typeArguments*/ undefined, [
  88298. ts.createLiteral(ts.idText(entry.exportClause.name)),
  88299. parameterName
  88300. ])));
  88301. }
  88302. }
  88303. else {
  88304. // export * from 'foo'
  88305. //
  88306. // emit as:
  88307. //
  88308. // exportStar(foo_1_1);
  88309. statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction,
  88310. /*typeArguments*/ undefined, [parameterName])));
  88311. }
  88312. break;
  88313. }
  88314. }
  88315. setters.push(ts.createFunctionExpression(
  88316. /*modifiers*/ undefined,
  88317. /*asteriskToken*/ undefined,
  88318. /*name*/ undefined,
  88319. /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
  88320. /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
  88321. }
  88322. return ts.createArrayLiteral(setters, /*multiLine*/ true);
  88323. }
  88324. //
  88325. // Top-level Source Element Visitors
  88326. //
  88327. /**
  88328. * Visit source elements at the top-level of a module.
  88329. *
  88330. * @param node The node to visit.
  88331. */
  88332. function sourceElementVisitor(node) {
  88333. switch (node.kind) {
  88334. case 254 /* ImportDeclaration */:
  88335. return visitImportDeclaration(node);
  88336. case 253 /* ImportEqualsDeclaration */:
  88337. return visitImportEqualsDeclaration(node);
  88338. case 260 /* ExportDeclaration */:
  88339. return visitExportDeclaration(node);
  88340. case 259 /* ExportAssignment */:
  88341. return visitExportAssignment(node);
  88342. default:
  88343. return nestedElementVisitor(node);
  88344. }
  88345. }
  88346. /**
  88347. * Visits an ImportDeclaration node.
  88348. *
  88349. * @param node The node to visit.
  88350. */
  88351. function visitImportDeclaration(node) {
  88352. var statements;
  88353. if (node.importClause) {
  88354. hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
  88355. }
  88356. if (hasAssociatedEndOfDeclarationMarker(node)) {
  88357. // Defer exports until we encounter an EndOfDeclarationMarker node
  88358. var id = ts.getOriginalNodeId(node);
  88359. deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
  88360. }
  88361. else {
  88362. statements = appendExportsOfImportDeclaration(statements, node);
  88363. }
  88364. return ts.singleOrMany(statements);
  88365. }
  88366. function visitExportDeclaration(node) {
  88367. ts.Debug.assertDefined(node);
  88368. return undefined;
  88369. }
  88370. /**
  88371. * Visits an ImportEqualsDeclaration node.
  88372. *
  88373. * @param node The node to visit.
  88374. */
  88375. function visitImportEqualsDeclaration(node) {
  88376. ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
  88377. var statements;
  88378. hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
  88379. if (hasAssociatedEndOfDeclarationMarker(node)) {
  88380. // Defer exports until we encounter an EndOfDeclarationMarker node
  88381. var id = ts.getOriginalNodeId(node);
  88382. deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
  88383. }
  88384. else {
  88385. statements = appendExportsOfImportEqualsDeclaration(statements, node);
  88386. }
  88387. return ts.singleOrMany(statements);
  88388. }
  88389. /**
  88390. * Visits an ExportAssignment node.
  88391. *
  88392. * @param node The node to visit.
  88393. */
  88394. function visitExportAssignment(node) {
  88395. if (node.isExportEquals) {
  88396. // Elide `export=` as it is illegal in a SystemJS module.
  88397. return undefined;
  88398. }
  88399. var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
  88400. var original = node.original;
  88401. if (original && hasAssociatedEndOfDeclarationMarker(original)) {
  88402. // Defer exports until we encounter an EndOfDeclarationMarker node
  88403. var id = ts.getOriginalNodeId(node);
  88404. deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
  88405. }
  88406. else {
  88407. return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
  88408. }
  88409. }
  88410. /**
  88411. * Visits a FunctionDeclaration, hoisting it to the outer module body function.
  88412. *
  88413. * @param node The node to visit.
  88414. */
  88415. function visitFunctionDeclaration(node) {
  88416. if (ts.hasModifier(node, 1 /* Export */)) {
  88417. hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
  88418. /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration),
  88419. /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
  88420. }
  88421. else {
  88422. hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
  88423. }
  88424. if (hasAssociatedEndOfDeclarationMarker(node)) {
  88425. // Defer exports until we encounter an EndOfDeclarationMarker node
  88426. var id = ts.getOriginalNodeId(node);
  88427. deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
  88428. }
  88429. else {
  88430. hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
  88431. }
  88432. return undefined;
  88433. }
  88434. /**
  88435. * Visits a ClassDeclaration, hoisting its name to the outer module body function.
  88436. *
  88437. * @param node The node to visit.
  88438. */
  88439. function visitClassDeclaration(node) {
  88440. var statements;
  88441. // Hoist the name of the class declaration to the outer module body function.
  88442. var name = ts.getLocalName(node);
  88443. hoistVariableDeclaration(name);
  88444. // Rewrite the class declaration into an assignment of a class expression.
  88445. statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
  88446. /*modifiers*/ undefined, node.name,
  88447. /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
  88448. if (hasAssociatedEndOfDeclarationMarker(node)) {
  88449. // Defer exports until we encounter an EndOfDeclarationMarker node
  88450. var id = ts.getOriginalNodeId(node);
  88451. deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
  88452. }
  88453. else {
  88454. statements = appendExportsOfHoistedDeclaration(statements, node);
  88455. }
  88456. return ts.singleOrMany(statements);
  88457. }
  88458. /**
  88459. * Visits a variable statement, hoisting declared names to the top-level module body.
  88460. * Each declaration is rewritten into an assignment expression.
  88461. *
  88462. * @param node The node to visit.
  88463. */
  88464. function visitVariableStatement(node) {
  88465. if (!shouldHoistVariableDeclarationList(node.declarationList)) {
  88466. return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
  88467. }
  88468. var expressions;
  88469. var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
  88470. var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
  88471. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  88472. var variable = _a[_i];
  88473. if (variable.initializer) {
  88474. expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
  88475. }
  88476. else {
  88477. hoistBindingElement(variable);
  88478. }
  88479. }
  88480. var statements;
  88481. if (expressions) {
  88482. statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
  88483. }
  88484. if (isMarkedDeclaration) {
  88485. // Defer exports until we encounter an EndOfDeclarationMarker node
  88486. var id = ts.getOriginalNodeId(node);
  88487. deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
  88488. }
  88489. else {
  88490. statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
  88491. }
  88492. return ts.singleOrMany(statements);
  88493. }
  88494. /**
  88495. * Hoists the declared names of a VariableDeclaration or BindingElement.
  88496. *
  88497. * @param node The declaration to hoist.
  88498. */
  88499. function hoistBindingElement(node) {
  88500. if (ts.isBindingPattern(node.name)) {
  88501. for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
  88502. var element = _a[_i];
  88503. if (!ts.isOmittedExpression(element)) {
  88504. hoistBindingElement(element);
  88505. }
  88506. }
  88507. }
  88508. else {
  88509. hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
  88510. }
  88511. }
  88512. /**
  88513. * Determines whether a VariableDeclarationList should be hoisted.
  88514. *
  88515. * @param node The node to test.
  88516. */
  88517. function shouldHoistVariableDeclarationList(node) {
  88518. // hoist only non-block scoped declarations or block scoped declarations parented by source file
  88519. return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
  88520. && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
  88521. || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
  88522. }
  88523. /**
  88524. * Transform an initialized variable declaration into an expression.
  88525. *
  88526. * @param node The node to transform.
  88527. * @param isExportedDeclaration A value indicating whether the variable is exported.
  88528. */
  88529. function transformInitializedVariable(node, isExportedDeclaration) {
  88530. var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
  88531. return ts.isBindingPattern(node.name)
  88532. ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */,
  88533. /*needsValue*/ false, createAssignment)
  88534. : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
  88535. }
  88536. /**
  88537. * Creates an assignment expression for an exported variable declaration.
  88538. *
  88539. * @param name The name of the variable.
  88540. * @param value The value of the variable's initializer.
  88541. * @param location The source map location for the assignment.
  88542. */
  88543. function createExportedVariableAssignment(name, value, location) {
  88544. return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
  88545. }
  88546. /**
  88547. * Creates an assignment expression for a non-exported variable declaration.
  88548. *
  88549. * @param name The name of the variable.
  88550. * @param value The value of the variable's initializer.
  88551. * @param location The source map location for the assignment.
  88552. */
  88553. function createNonExportedVariableAssignment(name, value, location) {
  88554. return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
  88555. }
  88556. /**
  88557. * Creates an assignment expression for a variable declaration.
  88558. *
  88559. * @param name The name of the variable.
  88560. * @param value The value of the variable's initializer.
  88561. * @param location The source map location for the assignment.
  88562. * @param isExportedDeclaration A value indicating whether the variable is exported.
  88563. */
  88564. function createVariableAssignment(name, value, location, isExportedDeclaration) {
  88565. hoistVariableDeclaration(ts.getSynthesizedClone(name));
  88566. return isExportedDeclaration
  88567. ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
  88568. : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
  88569. }
  88570. /**
  88571. * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
  88572. * and transformed declaration.
  88573. *
  88574. * @param node The node to visit.
  88575. */
  88576. function visitMergeDeclarationMarker(node) {
  88577. // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
  88578. // declaration we do not emit a leading variable declaration. To preserve the
  88579. // begin/end semantics of the declararation and to properly handle exports
  88580. // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
  88581. //
  88582. // To balance the declaration, we defer the exports of the elided variable
  88583. // statement until we visit this declaration's `EndOfDeclarationMarker`.
  88584. if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
  88585. var id = ts.getOriginalNodeId(node);
  88586. var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
  88587. deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
  88588. }
  88589. return node;
  88590. }
  88591. /**
  88592. * Determines whether a node has an associated EndOfDeclarationMarker.
  88593. *
  88594. * @param node The node to test.
  88595. */
  88596. function hasAssociatedEndOfDeclarationMarker(node) {
  88597. return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
  88598. }
  88599. /**
  88600. * Visits a DeclarationMarker used as a placeholder for the end of a transformed
  88601. * declaration.
  88602. *
  88603. * @param node The node to visit.
  88604. */
  88605. function visitEndOfDeclarationMarker(node) {
  88606. // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
  88607. // end of the transformed declaration. We use this marker to emit any deferred exports
  88608. // of the declaration.
  88609. var id = ts.getOriginalNodeId(node);
  88610. var statements = deferredExports[id];
  88611. if (statements) {
  88612. delete deferredExports[id];
  88613. return ts.append(statements, node);
  88614. }
  88615. else {
  88616. var original = ts.getOriginalNode(node);
  88617. if (ts.isModuleOrEnumDeclaration(original)) {
  88618. return ts.append(appendExportsOfDeclaration(statements, original), node);
  88619. }
  88620. }
  88621. return node;
  88622. }
  88623. /**
  88624. * Appends the exports of an ImportDeclaration to a statement list, returning the
  88625. * statement list.
  88626. *
  88627. * @param statements A statement list to which the down-level export statements are to be
  88628. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88629. * appended.
  88630. * @param decl The declaration whose exports are to be recorded.
  88631. */
  88632. function appendExportsOfImportDeclaration(statements, decl) {
  88633. if (moduleInfo.exportEquals) {
  88634. return statements;
  88635. }
  88636. var importClause = decl.importClause;
  88637. if (!importClause) {
  88638. return statements;
  88639. }
  88640. if (importClause.name) {
  88641. statements = appendExportsOfDeclaration(statements, importClause);
  88642. }
  88643. var namedBindings = importClause.namedBindings;
  88644. if (namedBindings) {
  88645. switch (namedBindings.kind) {
  88646. case 256 /* NamespaceImport */:
  88647. statements = appendExportsOfDeclaration(statements, namedBindings);
  88648. break;
  88649. case 257 /* NamedImports */:
  88650. for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
  88651. var importBinding = _a[_i];
  88652. statements = appendExportsOfDeclaration(statements, importBinding);
  88653. }
  88654. break;
  88655. }
  88656. }
  88657. return statements;
  88658. }
  88659. /**
  88660. * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
  88661. * statement list.
  88662. *
  88663. * @param statements A statement list to which the down-level export statements are to be
  88664. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88665. * appended.
  88666. * @param decl The declaration whose exports are to be recorded.
  88667. */
  88668. function appendExportsOfImportEqualsDeclaration(statements, decl) {
  88669. if (moduleInfo.exportEquals) {
  88670. return statements;
  88671. }
  88672. return appendExportsOfDeclaration(statements, decl);
  88673. }
  88674. /**
  88675. * Appends the exports of a VariableStatement to a statement list, returning the statement
  88676. * list.
  88677. *
  88678. * @param statements A statement list to which the down-level export statements are to be
  88679. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88680. * appended.
  88681. * @param node The VariableStatement whose exports are to be recorded.
  88682. * @param exportSelf A value indicating whether to also export each VariableDeclaration of
  88683. * `nodes` declaration list.
  88684. */
  88685. function appendExportsOfVariableStatement(statements, node, exportSelf) {
  88686. if (moduleInfo.exportEquals) {
  88687. return statements;
  88688. }
  88689. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  88690. var decl = _a[_i];
  88691. if (decl.initializer || exportSelf) {
  88692. statements = appendExportsOfBindingElement(statements, decl, exportSelf);
  88693. }
  88694. }
  88695. return statements;
  88696. }
  88697. /**
  88698. * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
  88699. * returning the statement list.
  88700. *
  88701. * @param statements A statement list to which the down-level export statements are to be
  88702. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88703. * appended.
  88704. * @param decl The declaration whose exports are to be recorded.
  88705. * @param exportSelf A value indicating whether to also export the declaration itself.
  88706. */
  88707. function appendExportsOfBindingElement(statements, decl, exportSelf) {
  88708. if (moduleInfo.exportEquals) {
  88709. return statements;
  88710. }
  88711. if (ts.isBindingPattern(decl.name)) {
  88712. for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
  88713. var element = _a[_i];
  88714. if (!ts.isOmittedExpression(element)) {
  88715. statements = appendExportsOfBindingElement(statements, element, exportSelf);
  88716. }
  88717. }
  88718. }
  88719. else if (!ts.isGeneratedIdentifier(decl.name)) {
  88720. var excludeName = void 0;
  88721. if (exportSelf) {
  88722. statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
  88723. excludeName = ts.idText(decl.name);
  88724. }
  88725. statements = appendExportsOfDeclaration(statements, decl, excludeName);
  88726. }
  88727. return statements;
  88728. }
  88729. /**
  88730. * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
  88731. * returning the statement list.
  88732. *
  88733. * @param statements A statement list to which the down-level export statements are to be
  88734. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88735. * appended.
  88736. * @param decl The declaration whose exports are to be recorded.
  88737. */
  88738. function appendExportsOfHoistedDeclaration(statements, decl) {
  88739. if (moduleInfo.exportEquals) {
  88740. return statements;
  88741. }
  88742. var excludeName;
  88743. if (ts.hasModifier(decl, 1 /* Export */)) {
  88744. var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
  88745. statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
  88746. excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
  88747. }
  88748. if (decl.name) {
  88749. statements = appendExportsOfDeclaration(statements, decl, excludeName);
  88750. }
  88751. return statements;
  88752. }
  88753. /**
  88754. * Appends the exports of a declaration to a statement list, returning the statement list.
  88755. *
  88756. * @param statements A statement list to which the down-level export statements are to be
  88757. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88758. * appended.
  88759. * @param decl The declaration to export.
  88760. * @param excludeName An optional name to exclude from exports.
  88761. */
  88762. function appendExportsOfDeclaration(statements, decl, excludeName) {
  88763. if (moduleInfo.exportEquals) {
  88764. return statements;
  88765. }
  88766. var name = ts.getDeclarationName(decl);
  88767. var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
  88768. if (exportSpecifiers) {
  88769. for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
  88770. var exportSpecifier = exportSpecifiers_2[_i];
  88771. if (exportSpecifier.name.escapedText !== excludeName) {
  88772. statements = appendExportStatement(statements, exportSpecifier.name, name);
  88773. }
  88774. }
  88775. }
  88776. return statements;
  88777. }
  88778. /**
  88779. * Appends the down-level representation of an export to a statement list, returning the
  88780. * statement list.
  88781. *
  88782. * @param statements A statement list to which the down-level export statements are to be
  88783. * appended. If `statements` is `undefined`, a new array is allocated if statements are
  88784. * appended.
  88785. * @param exportName The name of the export.
  88786. * @param expression The expression to export.
  88787. * @param allowComments Whether to allow comments on the export.
  88788. */
  88789. function appendExportStatement(statements, exportName, expression, allowComments) {
  88790. statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
  88791. return statements;
  88792. }
  88793. /**
  88794. * Creates a call to the current file's export function to export a value.
  88795. *
  88796. * @param name The bound name of the export.
  88797. * @param value The exported value.
  88798. * @param allowComments An optional value indicating whether to emit comments for the statement.
  88799. */
  88800. function createExportStatement(name, value, allowComments) {
  88801. var statement = ts.createExpressionStatement(createExportExpression(name, value));
  88802. ts.startOnNewLine(statement);
  88803. if (!allowComments) {
  88804. ts.setEmitFlags(statement, 1536 /* NoComments */);
  88805. }
  88806. return statement;
  88807. }
  88808. /**
  88809. * Creates a call to the current file's export function to export a value.
  88810. *
  88811. * @param name The bound name of the export.
  88812. * @param value The exported value.
  88813. */
  88814. function createExportExpression(name, value) {
  88815. var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
  88816. ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
  88817. return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
  88818. }
  88819. //
  88820. // Top-Level or Nested Source Element Visitors
  88821. //
  88822. /**
  88823. * Visit nested elements at the top-level of a module.
  88824. *
  88825. * @param node The node to visit.
  88826. */
  88827. function nestedElementVisitor(node) {
  88828. switch (node.kind) {
  88829. case 225 /* VariableStatement */:
  88830. return visitVariableStatement(node);
  88831. case 244 /* FunctionDeclaration */:
  88832. return visitFunctionDeclaration(node);
  88833. case 245 /* ClassDeclaration */:
  88834. return visitClassDeclaration(node);
  88835. case 230 /* ForStatement */:
  88836. return visitForStatement(node);
  88837. case 231 /* ForInStatement */:
  88838. return visitForInStatement(node);
  88839. case 232 /* ForOfStatement */:
  88840. return visitForOfStatement(node);
  88841. case 228 /* DoStatement */:
  88842. return visitDoStatement(node);
  88843. case 229 /* WhileStatement */:
  88844. return visitWhileStatement(node);
  88845. case 238 /* LabeledStatement */:
  88846. return visitLabeledStatement(node);
  88847. case 236 /* WithStatement */:
  88848. return visitWithStatement(node);
  88849. case 237 /* SwitchStatement */:
  88850. return visitSwitchStatement(node);
  88851. case 251 /* CaseBlock */:
  88852. return visitCaseBlock(node);
  88853. case 277 /* CaseClause */:
  88854. return visitCaseClause(node);
  88855. case 278 /* DefaultClause */:
  88856. return visitDefaultClause(node);
  88857. case 240 /* TryStatement */:
  88858. return visitTryStatement(node);
  88859. case 280 /* CatchClause */:
  88860. return visitCatchClause(node);
  88861. case 223 /* Block */:
  88862. return visitBlock(node);
  88863. case 327 /* MergeDeclarationMarker */:
  88864. return visitMergeDeclarationMarker(node);
  88865. case 328 /* EndOfDeclarationMarker */:
  88866. return visitEndOfDeclarationMarker(node);
  88867. default:
  88868. return destructuringAndImportCallVisitor(node);
  88869. }
  88870. }
  88871. /**
  88872. * Visits the body of a ForStatement to hoist declarations.
  88873. *
  88874. * @param node The node to visit.
  88875. */
  88876. function visitForStatement(node) {
  88877. var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
  88878. enclosingBlockScopedContainer = node;
  88879. node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
  88880. enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
  88881. return node;
  88882. }
  88883. /**
  88884. * Visits the body of a ForInStatement to hoist declarations.
  88885. *
  88886. * @param node The node to visit.
  88887. */
  88888. function visitForInStatement(node) {
  88889. var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
  88890. enclosingBlockScopedContainer = node;
  88891. node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
  88892. enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
  88893. return node;
  88894. }
  88895. /**
  88896. * Visits the body of a ForOfStatement to hoist declarations.
  88897. *
  88898. * @param node The node to visit.
  88899. */
  88900. function visitForOfStatement(node) {
  88901. var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
  88902. enclosingBlockScopedContainer = node;
  88903. node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
  88904. enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
  88905. return node;
  88906. }
  88907. /**
  88908. * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
  88909. * ForOfStatement.
  88910. *
  88911. * @param node The node to test.
  88912. */
  88913. function shouldHoistForInitializer(node) {
  88914. return ts.isVariableDeclarationList(node)
  88915. && shouldHoistVariableDeclarationList(node);
  88916. }
  88917. /**
  88918. * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
  88919. *
  88920. * @param node The node to visit.
  88921. */
  88922. function visitForInitializer(node) {
  88923. if (shouldHoistForInitializer(node)) {
  88924. var expressions = void 0;
  88925. for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
  88926. var variable = _a[_i];
  88927. expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
  88928. if (!variable.initializer) {
  88929. hoistBindingElement(variable);
  88930. }
  88931. }
  88932. return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
  88933. }
  88934. else {
  88935. return ts.visitEachChild(node, nestedElementVisitor, context);
  88936. }
  88937. }
  88938. /**
  88939. * Visits the body of a DoStatement to hoist declarations.
  88940. *
  88941. * @param node The node to visit.
  88942. */
  88943. function visitDoStatement(node) {
  88944. return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
  88945. }
  88946. /**
  88947. * Visits the body of a WhileStatement to hoist declarations.
  88948. *
  88949. * @param node The node to visit.
  88950. */
  88951. function visitWhileStatement(node) {
  88952. return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
  88953. }
  88954. /**
  88955. * Visits the body of a LabeledStatement to hoist declarations.
  88956. *
  88957. * @param node The node to visit.
  88958. */
  88959. function visitLabeledStatement(node) {
  88960. return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
  88961. }
  88962. /**
  88963. * Visits the body of a WithStatement to hoist declarations.
  88964. *
  88965. * @param node The node to visit.
  88966. */
  88967. function visitWithStatement(node) {
  88968. return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
  88969. }
  88970. /**
  88971. * Visits the body of a SwitchStatement to hoist declarations.
  88972. *
  88973. * @param node The node to visit.
  88974. */
  88975. function visitSwitchStatement(node) {
  88976. return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
  88977. }
  88978. /**
  88979. * Visits the body of a CaseBlock to hoist declarations.
  88980. *
  88981. * @param node The node to visit.
  88982. */
  88983. function visitCaseBlock(node) {
  88984. var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
  88985. enclosingBlockScopedContainer = node;
  88986. node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
  88987. enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
  88988. return node;
  88989. }
  88990. /**
  88991. * Visits the body of a CaseClause to hoist declarations.
  88992. *
  88993. * @param node The node to visit.
  88994. */
  88995. function visitCaseClause(node) {
  88996. return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
  88997. }
  88998. /**
  88999. * Visits the body of a DefaultClause to hoist declarations.
  89000. *
  89001. * @param node The node to visit.
  89002. */
  89003. function visitDefaultClause(node) {
  89004. return ts.visitEachChild(node, nestedElementVisitor, context);
  89005. }
  89006. /**
  89007. * Visits the body of a TryStatement to hoist declarations.
  89008. *
  89009. * @param node The node to visit.
  89010. */
  89011. function visitTryStatement(node) {
  89012. return ts.visitEachChild(node, nestedElementVisitor, context);
  89013. }
  89014. /**
  89015. * Visits the body of a CatchClause to hoist declarations.
  89016. *
  89017. * @param node The node to visit.
  89018. */
  89019. function visitCatchClause(node) {
  89020. var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
  89021. enclosingBlockScopedContainer = node;
  89022. node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
  89023. enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
  89024. return node;
  89025. }
  89026. /**
  89027. * Visits the body of a Block to hoist declarations.
  89028. *
  89029. * @param node The node to visit.
  89030. */
  89031. function visitBlock(node) {
  89032. var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
  89033. enclosingBlockScopedContainer = node;
  89034. node = ts.visitEachChild(node, nestedElementVisitor, context);
  89035. enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
  89036. return node;
  89037. }
  89038. //
  89039. // Destructuring Assignment Visitors
  89040. //
  89041. /**
  89042. * Visit nodes to flatten destructuring assignments to exported symbols.
  89043. *
  89044. * @param node The node to visit.
  89045. */
  89046. function destructuringAndImportCallVisitor(node) {
  89047. if (ts.isDestructuringAssignment(node)) {
  89048. return visitDestructuringAssignment(node);
  89049. }
  89050. else if (ts.isImportCall(node)) {
  89051. return visitImportCallExpression(node);
  89052. }
  89053. else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
  89054. return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
  89055. }
  89056. else {
  89057. return node;
  89058. }
  89059. }
  89060. function visitImportCallExpression(node) {
  89061. // import("./blah")
  89062. // emit as
  89063. // System.register([], function (_export, _context) {
  89064. // return {
  89065. // setters: [],
  89066. // execute: () => {
  89067. // _context.import('./blah');
  89068. // }
  89069. // };
  89070. // });
  89071. return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")),
  89072. /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
  89073. }
  89074. /**
  89075. * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
  89076. *
  89077. * @param node The node to visit.
  89078. */
  89079. function visitDestructuringAssignment(node) {
  89080. if (hasExportedReferenceInDestructuringTarget(node.left)) {
  89081. return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */,
  89082. /*needsValue*/ true);
  89083. }
  89084. return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
  89085. }
  89086. /**
  89087. * Determines whether the target of a destructuring assigment refers to an exported symbol.
  89088. *
  89089. * @param node The destructuring target.
  89090. */
  89091. function hasExportedReferenceInDestructuringTarget(node) {
  89092. if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
  89093. return hasExportedReferenceInDestructuringTarget(node.left);
  89094. }
  89095. else if (ts.isSpreadElement(node)) {
  89096. return hasExportedReferenceInDestructuringTarget(node.expression);
  89097. }
  89098. else if (ts.isObjectLiteralExpression(node)) {
  89099. return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
  89100. }
  89101. else if (ts.isArrayLiteralExpression(node)) {
  89102. return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
  89103. }
  89104. else if (ts.isShorthandPropertyAssignment(node)) {
  89105. return hasExportedReferenceInDestructuringTarget(node.name);
  89106. }
  89107. else if (ts.isPropertyAssignment(node)) {
  89108. return hasExportedReferenceInDestructuringTarget(node.initializer);
  89109. }
  89110. else if (ts.isIdentifier(node)) {
  89111. var container = resolver.getReferencedExportContainer(node);
  89112. return container !== undefined && container.kind === 290 /* SourceFile */;
  89113. }
  89114. else {
  89115. return false;
  89116. }
  89117. }
  89118. //
  89119. // Modifier Visitors
  89120. //
  89121. /**
  89122. * Visit nodes to elide module-specific modifiers.
  89123. *
  89124. * @param node The node to visit.
  89125. */
  89126. function modifierVisitor(node) {
  89127. switch (node.kind) {
  89128. case 89 /* ExportKeyword */:
  89129. case 84 /* DefaultKeyword */:
  89130. return undefined;
  89131. }
  89132. return node;
  89133. }
  89134. //
  89135. // Emit Notification
  89136. //
  89137. /**
  89138. * Hook for node emit notifications.
  89139. *
  89140. * @param hint A hint as to the intended usage of the node.
  89141. * @param node The node to emit.
  89142. * @param emitCallback A callback used to emit the node in the printer.
  89143. */
  89144. function onEmitNode(hint, node, emitCallback) {
  89145. if (node.kind === 290 /* SourceFile */) {
  89146. var id = ts.getOriginalNodeId(node);
  89147. currentSourceFile = node;
  89148. moduleInfo = moduleInfoMap[id];
  89149. exportFunction = exportFunctionsMap[id];
  89150. noSubstitution = noSubstitutionMap[id];
  89151. contextObject = contextObjectMap[id];
  89152. if (noSubstitution) {
  89153. delete noSubstitutionMap[id];
  89154. }
  89155. previousOnEmitNode(hint, node, emitCallback);
  89156. currentSourceFile = undefined;
  89157. moduleInfo = undefined;
  89158. exportFunction = undefined;
  89159. contextObject = undefined;
  89160. noSubstitution = undefined;
  89161. }
  89162. else {
  89163. previousOnEmitNode(hint, node, emitCallback);
  89164. }
  89165. }
  89166. //
  89167. // Substitutions
  89168. //
  89169. /**
  89170. * Hooks node substitutions.
  89171. *
  89172. * @param hint A hint as to the intended usage of the node.
  89173. * @param node The node to substitute.
  89174. */
  89175. function onSubstituteNode(hint, node) {
  89176. node = previousOnSubstituteNode(hint, node);
  89177. if (isSubstitutionPrevented(node)) {
  89178. return node;
  89179. }
  89180. if (hint === 1 /* Expression */) {
  89181. return substituteExpression(node);
  89182. }
  89183. else if (hint === 4 /* Unspecified */) {
  89184. return substituteUnspecified(node);
  89185. }
  89186. return node;
  89187. }
  89188. /**
  89189. * Substitute the node, if necessary.
  89190. *
  89191. * @param node The node to substitute.
  89192. */
  89193. function substituteUnspecified(node) {
  89194. switch (node.kind) {
  89195. case 282 /* ShorthandPropertyAssignment */:
  89196. return substituteShorthandPropertyAssignment(node);
  89197. }
  89198. return node;
  89199. }
  89200. /**
  89201. * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
  89202. *
  89203. * @param node The node to substitute.
  89204. */
  89205. function substituteShorthandPropertyAssignment(node) {
  89206. var name = node.name;
  89207. if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
  89208. var importDeclaration = resolver.getReferencedImportDeclaration(name);
  89209. if (importDeclaration) {
  89210. if (ts.isImportClause(importDeclaration)) {
  89211. return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))),
  89212. /*location*/ node);
  89213. }
  89214. else if (ts.isImportSpecifier(importDeclaration)) {
  89215. return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))),
  89216. /*location*/ node);
  89217. }
  89218. }
  89219. }
  89220. return node;
  89221. }
  89222. /**
  89223. * Substitute the expression, if necessary.
  89224. *
  89225. * @param node The node to substitute.
  89226. */
  89227. function substituteExpression(node) {
  89228. switch (node.kind) {
  89229. case 75 /* Identifier */:
  89230. return substituteExpressionIdentifier(node);
  89231. case 209 /* BinaryExpression */:
  89232. return substituteBinaryExpression(node);
  89233. case 207 /* PrefixUnaryExpression */:
  89234. case 208 /* PostfixUnaryExpression */:
  89235. return substituteUnaryExpression(node);
  89236. case 219 /* MetaProperty */:
  89237. return substituteMetaProperty(node);
  89238. }
  89239. return node;
  89240. }
  89241. /**
  89242. * Substitution for an Identifier expression that may contain an imported or exported symbol.
  89243. *
  89244. * @param node The node to substitute.
  89245. */
  89246. function substituteExpressionIdentifier(node) {
  89247. if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
  89248. var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
  89249. if (externalHelpersModuleName) {
  89250. return ts.createPropertyAccess(externalHelpersModuleName, node);
  89251. }
  89252. return node;
  89253. }
  89254. // When we see an identifier in an expression position that
  89255. // points to an imported symbol, we should substitute a qualified
  89256. // reference to the imported symbol if one is needed.
  89257. //
  89258. // - We do not substitute generated identifiers for any reason.
  89259. // - We do not substitute identifiers tagged with the LocalName flag.
  89260. if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
  89261. var importDeclaration = resolver.getReferencedImportDeclaration(node);
  89262. if (importDeclaration) {
  89263. if (ts.isImportClause(importDeclaration)) {
  89264. return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")),
  89265. /*location*/ node);
  89266. }
  89267. else if (ts.isImportSpecifier(importDeclaration)) {
  89268. return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)),
  89269. /*location*/ node);
  89270. }
  89271. }
  89272. }
  89273. return node;
  89274. }
  89275. /**
  89276. * Substitution for a BinaryExpression that may contain an imported or exported symbol.
  89277. *
  89278. * @param node The node to substitute.
  89279. */
  89280. function substituteBinaryExpression(node) {
  89281. // When we see an assignment expression whose left-hand side is an exported symbol,
  89282. // we should ensure all exports of that symbol are updated with the correct value.
  89283. //
  89284. // - We do not substitute generated identifiers for any reason.
  89285. // - We do not substitute identifiers tagged with the LocalName flag.
  89286. // - We do not substitute identifiers that were originally the name of an enum or
  89287. // namespace due to how they are transformed in TypeScript.
  89288. // - We only substitute identifiers that are exported at the top level.
  89289. if (ts.isAssignmentOperator(node.operatorToken.kind)
  89290. && ts.isIdentifier(node.left)
  89291. && !ts.isGeneratedIdentifier(node.left)
  89292. && !ts.isLocalName(node.left)
  89293. && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
  89294. var exportedNames = getExports(node.left);
  89295. if (exportedNames) {
  89296. // For each additional export of the declaration, apply an export assignment.
  89297. var expression = node;
  89298. for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
  89299. var exportName = exportedNames_4[_i];
  89300. expression = createExportExpression(exportName, preventSubstitution(expression));
  89301. }
  89302. return expression;
  89303. }
  89304. }
  89305. return node;
  89306. }
  89307. /**
  89308. * Substitution for a UnaryExpression that may contain an imported or exported symbol.
  89309. *
  89310. * @param node The node to substitute.
  89311. */
  89312. function substituteUnaryExpression(node) {
  89313. // When we see a prefix or postfix increment expression whose operand is an exported
  89314. // symbol, we should ensure all exports of that symbol are updated with the correct
  89315. // value.
  89316. //
  89317. // - We do not substitute generated identifiers for any reason.
  89318. // - We do not substitute identifiers tagged with the LocalName flag.
  89319. // - We do not substitute identifiers that were originally the name of an enum or
  89320. // namespace due to how they are transformed in TypeScript.
  89321. // - We only substitute identifiers that are exported at the top level.
  89322. if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
  89323. && ts.isIdentifier(node.operand)
  89324. && !ts.isGeneratedIdentifier(node.operand)
  89325. && !ts.isLocalName(node.operand)
  89326. && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
  89327. var exportedNames = getExports(node.operand);
  89328. if (exportedNames) {
  89329. var expression = node.kind === 208 /* PostfixUnaryExpression */
  89330. ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
  89331. : node;
  89332. for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
  89333. var exportName = exportedNames_5[_i];
  89334. expression = createExportExpression(exportName, preventSubstitution(expression));
  89335. }
  89336. if (node.kind === 208 /* PostfixUnaryExpression */) {
  89337. expression = node.operator === 45 /* PlusPlusToken */
  89338. ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
  89339. : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
  89340. }
  89341. return expression;
  89342. }
  89343. }
  89344. return node;
  89345. }
  89346. function substituteMetaProperty(node) {
  89347. if (ts.isImportMeta(node)) {
  89348. return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
  89349. }
  89350. return node;
  89351. }
  89352. /**
  89353. * Gets the exports of a name.
  89354. *
  89355. * @param name The name.
  89356. */
  89357. function getExports(name) {
  89358. var exportedNames;
  89359. if (!ts.isGeneratedIdentifier(name)) {
  89360. var valueDeclaration = resolver.getReferencedImportDeclaration(name)
  89361. || resolver.getReferencedValueDeclaration(name);
  89362. if (valueDeclaration) {
  89363. var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
  89364. if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
  89365. exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
  89366. }
  89367. exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
  89368. }
  89369. }
  89370. return exportedNames;
  89371. }
  89372. /**
  89373. * Prevent substitution of a node for this transformer.
  89374. *
  89375. * @param node The node which should not be substituted.
  89376. */
  89377. function preventSubstitution(node) {
  89378. if (noSubstitution === undefined)
  89379. noSubstitution = [];
  89380. noSubstitution[ts.getNodeId(node)] = true;
  89381. return node;
  89382. }
  89383. /**
  89384. * Determines whether a node should not be substituted.
  89385. *
  89386. * @param node The node to test.
  89387. */
  89388. function isSubstitutionPrevented(node) {
  89389. return noSubstitution && node.id && noSubstitution[node.id];
  89390. }
  89391. }
  89392. ts.transformSystemModule = transformSystemModule;
  89393. })(ts || (ts = {}));
  89394. /*@internal*/
  89395. var ts;
  89396. (function (ts) {
  89397. function transformECMAScriptModule(context) {
  89398. var compilerOptions = context.getCompilerOptions();
  89399. var previousOnEmitNode = context.onEmitNode;
  89400. var previousOnSubstituteNode = context.onSubstituteNode;
  89401. context.onEmitNode = onEmitNode;
  89402. context.onSubstituteNode = onSubstituteNode;
  89403. context.enableEmitNotification(290 /* SourceFile */);
  89404. context.enableSubstitution(75 /* Identifier */);
  89405. var helperNameSubstitutions;
  89406. return ts.chainBundle(transformSourceFile);
  89407. function transformSourceFile(node) {
  89408. if (node.isDeclarationFile) {
  89409. return node;
  89410. }
  89411. if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
  89412. var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
  89413. if (externalHelpersImportDeclaration) {
  89414. var statements = [];
  89415. var statementOffset = ts.addPrologue(statements, node.statements);
  89416. ts.append(statements, externalHelpersImportDeclaration);
  89417. ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
  89418. return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
  89419. }
  89420. else {
  89421. return ts.visitEachChild(node, visitor, context);
  89422. }
  89423. }
  89424. return node;
  89425. }
  89426. function visitor(node) {
  89427. switch (node.kind) {
  89428. case 253 /* ImportEqualsDeclaration */:
  89429. // Elide `import=` as it is not legal with --module ES6
  89430. return undefined;
  89431. case 259 /* ExportAssignment */:
  89432. return visitExportAssignment(node);
  89433. case 260 /* ExportDeclaration */:
  89434. var exportDecl = node;
  89435. return visitExportDeclaration(exportDecl);
  89436. }
  89437. return node;
  89438. }
  89439. function visitExportAssignment(node) {
  89440. // Elide `export=` as it is not legal with --module ES6
  89441. return node.isExportEquals ? undefined : node;
  89442. }
  89443. function visitExportDeclaration(node) {
  89444. // `export * as ns` only needs to be transformed in ES2015
  89445. if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
  89446. return node;
  89447. }
  89448. // Either ill-formed or don't need to be tranformed.
  89449. if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
  89450. return node;
  89451. }
  89452. var oldIdentifier = node.exportClause.name;
  89453. var synthName = ts.getGeneratedNameForNode(oldIdentifier);
  89454. var importDecl = ts.createImportDeclaration(
  89455. /*decorators*/ undefined,
  89456. /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
  89457. ts.setOriginalNode(importDecl, node.exportClause);
  89458. var exportDecl = ts.createExportDeclaration(
  89459. /*decorators*/ undefined,
  89460. /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
  89461. ts.setOriginalNode(exportDecl, node);
  89462. return [importDecl, exportDecl];
  89463. }
  89464. //
  89465. // Emit Notification
  89466. //
  89467. /**
  89468. * Hook for node emit.
  89469. *
  89470. * @param hint A hint as to the intended usage of the node.
  89471. * @param node The node to emit.
  89472. * @param emit A callback used to emit the node in the printer.
  89473. */
  89474. function onEmitNode(hint, node, emitCallback) {
  89475. if (ts.isSourceFile(node)) {
  89476. if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
  89477. helperNameSubstitutions = ts.createMap();
  89478. }
  89479. previousOnEmitNode(hint, node, emitCallback);
  89480. helperNameSubstitutions = undefined;
  89481. }
  89482. else {
  89483. previousOnEmitNode(hint, node, emitCallback);
  89484. }
  89485. }
  89486. //
  89487. // Substitutions
  89488. //
  89489. /**
  89490. * Hooks node substitutions.
  89491. *
  89492. * @param hint A hint as to the intended usage of the node.
  89493. * @param node The node to substitute.
  89494. */
  89495. function onSubstituteNode(hint, node) {
  89496. node = previousOnSubstituteNode(hint, node);
  89497. if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
  89498. return substituteHelperName(node);
  89499. }
  89500. return node;
  89501. }
  89502. function substituteHelperName(node) {
  89503. var name = ts.idText(node);
  89504. var substitution = helperNameSubstitutions.get(name);
  89505. if (!substitution) {
  89506. helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
  89507. }
  89508. return substitution;
  89509. }
  89510. }
  89511. ts.transformECMAScriptModule = transformECMAScriptModule;
  89512. })(ts || (ts = {}));
  89513. /* @internal */
  89514. var ts;
  89515. (function (ts) {
  89516. function canProduceDiagnostics(node) {
  89517. return ts.isVariableDeclaration(node) ||
  89518. ts.isPropertyDeclaration(node) ||
  89519. ts.isPropertySignature(node) ||
  89520. ts.isBindingElement(node) ||
  89521. ts.isSetAccessor(node) ||
  89522. ts.isGetAccessor(node) ||
  89523. ts.isConstructSignatureDeclaration(node) ||
  89524. ts.isCallSignatureDeclaration(node) ||
  89525. ts.isMethodDeclaration(node) ||
  89526. ts.isMethodSignature(node) ||
  89527. ts.isFunctionDeclaration(node) ||
  89528. ts.isParameter(node) ||
  89529. ts.isTypeParameterDeclaration(node) ||
  89530. ts.isExpressionWithTypeArguments(node) ||
  89531. ts.isImportEqualsDeclaration(node) ||
  89532. ts.isTypeAliasDeclaration(node) ||
  89533. ts.isConstructorDeclaration(node) ||
  89534. ts.isIndexSignatureDeclaration(node) ||
  89535. ts.isPropertyAccessExpression(node);
  89536. }
  89537. ts.canProduceDiagnostics = canProduceDiagnostics;
  89538. function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
  89539. if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
  89540. return getAccessorNameVisibilityError;
  89541. }
  89542. else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
  89543. return getMethodNameVisibilityError;
  89544. }
  89545. else {
  89546. return createGetSymbolAccessibilityDiagnosticForNode(node);
  89547. }
  89548. function getAccessorNameVisibilityError(symbolAccessibilityResult) {
  89549. var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
  89550. return diagnosticMessage !== undefined ? {
  89551. diagnosticMessage: diagnosticMessage,
  89552. errorNode: node,
  89553. typeName: node.name
  89554. } : undefined;
  89555. }
  89556. function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
  89557. if (ts.hasModifier(node, 32 /* Static */)) {
  89558. return symbolAccessibilityResult.errorModuleName ?
  89559. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89560. ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89561. ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89562. ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
  89563. }
  89564. else if (node.parent.kind === 245 /* ClassDeclaration */) {
  89565. return symbolAccessibilityResult.errorModuleName ?
  89566. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89567. ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89568. ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89569. ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
  89570. }
  89571. else {
  89572. return symbolAccessibilityResult.errorModuleName ?
  89573. ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89574. ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
  89575. }
  89576. }
  89577. function getMethodNameVisibilityError(symbolAccessibilityResult) {
  89578. var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
  89579. return diagnosticMessage !== undefined ? {
  89580. diagnosticMessage: diagnosticMessage,
  89581. errorNode: node,
  89582. typeName: node.name
  89583. } : undefined;
  89584. }
  89585. function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
  89586. if (ts.hasModifier(node, 32 /* Static */)) {
  89587. return symbolAccessibilityResult.errorModuleName ?
  89588. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89589. ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89590. ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89591. ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
  89592. }
  89593. else if (node.parent.kind === 245 /* ClassDeclaration */) {
  89594. return symbolAccessibilityResult.errorModuleName ?
  89595. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89596. ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89597. ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89598. ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
  89599. }
  89600. else {
  89601. return symbolAccessibilityResult.errorModuleName ?
  89602. ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89603. ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
  89604. }
  89605. }
  89606. }
  89607. ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
  89608. function createGetSymbolAccessibilityDiagnosticForNode(node) {
  89609. if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
  89610. return getVariableDeclarationTypeVisibilityError;
  89611. }
  89612. else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
  89613. return getAccessorDeclarationTypeVisibilityError;
  89614. }
  89615. else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
  89616. return getReturnTypeVisibilityError;
  89617. }
  89618. else if (ts.isParameter(node)) {
  89619. if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
  89620. return getVariableDeclarationTypeVisibilityError;
  89621. }
  89622. return getParameterDeclarationTypeVisibilityError;
  89623. }
  89624. else if (ts.isTypeParameterDeclaration(node)) {
  89625. return getTypeParameterConstraintVisibilityError;
  89626. }
  89627. else if (ts.isExpressionWithTypeArguments(node)) {
  89628. return getHeritageClauseVisibilityError;
  89629. }
  89630. else if (ts.isImportEqualsDeclaration(node)) {
  89631. return getImportEntityNameVisibilityError;
  89632. }
  89633. else if (ts.isTypeAliasDeclaration(node)) {
  89634. return getTypeAliasDeclarationVisibilityError;
  89635. }
  89636. else {
  89637. return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
  89638. }
  89639. function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
  89640. if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
  89641. return symbolAccessibilityResult.errorModuleName ?
  89642. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89643. ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89644. ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
  89645. ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
  89646. }
  89647. // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
  89648. // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
  89649. else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
  89650. (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
  89651. // TODO(jfreeman): Deal with computed properties in error reporting.
  89652. if (ts.hasModifier(node, 32 /* Static */)) {
  89653. return symbolAccessibilityResult.errorModuleName ?
  89654. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89655. ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89656. ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89657. ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
  89658. }
  89659. else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
  89660. return symbolAccessibilityResult.errorModuleName ?
  89661. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89662. ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89663. ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89664. ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
  89665. }
  89666. else {
  89667. // Interfaces cannot have types that cannot be named
  89668. return symbolAccessibilityResult.errorModuleName ?
  89669. ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89670. ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
  89671. }
  89672. }
  89673. }
  89674. function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
  89675. var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
  89676. return diagnosticMessage !== undefined ? {
  89677. diagnosticMessage: diagnosticMessage,
  89678. errorNode: node,
  89679. typeName: node.name
  89680. } : undefined;
  89681. }
  89682. function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
  89683. var diagnosticMessage;
  89684. if (node.kind === 164 /* SetAccessor */) {
  89685. // Getters can infer the return type from the returned expression, but setters cannot, so the
  89686. // "_from_external_module_1_but_cannot_be_named" case cannot occur.
  89687. if (ts.hasModifier(node, 32 /* Static */)) {
  89688. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89689. ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89690. ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
  89691. }
  89692. else {
  89693. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89694. ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89695. ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
  89696. }
  89697. }
  89698. else {
  89699. if (ts.hasModifier(node, 32 /* Static */)) {
  89700. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89701. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89702. ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89703. ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89704. ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
  89705. }
  89706. else {
  89707. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89708. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89709. ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89710. ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89711. ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
  89712. }
  89713. }
  89714. return {
  89715. diagnosticMessage: diagnosticMessage,
  89716. errorNode: node.name,
  89717. typeName: node.name
  89718. };
  89719. }
  89720. function getReturnTypeVisibilityError(symbolAccessibilityResult) {
  89721. var diagnosticMessage;
  89722. switch (node.kind) {
  89723. case 166 /* ConstructSignature */:
  89724. // Interfaces cannot have return types that cannot be named
  89725. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89726. ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
  89727. ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
  89728. break;
  89729. case 165 /* CallSignature */:
  89730. // Interfaces cannot have return types that cannot be named
  89731. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89732. ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
  89733. ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
  89734. break;
  89735. case 167 /* IndexSignature */:
  89736. // Interfaces cannot have return types that cannot be named
  89737. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89738. ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
  89739. ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
  89740. break;
  89741. case 161 /* MethodDeclaration */:
  89742. case 160 /* MethodSignature */:
  89743. if (ts.hasModifier(node, 32 /* Static */)) {
  89744. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89745. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89746. ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
  89747. ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
  89748. ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
  89749. }
  89750. else if (node.parent.kind === 245 /* ClassDeclaration */) {
  89751. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89752. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89753. ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
  89754. ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
  89755. ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
  89756. }
  89757. else {
  89758. // Interfaces cannot have return types that cannot be named
  89759. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89760. ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
  89761. ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
  89762. }
  89763. break;
  89764. case 244 /* FunctionDeclaration */:
  89765. diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
  89766. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89767. ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
  89768. ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
  89769. ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
  89770. break;
  89771. default:
  89772. return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
  89773. }
  89774. return {
  89775. diagnosticMessage: diagnosticMessage,
  89776. errorNode: node.name || node
  89777. };
  89778. }
  89779. function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
  89780. var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
  89781. return diagnosticMessage !== undefined ? {
  89782. diagnosticMessage: diagnosticMessage,
  89783. errorNode: node,
  89784. typeName: node.name
  89785. } : undefined;
  89786. }
  89787. function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
  89788. switch (node.parent.kind) {
  89789. case 162 /* Constructor */:
  89790. return symbolAccessibilityResult.errorModuleName ?
  89791. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89792. ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89793. ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89794. ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
  89795. case 166 /* ConstructSignature */:
  89796. case 171 /* ConstructorType */:
  89797. // Interfaces cannot have parameter types that cannot be named
  89798. return symbolAccessibilityResult.errorModuleName ?
  89799. ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89800. ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
  89801. case 165 /* CallSignature */:
  89802. // Interfaces cannot have parameter types that cannot be named
  89803. return symbolAccessibilityResult.errorModuleName ?
  89804. ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89805. ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
  89806. case 167 /* IndexSignature */:
  89807. // Interfaces cannot have parameter types that cannot be named
  89808. return symbolAccessibilityResult.errorModuleName ?
  89809. ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89810. ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
  89811. case 161 /* MethodDeclaration */:
  89812. case 160 /* MethodSignature */:
  89813. if (ts.hasModifier(node.parent, 32 /* Static */)) {
  89814. return symbolAccessibilityResult.errorModuleName ?
  89815. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89816. ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89817. ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89818. ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
  89819. }
  89820. else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
  89821. return symbolAccessibilityResult.errorModuleName ?
  89822. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89823. ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89824. ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
  89825. ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
  89826. }
  89827. else {
  89828. // Interfaces cannot have parameter types that cannot be named
  89829. return symbolAccessibilityResult.errorModuleName ?
  89830. ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
  89831. ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
  89832. }
  89833. case 244 /* FunctionDeclaration */:
  89834. case 170 /* FunctionType */:
  89835. return symbolAccessibilityResult.errorModuleName ?
  89836. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89837. ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89838. ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
  89839. ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
  89840. case 164 /* SetAccessor */:
  89841. case 163 /* GetAccessor */:
  89842. return symbolAccessibilityResult.errorModuleName ?
  89843. symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
  89844. ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
  89845. ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
  89846. ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
  89847. default:
  89848. return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
  89849. }
  89850. }
  89851. function getTypeParameterConstraintVisibilityError() {
  89852. // Type parameter constraints are named by user so we should always be able to name it
  89853. var diagnosticMessage;
  89854. switch (node.parent.kind) {
  89855. case 245 /* ClassDeclaration */:
  89856. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
  89857. break;
  89858. case 246 /* InterfaceDeclaration */:
  89859. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
  89860. break;
  89861. case 186 /* MappedType */:
  89862. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
  89863. break;
  89864. case 171 /* ConstructorType */:
  89865. case 166 /* ConstructSignature */:
  89866. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
  89867. break;
  89868. case 165 /* CallSignature */:
  89869. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
  89870. break;
  89871. case 161 /* MethodDeclaration */:
  89872. case 160 /* MethodSignature */:
  89873. if (ts.hasModifier(node.parent, 32 /* Static */)) {
  89874. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
  89875. }
  89876. else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
  89877. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
  89878. }
  89879. else {
  89880. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
  89881. }
  89882. break;
  89883. case 170 /* FunctionType */:
  89884. case 244 /* FunctionDeclaration */:
  89885. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
  89886. break;
  89887. case 247 /* TypeAliasDeclaration */:
  89888. diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
  89889. break;
  89890. default:
  89891. return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
  89892. }
  89893. return {
  89894. diagnosticMessage: diagnosticMessage,
  89895. errorNode: node,
  89896. typeName: node.name
  89897. };
  89898. }
  89899. function getHeritageClauseVisibilityError() {
  89900. var diagnosticMessage;
  89901. // Heritage clause is written by user so it can always be named
  89902. if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
  89903. // Class or Interface implemented/extended is inaccessible
  89904. diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
  89905. ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
  89906. ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
  89907. }
  89908. else {
  89909. // interface is inaccessible
  89910. diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
  89911. }
  89912. return {
  89913. diagnosticMessage: diagnosticMessage,
  89914. errorNode: node,
  89915. typeName: ts.getNameOfDeclaration(node.parent.parent)
  89916. };
  89917. }
  89918. function getImportEntityNameVisibilityError() {
  89919. return {
  89920. diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
  89921. errorNode: node,
  89922. typeName: node.name
  89923. };
  89924. }
  89925. function getTypeAliasDeclarationVisibilityError() {
  89926. return {
  89927. diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
  89928. errorNode: node.type,
  89929. typeName: node.name
  89930. };
  89931. }
  89932. }
  89933. ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
  89934. })(ts || (ts = {}));
  89935. /*@internal*/
  89936. var ts;
  89937. (function (ts) {
  89938. function getDeclarationDiagnostics(host, resolver, file) {
  89939. if (file && ts.isJsonSourceFile(file)) {
  89940. return []; // No declaration diagnostics for json for now
  89941. }
  89942. var compilerOptions = host.getCompilerOptions();
  89943. var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
  89944. return result.diagnostics;
  89945. }
  89946. ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
  89947. function hasInternalAnnotation(range, currentSourceFile) {
  89948. var comment = currentSourceFile.text.substring(range.pos, range.end);
  89949. return ts.stringContains(comment, "@internal");
  89950. }
  89951. function isInternalDeclaration(node, currentSourceFile) {
  89952. var parseTreeNode = ts.getParseTreeNode(node);
  89953. if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
  89954. var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
  89955. var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
  89956. var text = currentSourceFile.text;
  89957. var commentRanges = previousSibling
  89958. ? ts.concatenate(
  89959. // to handle
  89960. // ... parameters, /* @internal */
  89961. // public param: string
  89962. ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
  89963. : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
  89964. return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
  89965. }
  89966. var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
  89967. return !!ts.forEach(leadingCommentRanges, function (range) {
  89968. return hasInternalAnnotation(range, currentSourceFile);
  89969. });
  89970. }
  89971. ts.isInternalDeclaration = isInternalDeclaration;
  89972. var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
  89973. 2048 /* WriteClassExpressionAsTypeLiteral */ |
  89974. 4096 /* UseTypeOfFunction */ |
  89975. 8 /* UseStructuralFallback */ |
  89976. 524288 /* AllowEmptyTuple */ |
  89977. 4 /* GenerateNamesForShadowedTypeParams */ |
  89978. 1 /* NoTruncation */;
  89979. /**
  89980. * Transforms a ts file into a .d.ts file
  89981. * This process requires type information, which is retrieved through the emit resolver. Because of this,
  89982. * in many places this transformer assumes it will be operating on parse tree nodes directly.
  89983. * This means that _no transforms should be allowed to occur before this one_.
  89984. */
  89985. function transformDeclarations(context) {
  89986. var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
  89987. var getSymbolAccessibilityDiagnostic = throwDiagnostic;
  89988. var needsDeclare = true;
  89989. var isBundledEmit = false;
  89990. var resultHasExternalModuleIndicator = false;
  89991. var needsScopeFixMarker = false;
  89992. var resultHasScopeMarker = false;
  89993. var enclosingDeclaration;
  89994. var necessaryTypeReferences;
  89995. var lateMarkedStatements;
  89996. var lateStatementReplacementMap;
  89997. var suppressNewDiagnosticContexts;
  89998. var exportedModulesFromDeclarationEmit;
  89999. var host = context.getEmitHost();
  90000. var symbolTracker = {
  90001. trackSymbol: trackSymbol,
  90002. reportInaccessibleThisError: reportInaccessibleThisError,
  90003. reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
  90004. reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
  90005. reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
  90006. moduleResolverHost: host,
  90007. trackReferencedAmbientModule: trackReferencedAmbientModule,
  90008. trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
  90009. };
  90010. var errorNameNode;
  90011. var currentSourceFile;
  90012. var refs;
  90013. var libs;
  90014. var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
  90015. var resolver = context.getEmitResolver();
  90016. var options = context.getCompilerOptions();
  90017. var noResolve = options.noResolve, stripInternal = options.stripInternal;
  90018. return transformRoot;
  90019. function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
  90020. if (!typeReferenceDirectives) {
  90021. return;
  90022. }
  90023. necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
  90024. for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
  90025. var ref = typeReferenceDirectives_2[_i];
  90026. necessaryTypeReferences.set(ref, true);
  90027. }
  90028. }
  90029. function trackReferencedAmbientModule(node, symbol) {
  90030. // If it is visible via `// <reference types="..."/>`, then we should just use that
  90031. var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
  90032. if (ts.length(directives)) {
  90033. return recordTypeReferenceDirectivesIfNecessary(directives);
  90034. }
  90035. // Otherwise we should emit a path-based reference
  90036. var container = ts.getSourceFileOfNode(node);
  90037. refs.set("" + ts.getOriginalNodeId(container), container);
  90038. }
  90039. function handleSymbolAccessibilityError(symbolAccessibilityResult) {
  90040. if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
  90041. // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
  90042. if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
  90043. if (!lateMarkedStatements) {
  90044. lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
  90045. }
  90046. else {
  90047. for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
  90048. var ref = _a[_i];
  90049. ts.pushIfUnique(lateMarkedStatements, ref);
  90050. }
  90051. }
  90052. }
  90053. // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
  90054. }
  90055. else {
  90056. // Report error
  90057. var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
  90058. if (errorInfo) {
  90059. if (errorInfo.typeName) {
  90060. context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
  90061. }
  90062. else {
  90063. context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
  90064. }
  90065. }
  90066. }
  90067. }
  90068. function trackExternalModuleSymbolOfImportTypeNode(symbol) {
  90069. if (!isBundledEmit) {
  90070. (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
  90071. }
  90072. }
  90073. function trackSymbol(symbol, enclosingDeclaration, meaning) {
  90074. if (symbol.flags & 262144 /* TypeParameter */)
  90075. return;
  90076. handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
  90077. recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
  90078. }
  90079. function reportPrivateInBaseOfClassExpression(propertyName) {
  90080. if (errorNameNode) {
  90081. context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
  90082. }
  90083. }
  90084. function reportInaccessibleUniqueSymbolError() {
  90085. if (errorNameNode) {
  90086. context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol"));
  90087. }
  90088. }
  90089. function reportInaccessibleThisError() {
  90090. if (errorNameNode) {
  90091. context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
  90092. }
  90093. }
  90094. function reportLikelyUnsafeImportRequiredError(specifier) {
  90095. if (errorNameNode) {
  90096. context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
  90097. }
  90098. }
  90099. function transformDeclarationsForJS(sourceFile, bundled) {
  90100. var oldDiag = getSymbolAccessibilityDiagnostic;
  90101. getSymbolAccessibilityDiagnostic = function (s) { return ({
  90102. diagnosticMessage: s.errorModuleName
  90103. ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
  90104. : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
  90105. errorNode: s.errorNode || sourceFile
  90106. }); };
  90107. var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
  90108. getSymbolAccessibilityDiagnostic = oldDiag;
  90109. return result;
  90110. }
  90111. function transformRoot(node) {
  90112. if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
  90113. return node;
  90114. }
  90115. if (node.kind === 291 /* Bundle */) {
  90116. isBundledEmit = true;
  90117. refs = ts.createMap();
  90118. libs = ts.createMap();
  90119. var hasNoDefaultLib_1 = false;
  90120. var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
  90121. if (sourceFile.isDeclarationFile)
  90122. return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
  90123. hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
  90124. currentSourceFile = sourceFile;
  90125. enclosingDeclaration = sourceFile;
  90126. lateMarkedStatements = undefined;
  90127. suppressNewDiagnosticContexts = false;
  90128. lateStatementReplacementMap = ts.createMap();
  90129. getSymbolAccessibilityDiagnostic = throwDiagnostic;
  90130. needsScopeFixMarker = false;
  90131. resultHasScopeMarker = false;
  90132. collectReferences(sourceFile, refs);
  90133. collectLibs(sourceFile, libs);
  90134. if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
  90135. resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
  90136. needsDeclare = false;
  90137. var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
  90138. var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(130 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
  90139. return newFile;
  90140. }
  90141. needsDeclare = true;
  90142. var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
  90143. return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
  90144. }), ts.mapDefined(node.prepends, function (prepend) {
  90145. if (prepend.kind === 293 /* InputFiles */) {
  90146. var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
  90147. hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
  90148. collectReferences(sourceFile, refs);
  90149. recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
  90150. collectLibs(sourceFile, libs);
  90151. return sourceFile;
  90152. }
  90153. return prepend;
  90154. }));
  90155. bundle.syntheticFileReferences = [];
  90156. bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
  90157. bundle.syntheticLibReferences = getLibReferences();
  90158. bundle.hasNoDefaultLib = hasNoDefaultLib_1;
  90159. var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
  90160. var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
  90161. refs.forEach(referenceVisitor_1);
  90162. return bundle;
  90163. }
  90164. // Single source file
  90165. needsDeclare = true;
  90166. needsScopeFixMarker = false;
  90167. resultHasScopeMarker = false;
  90168. enclosingDeclaration = node;
  90169. currentSourceFile = node;
  90170. getSymbolAccessibilityDiagnostic = throwDiagnostic;
  90171. isBundledEmit = false;
  90172. resultHasExternalModuleIndicator = false;
  90173. suppressNewDiagnosticContexts = false;
  90174. lateMarkedStatements = undefined;
  90175. lateStatementReplacementMap = ts.createMap();
  90176. necessaryTypeReferences = undefined;
  90177. refs = collectReferences(currentSourceFile, ts.createMap());
  90178. libs = collectLibs(currentSourceFile, ts.createMap());
  90179. var references = [];
  90180. var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
  90181. var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
  90182. var combinedStatements;
  90183. if (ts.isSourceFileJS(currentSourceFile)) {
  90184. combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
  90185. refs.forEach(referenceVisitor);
  90186. emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
  90187. }
  90188. else {
  90189. var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
  90190. combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
  90191. refs.forEach(referenceVisitor);
  90192. emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
  90193. if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
  90194. combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
  90195. }
  90196. }
  90197. var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
  90198. updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
  90199. return updated;
  90200. function getLibReferences() {
  90201. return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
  90202. }
  90203. function getFileReferencesForUsedTypeReferences() {
  90204. return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
  90205. }
  90206. function getFileReferenceForTypeName(typeName) {
  90207. // Elide type references for which we have imports
  90208. if (emittedImports) {
  90209. for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
  90210. var importStatement = emittedImports_1[_i];
  90211. if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
  90212. var expr = importStatement.moduleReference.expression;
  90213. if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
  90214. return undefined;
  90215. }
  90216. }
  90217. else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
  90218. return undefined;
  90219. }
  90220. }
  90221. }
  90222. return { fileName: typeName, pos: -1, end: -1 };
  90223. }
  90224. function mapReferencesIntoArray(references, outputFilePath) {
  90225. return function (file) {
  90226. var declFileName;
  90227. if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
  90228. declFileName = file.fileName;
  90229. }
  90230. else {
  90231. if (isBundledEmit && ts.contains(node.sourceFiles, file))
  90232. return; // Omit references to files which are being merged
  90233. var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
  90234. declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
  90235. }
  90236. if (declFileName) {
  90237. var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, host.getSourceFiles(),
  90238. /*preferences*/ undefined, host.redirectTargetsMap);
  90239. if (!ts.pathIsRelative(specifier)) {
  90240. // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
  90241. // via a non-relative name, emit a type reference directive to that non-relative name, rather than
  90242. // a relative path to the declaration file
  90243. recordTypeReferenceDirectivesIfNecessary([specifier]);
  90244. return;
  90245. }
  90246. var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
  90247. /*isAbsolutePathAnUrl*/ false);
  90248. if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
  90249. fileName = fileName.substring(2);
  90250. }
  90251. // omit references to files from node_modules (npm may disambiguate module
  90252. // references when installing this package, making the path is unreliable).
  90253. if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) {
  90254. return;
  90255. }
  90256. references.push({ pos: -1, end: -1, fileName: fileName });
  90257. }
  90258. };
  90259. }
  90260. }
  90261. function collectReferences(sourceFile, ret) {
  90262. if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
  90263. return ret;
  90264. ts.forEach(sourceFile.referencedFiles, function (f) {
  90265. var elem = host.getSourceFileFromReference(sourceFile, f);
  90266. if (elem) {
  90267. ret.set("" + ts.getOriginalNodeId(elem), elem);
  90268. }
  90269. });
  90270. return ret;
  90271. }
  90272. function collectLibs(sourceFile, ret) {
  90273. ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
  90274. var lib = host.getLibFileFromReference(ref);
  90275. if (lib) {
  90276. ret.set(ts.toFileNameLowerCase(ref.fileName), true);
  90277. }
  90278. });
  90279. return ret;
  90280. }
  90281. function filterBindingPatternInitializers(name) {
  90282. if (name.kind === 75 /* Identifier */) {
  90283. return name;
  90284. }
  90285. else {
  90286. if (name.kind === 190 /* ArrayBindingPattern */) {
  90287. return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
  90288. }
  90289. else {
  90290. return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
  90291. }
  90292. }
  90293. function visitBindingElement(elem) {
  90294. if (elem.kind === 215 /* OmittedExpression */) {
  90295. return elem;
  90296. }
  90297. return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
  90298. }
  90299. }
  90300. function ensureParameter(p, modifierMask, type) {
  90301. var oldDiag;
  90302. if (!suppressNewDiagnosticContexts) {
  90303. oldDiag = getSymbolAccessibilityDiagnostic;
  90304. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
  90305. }
  90306. var newParam = ts.updateParameter(p,
  90307. /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(57 /* QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param
  90308. ensureNoInitializer(p));
  90309. if (!suppressNewDiagnosticContexts) {
  90310. getSymbolAccessibilityDiagnostic = oldDiag;
  90311. }
  90312. return newParam;
  90313. }
  90314. function shouldPrintWithInitializer(node) {
  90315. return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
  90316. }
  90317. function ensureNoInitializer(node) {
  90318. if (shouldPrintWithInitializer(node)) {
  90319. return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
  90320. }
  90321. return undefined;
  90322. }
  90323. function ensureType(node, type, ignorePrivate) {
  90324. if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
  90325. // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
  90326. return;
  90327. }
  90328. if (shouldPrintWithInitializer(node)) {
  90329. // Literal const declarations will have an initializer ensured rather than a type
  90330. return;
  90331. }
  90332. var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
  90333. (resolver.isRequiredInitializedParameter(node) ||
  90334. resolver.isOptionalUninitializedParameterProperty(node));
  90335. if (type && !shouldUseResolverType) {
  90336. return ts.visitNode(type, visitDeclarationSubtree);
  90337. }
  90338. if (!ts.getParseTreeNode(node)) {
  90339. return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
  90340. }
  90341. if (node.kind === 164 /* SetAccessor */) {
  90342. // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now
  90343. // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
  90344. return ts.createKeywordTypeNode(125 /* AnyKeyword */);
  90345. }
  90346. errorNameNode = node.name;
  90347. var oldDiag;
  90348. if (!suppressNewDiagnosticContexts) {
  90349. oldDiag = getSymbolAccessibilityDiagnostic;
  90350. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
  90351. }
  90352. if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
  90353. return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
  90354. }
  90355. if (node.kind === 156 /* Parameter */
  90356. || node.kind === 159 /* PropertyDeclaration */
  90357. || node.kind === 158 /* PropertySignature */) {
  90358. if (!node.initializer)
  90359. return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
  90360. return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
  90361. }
  90362. return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
  90363. function cleanup(returnValue) {
  90364. errorNameNode = undefined;
  90365. if (!suppressNewDiagnosticContexts) {
  90366. getSymbolAccessibilityDiagnostic = oldDiag;
  90367. }
  90368. return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
  90369. }
  90370. }
  90371. function isDeclarationAndNotVisible(node) {
  90372. node = ts.getParseTreeNode(node);
  90373. switch (node.kind) {
  90374. case 244 /* FunctionDeclaration */:
  90375. case 249 /* ModuleDeclaration */:
  90376. case 246 /* InterfaceDeclaration */:
  90377. case 245 /* ClassDeclaration */:
  90378. case 247 /* TypeAliasDeclaration */:
  90379. case 248 /* EnumDeclaration */:
  90380. return !resolver.isDeclarationVisible(node);
  90381. // The following should be doing their own visibility checks based on filtering their members
  90382. case 242 /* VariableDeclaration */:
  90383. return !getBindingNameVisible(node);
  90384. case 253 /* ImportEqualsDeclaration */:
  90385. case 254 /* ImportDeclaration */:
  90386. case 260 /* ExportDeclaration */:
  90387. case 259 /* ExportAssignment */:
  90388. return false;
  90389. }
  90390. return false;
  90391. }
  90392. function getBindingNameVisible(elem) {
  90393. if (ts.isOmittedExpression(elem)) {
  90394. return false;
  90395. }
  90396. if (ts.isBindingPattern(elem.name)) {
  90397. // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
  90398. return ts.some(elem.name.elements, getBindingNameVisible);
  90399. }
  90400. else {
  90401. return resolver.isDeclarationVisible(elem);
  90402. }
  90403. }
  90404. function updateParamsList(node, params, modifierMask) {
  90405. if (ts.hasModifier(node, 8 /* Private */)) {
  90406. return undefined; // TODO: GH#18217
  90407. }
  90408. var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
  90409. if (!newParams) {
  90410. return undefined; // TODO: GH#18217
  90411. }
  90412. return ts.createNodeArray(newParams, params.hasTrailingComma);
  90413. }
  90414. function updateAccessorParamsList(input, isPrivate) {
  90415. var newParams;
  90416. if (!isPrivate) {
  90417. var thisParameter = ts.getThisParameter(input);
  90418. if (thisParameter) {
  90419. newParams = [ensureParameter(thisParameter)];
  90420. }
  90421. }
  90422. if (ts.isSetAccessorDeclaration(input)) {
  90423. var newValueParameter = void 0;
  90424. if (!isPrivate) {
  90425. var valueParameter = ts.getSetAccessorValueParameter(input);
  90426. if (valueParameter) {
  90427. var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
  90428. newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
  90429. }
  90430. }
  90431. if (!newValueParameter) {
  90432. newValueParameter = ts.createParameter(
  90433. /*decorators*/ undefined,
  90434. /*modifiers*/ undefined,
  90435. /*dotDotDotToken*/ undefined, "value");
  90436. }
  90437. newParams = ts.append(newParams, newValueParameter);
  90438. }
  90439. return ts.createNodeArray(newParams || ts.emptyArray);
  90440. }
  90441. function ensureTypeParams(node, params) {
  90442. return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
  90443. }
  90444. function isEnclosingDeclaration(node) {
  90445. return ts.isSourceFile(node)
  90446. || ts.isTypeAliasDeclaration(node)
  90447. || ts.isModuleDeclaration(node)
  90448. || ts.isClassDeclaration(node)
  90449. || ts.isInterfaceDeclaration(node)
  90450. || ts.isFunctionLike(node)
  90451. || ts.isIndexSignatureDeclaration(node)
  90452. || ts.isMappedTypeNode(node);
  90453. }
  90454. function checkEntityNameVisibility(entityName, enclosingDeclaration) {
  90455. var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
  90456. handleSymbolAccessibilityError(visibilityResult);
  90457. recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
  90458. }
  90459. function preserveJsDoc(updated, original) {
  90460. if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
  90461. updated.jsDoc = original.jsDoc;
  90462. }
  90463. return ts.setCommentRange(updated, ts.getCommentRange(original));
  90464. }
  90465. function rewriteModuleSpecifier(parent, input) {
  90466. if (!input)
  90467. return undefined; // TODO: GH#18217
  90468. resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
  90469. if (ts.isStringLiteralLike(input)) {
  90470. if (isBundledEmit) {
  90471. var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
  90472. if (newName) {
  90473. return ts.createLiteral(newName);
  90474. }
  90475. }
  90476. else {
  90477. var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
  90478. if (symbol) {
  90479. (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
  90480. }
  90481. }
  90482. }
  90483. return input;
  90484. }
  90485. function transformImportEqualsDeclaration(decl) {
  90486. if (!resolver.isDeclarationVisible(decl))
  90487. return;
  90488. if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
  90489. // Rewrite external module names if necessary
  90490. var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
  90491. return ts.updateImportEqualsDeclaration(decl,
  90492. /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
  90493. }
  90494. else {
  90495. var oldDiag = getSymbolAccessibilityDiagnostic;
  90496. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
  90497. checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
  90498. getSymbolAccessibilityDiagnostic = oldDiag;
  90499. return decl;
  90500. }
  90501. }
  90502. function transformImportDeclaration(decl) {
  90503. if (!decl.importClause) {
  90504. // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
  90505. return ts.updateImportDeclaration(decl,
  90506. /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
  90507. }
  90508. // The `importClause` visibility corresponds to the default's visibility.
  90509. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
  90510. if (!decl.importClause.namedBindings) {
  90511. // No named bindings (either namespace or list), meaning the import is just default or should be elided
  90512. return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding,
  90513. /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
  90514. }
  90515. if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
  90516. // Namespace import (optionally with visible default)
  90517. var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
  90518. return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
  90519. }
  90520. // Named imports (optionally with visible default)
  90521. var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
  90522. if ((bindingList && bindingList.length) || visibleDefaultBinding) {
  90523. return ts.updateImportDeclaration(decl,
  90524. /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
  90525. }
  90526. // Nothing visible
  90527. }
  90528. function transformAndReplaceLatePaintedStatements(statements) {
  90529. // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
  90530. // error handling which must now be included in the output and themselves checked for errors.
  90531. // For example:
  90532. // ```
  90533. // module A {
  90534. // export module Q {}
  90535. // import B = Q;
  90536. // import C = B;
  90537. // export import D = C;
  90538. // }
  90539. // ```
  90540. // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
  90541. // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
  90542. // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
  90543. while (ts.length(lateMarkedStatements)) {
  90544. var i = lateMarkedStatements.shift();
  90545. if (!ts.isLateVisibilityPaintedStatement(i)) {
  90546. return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
  90547. }
  90548. var priorNeedsDeclare = needsDeclare;
  90549. needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
  90550. var result = transformTopLevelDeclaration(i);
  90551. needsDeclare = priorNeedsDeclare;
  90552. lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
  90553. }
  90554. // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
  90555. // (and remove them from the set to examine for outter declarations)
  90556. return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
  90557. function visitLateVisibilityMarkedStatements(statement) {
  90558. if (ts.isLateVisibilityPaintedStatement(statement)) {
  90559. var key = "" + ts.getOriginalNodeId(statement);
  90560. if (lateStatementReplacementMap.has(key)) {
  90561. var result = lateStatementReplacementMap.get(key);
  90562. lateStatementReplacementMap.delete(key);
  90563. if (result) {
  90564. if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
  90565. // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
  90566. needsScopeFixMarker = true;
  90567. }
  90568. if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
  90569. resultHasExternalModuleIndicator = true;
  90570. }
  90571. }
  90572. return result;
  90573. }
  90574. }
  90575. return statement;
  90576. }
  90577. }
  90578. function visitDeclarationSubtree(input) {
  90579. if (shouldStripInternal(input))
  90580. return;
  90581. if (ts.isDeclaration(input)) {
  90582. if (isDeclarationAndNotVisible(input))
  90583. return;
  90584. if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
  90585. return;
  90586. }
  90587. }
  90588. // Elide implementation signatures from overload sets
  90589. if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
  90590. return;
  90591. // Elide semicolon class statements
  90592. if (ts.isSemicolonClassElement(input))
  90593. return;
  90594. var previousEnclosingDeclaration;
  90595. if (isEnclosingDeclaration(input)) {
  90596. previousEnclosingDeclaration = enclosingDeclaration;
  90597. enclosingDeclaration = input;
  90598. }
  90599. var oldDiag = getSymbolAccessibilityDiagnostic;
  90600. // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
  90601. // We'd see a TDZ violation at runtime
  90602. var canProduceDiagnostic = ts.canProduceDiagnostics(input);
  90603. var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
  90604. var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
  90605. // Emit methods which are private as properties with no type information
  90606. if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
  90607. if (ts.hasModifier(input, 8 /* Private */)) {
  90608. if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
  90609. return; // Elide all but the first overload
  90610. return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
  90611. }
  90612. }
  90613. if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
  90614. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
  90615. }
  90616. if (ts.isTypeQueryNode(input)) {
  90617. checkEntityNameVisibility(input.exprName, enclosingDeclaration);
  90618. }
  90619. if (shouldEnterSuppressNewDiagnosticsContextContext) {
  90620. // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do.
  90621. suppressNewDiagnosticContexts = true;
  90622. }
  90623. if (isProcessedComponent(input)) {
  90624. switch (input.kind) {
  90625. case 216 /* ExpressionWithTypeArguments */: {
  90626. if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
  90627. checkEntityNameVisibility(input.expression, enclosingDeclaration);
  90628. }
  90629. var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
  90630. return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
  90631. }
  90632. case 169 /* TypeReference */: {
  90633. checkEntityNameVisibility(input.typeName, enclosingDeclaration);
  90634. var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
  90635. return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
  90636. }
  90637. case 166 /* ConstructSignature */:
  90638. return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
  90639. case 162 /* Constructor */: {
  90640. // A constructor declaration may not have a type annotation
  90641. var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */),
  90642. /*type*/ undefined);
  90643. ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
  90644. return cleanup(ctor);
  90645. }
  90646. case 161 /* MethodDeclaration */: {
  90647. if (ts.isPrivateIdentifier(input.name)) {
  90648. return cleanup(/*returnValue*/ undefined);
  90649. }
  90650. var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
  90651. sig.name = input.name;
  90652. sig.modifiers = ts.createNodeArray(ensureModifiers(input));
  90653. sig.questionToken = input.questionToken;
  90654. return cleanup(sig);
  90655. }
  90656. case 163 /* GetAccessor */: {
  90657. if (ts.isPrivateIdentifier(input.name)) {
  90658. return cleanup(/*returnValue*/ undefined);
  90659. }
  90660. var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
  90661. return cleanup(ts.updateGetAccessor(input,
  90662. /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType),
  90663. /*body*/ undefined));
  90664. }
  90665. case 164 /* SetAccessor */: {
  90666. if (ts.isPrivateIdentifier(input.name)) {
  90667. return cleanup(/*returnValue*/ undefined);
  90668. }
  90669. return cleanup(ts.updateSetAccessor(input,
  90670. /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)),
  90671. /*body*/ undefined));
  90672. }
  90673. case 159 /* PropertyDeclaration */:
  90674. if (ts.isPrivateIdentifier(input.name)) {
  90675. return cleanup(/*returnValue*/ undefined);
  90676. }
  90677. return cleanup(ts.updateProperty(input,
  90678. /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
  90679. case 158 /* PropertySignature */:
  90680. if (ts.isPrivateIdentifier(input.name)) {
  90681. return cleanup(/*returnValue*/ undefined);
  90682. }
  90683. return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
  90684. case 160 /* MethodSignature */: {
  90685. if (ts.isPrivateIdentifier(input.name)) {
  90686. return cleanup(/*returnValue*/ undefined);
  90687. }
  90688. return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
  90689. }
  90690. case 165 /* CallSignature */: {
  90691. return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
  90692. }
  90693. case 167 /* IndexSignature */: {
  90694. return cleanup(ts.updateIndexSignature(input,
  90695. /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
  90696. }
  90697. case 242 /* VariableDeclaration */: {
  90698. if (ts.isBindingPattern(input.name)) {
  90699. return recreateBindingPattern(input.name);
  90700. }
  90701. shouldEnterSuppressNewDiagnosticsContextContext = true;
  90702. suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
  90703. return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
  90704. }
  90705. case 155 /* TypeParameter */: {
  90706. if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
  90707. return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
  90708. }
  90709. return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
  90710. }
  90711. case 180 /* ConditionalType */: {
  90712. // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
  90713. // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
  90714. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
  90715. var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
  90716. var oldEnclosingDecl = enclosingDeclaration;
  90717. enclosingDeclaration = input.trueType;
  90718. var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
  90719. enclosingDeclaration = oldEnclosingDecl;
  90720. var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
  90721. return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
  90722. }
  90723. case 170 /* FunctionType */: {
  90724. return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
  90725. }
  90726. case 171 /* ConstructorType */: {
  90727. return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
  90728. }
  90729. case 188 /* ImportType */: {
  90730. if (!ts.isLiteralImportTypeNode(input))
  90731. return cleanup(input);
  90732. return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
  90733. }
  90734. default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
  90735. }
  90736. }
  90737. return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
  90738. function cleanup(returnValue) {
  90739. if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
  90740. checkName(input);
  90741. }
  90742. if (isEnclosingDeclaration(input)) {
  90743. enclosingDeclaration = previousEnclosingDeclaration;
  90744. }
  90745. if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
  90746. getSymbolAccessibilityDiagnostic = oldDiag;
  90747. }
  90748. if (shouldEnterSuppressNewDiagnosticsContextContext) {
  90749. suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
  90750. }
  90751. if (returnValue === input) {
  90752. return returnValue;
  90753. }
  90754. return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
  90755. }
  90756. }
  90757. function isPrivateMethodTypeParameter(node) {
  90758. return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
  90759. }
  90760. function visitDeclarationStatements(input) {
  90761. if (!isPreservedDeclarationStatement(input)) {
  90762. // return undefined for unmatched kinds to omit them from the tree
  90763. return;
  90764. }
  90765. if (shouldStripInternal(input))
  90766. return;
  90767. switch (input.kind) {
  90768. case 260 /* ExportDeclaration */: {
  90769. if (ts.isSourceFile(input.parent)) {
  90770. resultHasExternalModuleIndicator = true;
  90771. }
  90772. resultHasScopeMarker = true;
  90773. // Always visible if the parent node isn't dropped for being not visible
  90774. // Rewrite external module names if necessary
  90775. return ts.updateExportDeclaration(input,
  90776. /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
  90777. }
  90778. case 259 /* ExportAssignment */: {
  90779. // Always visible if the parent node isn't dropped for being not visible
  90780. if (ts.isSourceFile(input.parent)) {
  90781. resultHasExternalModuleIndicator = true;
  90782. }
  90783. resultHasScopeMarker = true;
  90784. if (input.expression.kind === 75 /* Identifier */) {
  90785. return input;
  90786. }
  90787. else {
  90788. var newId = ts.createOptimisticUniqueName("_default");
  90789. getSymbolAccessibilityDiagnostic = function () { return ({
  90790. diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
  90791. errorNode: input
  90792. }); };
  90793. var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
  90794. var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
  90795. return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
  90796. }
  90797. }
  90798. }
  90799. var result = transformTopLevelDeclaration(input);
  90800. // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
  90801. lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
  90802. return input;
  90803. }
  90804. function stripExportModifiers(statement) {
  90805. if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
  90806. // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
  90807. // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
  90808. return statement;
  90809. }
  90810. var clone = ts.getMutableClone(statement);
  90811. var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
  90812. clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
  90813. return clone;
  90814. }
  90815. function transformTopLevelDeclaration(input) {
  90816. if (shouldStripInternal(input))
  90817. return;
  90818. switch (input.kind) {
  90819. case 253 /* ImportEqualsDeclaration */: {
  90820. return transformImportEqualsDeclaration(input);
  90821. }
  90822. case 254 /* ImportDeclaration */: {
  90823. return transformImportDeclaration(input);
  90824. }
  90825. }
  90826. if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
  90827. return;
  90828. // Elide implementation signatures from overload sets
  90829. if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
  90830. return;
  90831. var previousEnclosingDeclaration;
  90832. if (isEnclosingDeclaration(input)) {
  90833. previousEnclosingDeclaration = enclosingDeclaration;
  90834. enclosingDeclaration = input;
  90835. }
  90836. var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
  90837. var oldDiag = getSymbolAccessibilityDiagnostic;
  90838. if (canProdiceDiagnostic) {
  90839. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
  90840. }
  90841. var previousNeedsDeclare = needsDeclare;
  90842. switch (input.kind) {
  90843. case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
  90844. return cleanup(ts.updateTypeAliasDeclaration(input,
  90845. /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
  90846. case 246 /* InterfaceDeclaration */: {
  90847. return cleanup(ts.updateInterfaceDeclaration(input,
  90848. /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
  90849. }
  90850. case 244 /* FunctionDeclaration */: {
  90851. // Generators lose their generator-ness, excepting their return type
  90852. var clean = cleanup(ts.updateFunctionDeclaration(input,
  90853. /*decorators*/ undefined, ensureModifiers(input),
  90854. /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
  90855. /*body*/ undefined));
  90856. if (clean && resolver.isExpandoFunctionDeclaration(input)) {
  90857. var props = resolver.getPropertiesOfContainerFunction(input);
  90858. var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
  90859. fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
  90860. fakespace_1.parent = enclosingDeclaration;
  90861. fakespace_1.locals = ts.createSymbolTable(props);
  90862. fakespace_1.symbol = props[0].parent;
  90863. var declarations = ts.mapDefined(props, function (p) {
  90864. if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
  90865. return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
  90866. }
  90867. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
  90868. var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
  90869. getSymbolAccessibilityDiagnostic = oldDiag;
  90870. var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
  90871. return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
  90872. });
  90873. var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
  90874. if (!ts.hasModifier(clean, 512 /* Default */)) {
  90875. return [clean, namespaceDecl];
  90876. }
  90877. var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
  90878. var cleanDeclaration = ts.updateFunctionDeclaration(clean,
  90879. /*decorators*/ undefined, modifiers,
  90880. /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type,
  90881. /*body*/ undefined);
  90882. var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl,
  90883. /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
  90884. var exportDefaultDeclaration = ts.createExportAssignment(
  90885. /*decorators*/ undefined,
  90886. /*modifiers*/ undefined,
  90887. /*isExportEquals*/ false, namespaceDecl.name);
  90888. if (ts.isSourceFile(input.parent)) {
  90889. resultHasExternalModuleIndicator = true;
  90890. }
  90891. resultHasScopeMarker = true;
  90892. return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
  90893. }
  90894. else {
  90895. return clean;
  90896. }
  90897. }
  90898. case 249 /* ModuleDeclaration */: {
  90899. needsDeclare = false;
  90900. var inner = input.body;
  90901. if (inner && inner.kind === 250 /* ModuleBlock */) {
  90902. var oldNeedsScopeFix = needsScopeFixMarker;
  90903. var oldHasScopeFix = resultHasScopeMarker;
  90904. resultHasScopeMarker = false;
  90905. needsScopeFixMarker = false;
  90906. var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
  90907. var lateStatements = transformAndReplaceLatePaintedStatements(statements);
  90908. if (input.flags & 8388608 /* Ambient */) {
  90909. needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
  90910. }
  90911. // With the final list of statements, there are 3 possibilities:
  90912. // 1. There's an export assignment or export declaration in the namespace - do nothing
  90913. // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
  90914. // 3. Some things are exported, some are not, and there's no marker - add an empty marker
  90915. if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
  90916. if (needsScopeFixMarker) {
  90917. lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
  90918. }
  90919. else {
  90920. lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
  90921. }
  90922. }
  90923. var body = ts.updateModuleBlock(inner, lateStatements);
  90924. needsDeclare = previousNeedsDeclare;
  90925. needsScopeFixMarker = oldNeedsScopeFix;
  90926. resultHasScopeMarker = oldHasScopeFix;
  90927. var mods = ensureModifiers(input);
  90928. return cleanup(ts.updateModuleDeclaration(input,
  90929. /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
  90930. }
  90931. else {
  90932. needsDeclare = previousNeedsDeclare;
  90933. var mods = ensureModifiers(input);
  90934. needsDeclare = false;
  90935. ts.visitNode(inner, visitDeclarationStatements);
  90936. // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
  90937. var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
  90938. var body = lateStatementReplacementMap.get(id);
  90939. lateStatementReplacementMap.delete(id);
  90940. return cleanup(ts.updateModuleDeclaration(input,
  90941. /*decorators*/ undefined, mods, input.name, body));
  90942. }
  90943. }
  90944. case 245 /* ClassDeclaration */: {
  90945. var modifiers = ts.createNodeArray(ensureModifiers(input));
  90946. var typeParameters = ensureTypeParams(input, input.typeParameters);
  90947. var ctor = ts.getFirstConstructorWithBody(input);
  90948. var parameterProperties = void 0;
  90949. if (ctor) {
  90950. var oldDiag_1 = getSymbolAccessibilityDiagnostic;
  90951. parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
  90952. if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
  90953. return;
  90954. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
  90955. if (param.name.kind === 75 /* Identifier */) {
  90956. return preserveJsDoc(ts.createProperty(
  90957. /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
  90958. }
  90959. else {
  90960. // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
  90961. return walkBindingPattern(param.name);
  90962. }
  90963. function walkBindingPattern(pattern) {
  90964. var elems;
  90965. for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
  90966. var elem = _a[_i];
  90967. if (ts.isOmittedExpression(elem))
  90968. continue;
  90969. if (ts.isBindingPattern(elem.name)) {
  90970. elems = ts.concatenate(elems, walkBindingPattern(elem.name));
  90971. }
  90972. elems = elems || [];
  90973. elems.push(ts.createProperty(
  90974. /*decorators*/ undefined, ensureModifiers(param), elem.name,
  90975. /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined),
  90976. /*initializer*/ undefined));
  90977. }
  90978. return elems;
  90979. }
  90980. }));
  90981. getSymbolAccessibilityDiagnostic = oldDiag_1;
  90982. }
  90983. var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
  90984. var privateIdentifier = hasPrivateIdentifier ? [
  90985. ts.createProperty(
  90986. /*decorators*/ undefined,
  90987. /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"),
  90988. /*questionToken*/ undefined,
  90989. /*type*/ undefined,
  90990. /*initializer*/ undefined)
  90991. ] : undefined;
  90992. var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
  90993. var members = ts.createNodeArray(memberNodes);
  90994. var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
  90995. if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
  90996. // We must add a temporary declaration for the extends clause expression
  90997. var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
  90998. var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
  90999. getSymbolAccessibilityDiagnostic = function () { return ({
  91000. diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
  91001. errorNode: extendsClause_1,
  91002. typeName: input.name
  91003. }); };
  91004. var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
  91005. var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
  91006. var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
  91007. if (clause.token === 90 /* ExtendsKeyword */) {
  91008. var oldDiag_2 = getSymbolAccessibilityDiagnostic;
  91009. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
  91010. var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
  91011. getSymbolAccessibilityDiagnostic = oldDiag_2;
  91012. return newClause;
  91013. }
  91014. return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 100 /* NullKeyword */; })), visitDeclarationSubtree));
  91015. }));
  91016. return [statement, cleanup(ts.updateClassDeclaration(input,
  91017. /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
  91018. }
  91019. else {
  91020. var heritageClauses = transformHeritageClauses(input.heritageClauses);
  91021. return cleanup(ts.updateClassDeclaration(input,
  91022. /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
  91023. }
  91024. }
  91025. case 225 /* VariableStatement */: {
  91026. return cleanup(transformVariableStatement(input));
  91027. }
  91028. case 248 /* EnumDeclaration */: {
  91029. return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
  91030. if (shouldStripInternal(m))
  91031. return;
  91032. // Rewrite enum values to their constants, if available
  91033. var constValue = resolver.getConstantValue(m);
  91034. return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
  91035. }))));
  91036. }
  91037. }
  91038. // Anything left unhandled is an error, so this should be unreachable
  91039. return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
  91040. function cleanup(node) {
  91041. if (isEnclosingDeclaration(input)) {
  91042. enclosingDeclaration = previousEnclosingDeclaration;
  91043. }
  91044. if (canProdiceDiagnostic) {
  91045. getSymbolAccessibilityDiagnostic = oldDiag;
  91046. }
  91047. if (input.kind === 249 /* ModuleDeclaration */) {
  91048. needsDeclare = previousNeedsDeclare;
  91049. }
  91050. if (node === input) {
  91051. return node;
  91052. }
  91053. return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
  91054. }
  91055. }
  91056. function transformVariableStatement(input) {
  91057. if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
  91058. return;
  91059. var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
  91060. if (!ts.length(nodes))
  91061. return;
  91062. return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
  91063. }
  91064. function recreateBindingPattern(d) {
  91065. return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
  91066. }
  91067. function recreateBindingElement(e) {
  91068. if (e.kind === 215 /* OmittedExpression */) {
  91069. return;
  91070. }
  91071. if (e.name) {
  91072. if (!getBindingNameVisible(e))
  91073. return;
  91074. if (ts.isBindingPattern(e.name)) {
  91075. return recreateBindingPattern(e.name);
  91076. }
  91077. else {
  91078. return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
  91079. }
  91080. }
  91081. }
  91082. function checkName(node) {
  91083. var oldDiag;
  91084. if (!suppressNewDiagnosticContexts) {
  91085. oldDiag = getSymbolAccessibilityDiagnostic;
  91086. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
  91087. }
  91088. errorNameNode = node.name;
  91089. ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
  91090. var decl = node;
  91091. var entityName = decl.name.expression;
  91092. checkEntityNameVisibility(entityName, enclosingDeclaration);
  91093. if (!suppressNewDiagnosticContexts) {
  91094. getSymbolAccessibilityDiagnostic = oldDiag;
  91095. }
  91096. errorNameNode = undefined;
  91097. }
  91098. function shouldStripInternal(node) {
  91099. return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
  91100. }
  91101. function isScopeMarker(node) {
  91102. return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
  91103. }
  91104. function hasScopeMarker(statements) {
  91105. return ts.some(statements, isScopeMarker);
  91106. }
  91107. function ensureModifiers(node) {
  91108. var currentFlags = ts.getModifierFlags(node);
  91109. var newFlags = ensureModifierFlags(node);
  91110. if (currentFlags === newFlags) {
  91111. return node.modifiers;
  91112. }
  91113. return ts.createModifiersFromModifierFlags(newFlags);
  91114. }
  91115. function ensureModifierFlags(node) {
  91116. var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
  91117. var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
  91118. var parentIsFile = node.parent.kind === 290 /* SourceFile */;
  91119. if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
  91120. mask ^= 2 /* Ambient */;
  91121. additions = 0 /* None */;
  91122. }
  91123. return maskModifierFlags(node, mask, additions);
  91124. }
  91125. function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
  91126. var accessorType = getTypeAnnotationFromAccessor(node);
  91127. if (!accessorType && node !== accessors.firstAccessor) {
  91128. accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
  91129. // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message
  91130. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
  91131. }
  91132. if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
  91133. accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
  91134. // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message
  91135. getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
  91136. }
  91137. return accessorType;
  91138. }
  91139. function transformHeritageClauses(nodes) {
  91140. return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
  91141. return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
  91142. })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
  91143. }
  91144. }
  91145. ts.transformDeclarations = transformDeclarations;
  91146. function isAlwaysType(node) {
  91147. if (node.kind === 246 /* InterfaceDeclaration */) {
  91148. return true;
  91149. }
  91150. return false;
  91151. }
  91152. // Elide "public" modifier, as it is the default
  91153. function maskModifiers(node, modifierMask, modifierAdditions) {
  91154. return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
  91155. }
  91156. function maskModifierFlags(node, modifierMask, modifierAdditions) {
  91157. if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
  91158. if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
  91159. var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
  91160. if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
  91161. // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
  91162. // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
  91163. flags ^= 1 /* Export */;
  91164. }
  91165. if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
  91166. flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
  91167. }
  91168. return flags;
  91169. }
  91170. function getTypeAnnotationFromAccessor(accessor) {
  91171. if (accessor) {
  91172. return accessor.kind === 163 /* GetAccessor */
  91173. ? accessor.type // Getter - return type
  91174. : accessor.parameters.length > 0
  91175. ? accessor.parameters[0].type // Setter parameter type
  91176. : undefined;
  91177. }
  91178. }
  91179. function canHaveLiteralInitializer(node) {
  91180. switch (node.kind) {
  91181. case 159 /* PropertyDeclaration */:
  91182. case 158 /* PropertySignature */:
  91183. return !ts.hasModifier(node, 8 /* Private */);
  91184. case 156 /* Parameter */:
  91185. case 242 /* VariableDeclaration */:
  91186. return true;
  91187. }
  91188. return false;
  91189. }
  91190. function isPreservedDeclarationStatement(node) {
  91191. switch (node.kind) {
  91192. case 244 /* FunctionDeclaration */:
  91193. case 249 /* ModuleDeclaration */:
  91194. case 253 /* ImportEqualsDeclaration */:
  91195. case 246 /* InterfaceDeclaration */:
  91196. case 245 /* ClassDeclaration */:
  91197. case 247 /* TypeAliasDeclaration */:
  91198. case 248 /* EnumDeclaration */:
  91199. case 225 /* VariableStatement */:
  91200. case 254 /* ImportDeclaration */:
  91201. case 260 /* ExportDeclaration */:
  91202. case 259 /* ExportAssignment */:
  91203. return true;
  91204. }
  91205. return false;
  91206. }
  91207. function isProcessedComponent(node) {
  91208. switch (node.kind) {
  91209. case 166 /* ConstructSignature */:
  91210. case 162 /* Constructor */:
  91211. case 161 /* MethodDeclaration */:
  91212. case 163 /* GetAccessor */:
  91213. case 164 /* SetAccessor */:
  91214. case 159 /* PropertyDeclaration */:
  91215. case 158 /* PropertySignature */:
  91216. case 160 /* MethodSignature */:
  91217. case 165 /* CallSignature */:
  91218. case 167 /* IndexSignature */:
  91219. case 242 /* VariableDeclaration */:
  91220. case 155 /* TypeParameter */:
  91221. case 216 /* ExpressionWithTypeArguments */:
  91222. case 169 /* TypeReference */:
  91223. case 180 /* ConditionalType */:
  91224. case 170 /* FunctionType */:
  91225. case 171 /* ConstructorType */:
  91226. case 188 /* ImportType */:
  91227. return true;
  91228. }
  91229. return false;
  91230. }
  91231. })(ts || (ts = {}));
  91232. /* @internal */
  91233. var ts;
  91234. (function (ts) {
  91235. function getModuleTransformer(moduleKind) {
  91236. switch (moduleKind) {
  91237. case ts.ModuleKind.ESNext:
  91238. case ts.ModuleKind.ES2020:
  91239. case ts.ModuleKind.ES2015:
  91240. return ts.transformECMAScriptModule;
  91241. case ts.ModuleKind.System:
  91242. return ts.transformSystemModule;
  91243. default:
  91244. return ts.transformModule;
  91245. }
  91246. }
  91247. var TransformationState;
  91248. (function (TransformationState) {
  91249. TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
  91250. TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
  91251. TransformationState[TransformationState["Completed"] = 2] = "Completed";
  91252. TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
  91253. })(TransformationState || (TransformationState = {}));
  91254. var SyntaxKindFeatureFlags;
  91255. (function (SyntaxKindFeatureFlags) {
  91256. SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
  91257. SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
  91258. })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
  91259. ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
  91260. function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
  91261. return {
  91262. scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
  91263. declarationTransformers: getDeclarationTransformers(customTransformers),
  91264. };
  91265. }
  91266. ts.getTransformers = getTransformers;
  91267. function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
  91268. if (emitOnlyDtsFiles)
  91269. return ts.emptyArray;
  91270. var jsx = compilerOptions.jsx;
  91271. var languageVersion = ts.getEmitScriptTarget(compilerOptions);
  91272. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  91273. var transformers = [];
  91274. ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
  91275. transformers.push(ts.transformTypeScript);
  91276. transformers.push(ts.transformClassFields);
  91277. if (jsx === 2 /* React */) {
  91278. transformers.push(ts.transformJsx);
  91279. }
  91280. if (languageVersion < 99 /* ESNext */) {
  91281. transformers.push(ts.transformESNext);
  91282. }
  91283. if (languageVersion < 7 /* ES2020 */) {
  91284. transformers.push(ts.transformES2020);
  91285. }
  91286. if (languageVersion < 6 /* ES2019 */) {
  91287. transformers.push(ts.transformES2019);
  91288. }
  91289. if (languageVersion < 5 /* ES2018 */) {
  91290. transformers.push(ts.transformES2018);
  91291. }
  91292. if (languageVersion < 4 /* ES2017 */) {
  91293. transformers.push(ts.transformES2017);
  91294. }
  91295. if (languageVersion < 3 /* ES2016 */) {
  91296. transformers.push(ts.transformES2016);
  91297. }
  91298. if (languageVersion < 2 /* ES2015 */) {
  91299. transformers.push(ts.transformES2015);
  91300. transformers.push(ts.transformGenerators);
  91301. }
  91302. transformers.push(getModuleTransformer(moduleKind));
  91303. // The ES5 transformer is last so that it can substitute expressions like `exports.default`
  91304. // for ES3.
  91305. if (languageVersion < 1 /* ES5 */) {
  91306. transformers.push(ts.transformES5);
  91307. }
  91308. ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
  91309. return transformers;
  91310. }
  91311. function getDeclarationTransformers(customTransformers) {
  91312. var transformers = [];
  91313. transformers.push(ts.transformDeclarations);
  91314. ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
  91315. return transformers;
  91316. }
  91317. /**
  91318. * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
  91319. */
  91320. function wrapCustomTransformer(transformer) {
  91321. return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
  91322. }
  91323. /**
  91324. * Wrap a transformer factory that may return a custom script or declaration transformer object.
  91325. */
  91326. function wrapCustomTransformerFactory(transformer, handleDefault) {
  91327. return function (context) {
  91328. var customTransformer = transformer(context);
  91329. return typeof customTransformer === "function"
  91330. ? handleDefault(customTransformer)
  91331. : wrapCustomTransformer(customTransformer);
  91332. };
  91333. }
  91334. function wrapScriptTransformerFactory(transformer) {
  91335. return wrapCustomTransformerFactory(transformer, ts.chainBundle);
  91336. }
  91337. function wrapDeclarationTransformerFactory(transformer) {
  91338. return wrapCustomTransformerFactory(transformer, ts.identity);
  91339. }
  91340. function noEmitSubstitution(_hint, node) {
  91341. return node;
  91342. }
  91343. ts.noEmitSubstitution = noEmitSubstitution;
  91344. function noEmitNotification(hint, node, callback) {
  91345. callback(hint, node);
  91346. }
  91347. ts.noEmitNotification = noEmitNotification;
  91348. /**
  91349. * Transforms an array of SourceFiles by passing them through each transformer.
  91350. *
  91351. * @param resolver The emit resolver provided by the checker.
  91352. * @param host The emit host object used to interact with the file system.
  91353. * @param options Compiler options to surface in the `TransformationContext`.
  91354. * @param nodes An array of nodes to transform.
  91355. * @param transforms An array of `TransformerFactory` callbacks.
  91356. * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
  91357. */
  91358. function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
  91359. var enabledSyntaxKindFeatures = new Array(330 /* Count */);
  91360. var lexicalEnvironmentVariableDeclarations;
  91361. var lexicalEnvironmentFunctionDeclarations;
  91362. var lexicalEnvironmentVariableDeclarationsStack = [];
  91363. var lexicalEnvironmentFunctionDeclarationsStack = [];
  91364. var lexicalEnvironmentStackOffset = 0;
  91365. var lexicalEnvironmentSuspended = false;
  91366. var emitHelpers;
  91367. var onSubstituteNode = noEmitSubstitution;
  91368. var onEmitNode = noEmitNotification;
  91369. var state = 0 /* Uninitialized */;
  91370. var diagnostics = [];
  91371. // The transformation context is provided to each transformer as part of transformer
  91372. // initialization.
  91373. var context = {
  91374. getCompilerOptions: function () { return options; },
  91375. getEmitResolver: function () { return resolver; },
  91376. getEmitHost: function () { return host; },
  91377. startLexicalEnvironment: startLexicalEnvironment,
  91378. suspendLexicalEnvironment: suspendLexicalEnvironment,
  91379. resumeLexicalEnvironment: resumeLexicalEnvironment,
  91380. endLexicalEnvironment: endLexicalEnvironment,
  91381. hoistVariableDeclaration: hoistVariableDeclaration,
  91382. hoistFunctionDeclaration: hoistFunctionDeclaration,
  91383. requestEmitHelper: requestEmitHelper,
  91384. readEmitHelpers: readEmitHelpers,
  91385. enableSubstitution: enableSubstitution,
  91386. enableEmitNotification: enableEmitNotification,
  91387. isSubstitutionEnabled: isSubstitutionEnabled,
  91388. isEmitNotificationEnabled: isEmitNotificationEnabled,
  91389. get onSubstituteNode() { return onSubstituteNode; },
  91390. set onSubstituteNode(value) {
  91391. ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
  91392. ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
  91393. onSubstituteNode = value;
  91394. },
  91395. get onEmitNode() { return onEmitNode; },
  91396. set onEmitNode(value) {
  91397. ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
  91398. ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
  91399. onEmitNode = value;
  91400. },
  91401. addDiagnostic: function (diag) {
  91402. diagnostics.push(diag);
  91403. }
  91404. };
  91405. // Ensure the parse tree is clean before applying transformations
  91406. for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
  91407. var node = nodes_4[_i];
  91408. ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
  91409. }
  91410. ts.performance.mark("beforeTransform");
  91411. // Chain together and initialize each transformer.
  91412. var transformersWithContext = transformers.map(function (t) { return t(context); });
  91413. var transformation = function (node) {
  91414. for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
  91415. var transform = transformersWithContext_1[_i];
  91416. node = transform(node);
  91417. }
  91418. return node;
  91419. };
  91420. // prevent modification of transformation hooks.
  91421. state = 1 /* Initialized */;
  91422. // Transform each node.
  91423. var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
  91424. // prevent modification of the lexical environment.
  91425. state = 2 /* Completed */;
  91426. ts.performance.mark("afterTransform");
  91427. ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
  91428. return {
  91429. transformed: transformed,
  91430. substituteNode: substituteNode,
  91431. emitNodeWithNotification: emitNodeWithNotification,
  91432. isEmitNotificationEnabled: isEmitNotificationEnabled,
  91433. dispose: dispose,
  91434. diagnostics: diagnostics
  91435. };
  91436. function transformRoot(node) {
  91437. return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
  91438. }
  91439. /**
  91440. * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
  91441. */
  91442. function enableSubstitution(kind) {
  91443. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
  91444. enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
  91445. }
  91446. /**
  91447. * Determines whether expression substitutions are enabled for the provided node.
  91448. */
  91449. function isSubstitutionEnabled(node) {
  91450. return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
  91451. && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
  91452. }
  91453. /**
  91454. * Emits a node with possible substitution.
  91455. *
  91456. * @param hint A hint as to the intended usage of the node.
  91457. * @param node The node to emit.
  91458. * @param emitCallback The callback used to emit the node or its substitute.
  91459. */
  91460. function substituteNode(hint, node) {
  91461. ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
  91462. return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
  91463. }
  91464. /**
  91465. * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
  91466. */
  91467. function enableEmitNotification(kind) {
  91468. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
  91469. enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
  91470. }
  91471. /**
  91472. * Determines whether before/after emit notifications should be raised in the pretty
  91473. * printer when it emits a node.
  91474. */
  91475. function isEmitNotificationEnabled(node) {
  91476. return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
  91477. || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
  91478. }
  91479. /**
  91480. * Emits a node with possible emit notification.
  91481. *
  91482. * @param hint A hint as to the intended usage of the node.
  91483. * @param node The node to emit.
  91484. * @param emitCallback The callback used to emit the node.
  91485. */
  91486. function emitNodeWithNotification(hint, node, emitCallback) {
  91487. ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
  91488. if (node) {
  91489. // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
  91490. // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
  91491. if (isEmitNotificationEnabled(node)) {
  91492. onEmitNode(hint, node, emitCallback);
  91493. }
  91494. else {
  91495. emitCallback(hint, node);
  91496. }
  91497. }
  91498. }
  91499. /**
  91500. * Records a hoisted variable declaration for the provided name within a lexical environment.
  91501. */
  91502. function hoistVariableDeclaration(name) {
  91503. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
  91504. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
  91505. var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
  91506. if (!lexicalEnvironmentVariableDeclarations) {
  91507. lexicalEnvironmentVariableDeclarations = [decl];
  91508. }
  91509. else {
  91510. lexicalEnvironmentVariableDeclarations.push(decl);
  91511. }
  91512. }
  91513. /**
  91514. * Records a hoisted function declaration within a lexical environment.
  91515. */
  91516. function hoistFunctionDeclaration(func) {
  91517. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
  91518. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
  91519. if (!lexicalEnvironmentFunctionDeclarations) {
  91520. lexicalEnvironmentFunctionDeclarations = [func];
  91521. }
  91522. else {
  91523. lexicalEnvironmentFunctionDeclarations.push(func);
  91524. }
  91525. }
  91526. /**
  91527. * Starts a new lexical environment. Any existing hoisted variable or function declarations
  91528. * are pushed onto a stack, and the related storage variables are reset.
  91529. */
  91530. function startLexicalEnvironment() {
  91531. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
  91532. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
  91533. ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
  91534. // Save the current lexical environment. Rather than resizing the array we adjust the
  91535. // stack size variable. This allows us to reuse existing array slots we've
  91536. // already allocated between transformations to avoid allocation and GC overhead during
  91537. // transformation.
  91538. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
  91539. lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
  91540. lexicalEnvironmentStackOffset++;
  91541. lexicalEnvironmentVariableDeclarations = undefined;
  91542. lexicalEnvironmentFunctionDeclarations = undefined;
  91543. }
  91544. /** Suspends the current lexical environment, usually after visiting a parameter list. */
  91545. function suspendLexicalEnvironment() {
  91546. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
  91547. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
  91548. ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
  91549. lexicalEnvironmentSuspended = true;
  91550. }
  91551. /** Resumes a suspended lexical environment, usually before visiting a function body. */
  91552. function resumeLexicalEnvironment() {
  91553. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
  91554. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
  91555. ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
  91556. lexicalEnvironmentSuspended = false;
  91557. }
  91558. /**
  91559. * Ends a lexical environment. The previous set of hoisted declarations are restored and
  91560. * any hoisted declarations added in this environment are returned.
  91561. */
  91562. function endLexicalEnvironment() {
  91563. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
  91564. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
  91565. ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
  91566. var statements;
  91567. if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) {
  91568. if (lexicalEnvironmentFunctionDeclarations) {
  91569. statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
  91570. }
  91571. if (lexicalEnvironmentVariableDeclarations) {
  91572. var statement = ts.createVariableStatement(
  91573. /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
  91574. ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
  91575. if (!statements) {
  91576. statements = [statement];
  91577. }
  91578. else {
  91579. statements.push(statement);
  91580. }
  91581. }
  91582. }
  91583. // Restore the previous lexical environment.
  91584. lexicalEnvironmentStackOffset--;
  91585. lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
  91586. lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
  91587. if (lexicalEnvironmentStackOffset === 0) {
  91588. lexicalEnvironmentVariableDeclarationsStack = [];
  91589. lexicalEnvironmentFunctionDeclarationsStack = [];
  91590. }
  91591. return statements;
  91592. }
  91593. function requestEmitHelper(helper) {
  91594. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
  91595. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
  91596. ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
  91597. emitHelpers = ts.append(emitHelpers, helper);
  91598. }
  91599. function readEmitHelpers() {
  91600. ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
  91601. ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
  91602. var helpers = emitHelpers;
  91603. emitHelpers = undefined;
  91604. return helpers;
  91605. }
  91606. function dispose() {
  91607. if (state < 3 /* Disposed */) {
  91608. // Clean up emit nodes on parse tree
  91609. for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
  91610. var node = nodes_5[_i];
  91611. ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
  91612. }
  91613. // Release references to external entries for GC purposes.
  91614. lexicalEnvironmentVariableDeclarations = undefined;
  91615. lexicalEnvironmentVariableDeclarationsStack = undefined;
  91616. lexicalEnvironmentFunctionDeclarations = undefined;
  91617. lexicalEnvironmentFunctionDeclarationsStack = undefined;
  91618. onSubstituteNode = undefined;
  91619. onEmitNode = undefined;
  91620. emitHelpers = undefined;
  91621. // Prevent further use of the transformation result.
  91622. state = 3 /* Disposed */;
  91623. }
  91624. }
  91625. }
  91626. ts.transformNodes = transformNodes;
  91627. })(ts || (ts = {}));
  91628. var ts;
  91629. (function (ts) {
  91630. var brackets = createBracketsMap();
  91631. var syntheticParent = { pos: -1, end: -1 };
  91632. /*@internal*/
  91633. function isBuildInfoFile(file) {
  91634. return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
  91635. }
  91636. ts.isBuildInfoFile = isBuildInfoFile;
  91637. /*@internal*/
  91638. /**
  91639. * Iterates over the source files that are expected to have an emit output.
  91640. *
  91641. * @param host An EmitHost.
  91642. * @param action The action to execute.
  91643. * @param sourceFilesOrTargetSourceFile
  91644. * If an array, the full list of source files to emit.
  91645. * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
  91646. */
  91647. function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
  91648. if (forceDtsEmit === void 0) { forceDtsEmit = false; }
  91649. var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
  91650. var options = host.getCompilerOptions();
  91651. if (options.outFile || options.out) {
  91652. var prepends = host.getPrependNodes();
  91653. if (sourceFiles.length || prepends.length) {
  91654. var bundle = ts.createBundle(sourceFiles, prepends);
  91655. var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
  91656. if (result) {
  91657. return result;
  91658. }
  91659. }
  91660. }
  91661. else {
  91662. if (!onlyBuildInfo) {
  91663. for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
  91664. var sourceFile = sourceFiles_1[_a];
  91665. var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
  91666. if (result) {
  91667. return result;
  91668. }
  91669. }
  91670. }
  91671. if (includeBuildInfo) {
  91672. var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
  91673. if (buildInfoPath)
  91674. return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
  91675. }
  91676. }
  91677. }
  91678. ts.forEachEmittedFile = forEachEmittedFile;
  91679. function getTsBuildInfoEmitOutputFilePath(options) {
  91680. var configFile = options.configFilePath;
  91681. if (!ts.isIncrementalCompilation(options))
  91682. return undefined;
  91683. if (options.tsBuildInfoFile)
  91684. return options.tsBuildInfoFile;
  91685. var outPath = options.outFile || options.out;
  91686. var buildInfoExtensionLess;
  91687. if (outPath) {
  91688. buildInfoExtensionLess = ts.removeFileExtension(outPath);
  91689. }
  91690. else {
  91691. if (!configFile)
  91692. return undefined;
  91693. var configFileExtensionLess = ts.removeFileExtension(configFile);
  91694. buildInfoExtensionLess = options.outDir ?
  91695. options.rootDir ?
  91696. ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
  91697. ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
  91698. configFileExtensionLess;
  91699. }
  91700. return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
  91701. }
  91702. ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
  91703. /*@internal*/
  91704. function getOutputPathsForBundle(options, forceDtsPaths) {
  91705. var outPath = options.outFile || options.out;
  91706. var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
  91707. var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
  91708. var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
  91709. var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
  91710. var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
  91711. return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
  91712. }
  91713. ts.getOutputPathsForBundle = getOutputPathsForBundle;
  91714. /*@internal*/
  91715. function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
  91716. var options = host.getCompilerOptions();
  91717. if (sourceFile.kind === 291 /* Bundle */) {
  91718. return getOutputPathsForBundle(options, forceDtsPaths);
  91719. }
  91720. else {
  91721. var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
  91722. var isJsonFile = ts.isJsonSourceFile(sourceFile);
  91723. // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
  91724. var isJsonEmittedToSameLocation = isJsonFile &&
  91725. ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
  91726. var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
  91727. var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
  91728. var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
  91729. var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
  91730. return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
  91731. }
  91732. }
  91733. ts.getOutputPathsFor = getOutputPathsFor;
  91734. function getSourceMapFilePath(jsFilePath, options) {
  91735. return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
  91736. }
  91737. // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
  91738. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
  91739. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
  91740. /* @internal */
  91741. function getOutputExtension(sourceFile, options) {
  91742. if (ts.isJsonSourceFile(sourceFile)) {
  91743. return ".json" /* Json */;
  91744. }
  91745. if (options.jsx === 1 /* Preserve */) {
  91746. if (ts.isSourceFileJS(sourceFile)) {
  91747. if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
  91748. return ".jsx" /* Jsx */;
  91749. }
  91750. }
  91751. else if (sourceFile.languageVariant === 1 /* JSX */) {
  91752. // TypeScript source file preserving JSX syntax
  91753. return ".jsx" /* Jsx */;
  91754. }
  91755. }
  91756. return ".js" /* Js */;
  91757. }
  91758. ts.getOutputExtension = getOutputExtension;
  91759. function rootDirOfOptions(configFile) {
  91760. return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
  91761. }
  91762. function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
  91763. return outputDir ?
  91764. ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
  91765. inputFileName;
  91766. }
  91767. /* @internal */
  91768. function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
  91769. ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
  91770. return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
  91771. }
  91772. ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
  91773. function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
  91774. if (configFile.options.emitDeclarationOnly)
  91775. return undefined;
  91776. var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
  91777. var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
  91778. ".json" /* Json */ :
  91779. ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
  91780. ".jsx" /* Jsx */ :
  91781. ".js" /* Js */);
  91782. return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
  91783. outputFileName :
  91784. undefined;
  91785. }
  91786. function createAddOutput() {
  91787. var outputs;
  91788. return { addOutput: addOutput, getOutputs: getOutputs };
  91789. function addOutput(path) {
  91790. if (path) {
  91791. (outputs || (outputs = [])).push(path);
  91792. }
  91793. }
  91794. function getOutputs() {
  91795. return outputs || ts.emptyArray;
  91796. }
  91797. }
  91798. function getSingleOutputFileNames(configFile, addOutput) {
  91799. var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
  91800. addOutput(jsFilePath);
  91801. addOutput(sourceMapFilePath);
  91802. addOutput(declarationFilePath);
  91803. addOutput(declarationMapPath);
  91804. addOutput(buildInfoPath);
  91805. }
  91806. function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
  91807. if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
  91808. return;
  91809. var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
  91810. addOutput(js);
  91811. if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
  91812. return;
  91813. if (js && configFile.options.sourceMap) {
  91814. addOutput(js + ".map");
  91815. }
  91816. if (ts.getEmitDeclarations(configFile.options)) {
  91817. var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
  91818. addOutput(dts);
  91819. if (configFile.options.declarationMap) {
  91820. addOutput(dts + ".map");
  91821. }
  91822. }
  91823. }
  91824. /*@internal*/
  91825. function getAllProjectOutputs(configFile, ignoreCase) {
  91826. var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
  91827. if (configFile.options.outFile || configFile.options.out) {
  91828. getSingleOutputFileNames(configFile, addOutput);
  91829. }
  91830. else {
  91831. for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
  91832. var inputFileName = _c[_b];
  91833. getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
  91834. }
  91835. addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
  91836. }
  91837. return getOutputs();
  91838. }
  91839. ts.getAllProjectOutputs = getAllProjectOutputs;
  91840. function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
  91841. inputFileName = ts.normalizePath(inputFileName);
  91842. ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
  91843. var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
  91844. if (commandLine.options.outFile || commandLine.options.out) {
  91845. getSingleOutputFileNames(commandLine, addOutput);
  91846. }
  91847. else {
  91848. getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
  91849. }
  91850. return getOutputs();
  91851. }
  91852. ts.getOutputFileNames = getOutputFileNames;
  91853. /*@internal*/
  91854. function getFirstProjectOutput(configFile, ignoreCase) {
  91855. if (configFile.options.outFile || configFile.options.out) {
  91856. var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
  91857. return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
  91858. }
  91859. for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
  91860. var inputFileName = _b[_a];
  91861. if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
  91862. continue;
  91863. var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
  91864. if (jsFilePath)
  91865. return jsFilePath;
  91866. if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
  91867. continue;
  91868. if (ts.getEmitDeclarations(configFile.options)) {
  91869. return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
  91870. }
  91871. }
  91872. var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
  91873. if (buildInfoPath)
  91874. return buildInfoPath;
  91875. return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
  91876. }
  91877. ts.getFirstProjectOutput = getFirstProjectOutput;
  91878. /*@internal*/
  91879. // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
  91880. function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
  91881. var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
  91882. var compilerOptions = host.getCompilerOptions();
  91883. var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
  91884. var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
  91885. var emitterDiagnostics = ts.createDiagnosticCollection();
  91886. var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
  91887. var writer = ts.createTextWriter(newLine);
  91888. var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
  91889. var bundleBuildInfo;
  91890. var emitSkipped = false;
  91891. var exportedModulesFromDeclarationEmit;
  91892. // Emit each output file
  91893. enter();
  91894. forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
  91895. exit();
  91896. return {
  91897. emitSkipped: emitSkipped,
  91898. diagnostics: emitterDiagnostics.getDiagnostics(),
  91899. emittedFiles: emittedFilesList,
  91900. sourceMaps: sourceMapDataList,
  91901. exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
  91902. };
  91903. function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
  91904. var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
  91905. var buildInfoDirectory;
  91906. if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
  91907. buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
  91908. bundleBuildInfo = {
  91909. commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
  91910. sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
  91911. };
  91912. }
  91913. emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
  91914. emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
  91915. emitBuildInfo(bundleBuildInfo, buildInfoPath);
  91916. if (!emitSkipped && emittedFilesList) {
  91917. if (!emitOnlyDtsFiles) {
  91918. if (jsFilePath) {
  91919. emittedFilesList.push(jsFilePath);
  91920. }
  91921. if (sourceMapFilePath) {
  91922. emittedFilesList.push(sourceMapFilePath);
  91923. }
  91924. if (buildInfoPath) {
  91925. emittedFilesList.push(buildInfoPath);
  91926. }
  91927. }
  91928. if (declarationFilePath) {
  91929. emittedFilesList.push(declarationFilePath);
  91930. }
  91931. if (declarationMapPath) {
  91932. emittedFilesList.push(declarationMapPath);
  91933. }
  91934. }
  91935. function relativeToBuildInfo(path) {
  91936. return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
  91937. }
  91938. }
  91939. function emitBuildInfo(bundle, buildInfoPath) {
  91940. // Write build information if applicable
  91941. if (!buildInfoPath || targetSourceFile || emitSkipped)
  91942. return;
  91943. var program = host.getProgramBuildInfo();
  91944. if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
  91945. emitSkipped = true;
  91946. return;
  91947. }
  91948. var version = ts.version; // Extracted into a const so the form is stable between namespace and module
  91949. ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
  91950. }
  91951. function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
  91952. if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
  91953. return;
  91954. }
  91955. // Make sure not to write js file and source map file if any of them cannot be written
  91956. if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
  91957. emitSkipped = true;
  91958. return;
  91959. }
  91960. // Transform the source files
  91961. var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
  91962. var printerOptions = {
  91963. removeComments: compilerOptions.removeComments,
  91964. newLine: compilerOptions.newLine,
  91965. noEmitHelpers: compilerOptions.noEmitHelpers,
  91966. module: compilerOptions.module,
  91967. target: compilerOptions.target,
  91968. sourceMap: compilerOptions.sourceMap,
  91969. inlineSourceMap: compilerOptions.inlineSourceMap,
  91970. inlineSources: compilerOptions.inlineSources,
  91971. extendedDiagnostics: compilerOptions.extendedDiagnostics,
  91972. writeBundleFileInfo: !!bundleBuildInfo,
  91973. relativeToBuildInfo: relativeToBuildInfo
  91974. };
  91975. // Create a printer to print the nodes
  91976. var printer = createPrinter(printerOptions, {
  91977. // resolver hooks
  91978. hasGlobalName: resolver.hasGlobalName,
  91979. // transform hooks
  91980. onEmitNode: transform.emitNodeWithNotification,
  91981. isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
  91982. substituteNode: transform.substituteNode,
  91983. });
  91984. ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
  91985. printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
  91986. // Clean up emit nodes on parse tree
  91987. transform.dispose();
  91988. if (bundleBuildInfo)
  91989. bundleBuildInfo.js = printer.bundleFileInfo;
  91990. }
  91991. function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
  91992. if (!sourceFileOrBundle)
  91993. return;
  91994. if (!declarationFilePath) {
  91995. if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
  91996. emitSkipped = true;
  91997. return;
  91998. }
  91999. var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
  92000. var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
  92001. // Setup and perform the transformation to retrieve declarations from the input files
  92002. var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
  92003. if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
  92004. // Checker wont collect the linked aliases since thats only done when declaration is enabled.
  92005. // Do that here when emitting only dts files
  92006. filesForEmit.forEach(collectLinkedAliases);
  92007. }
  92008. var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
  92009. if (ts.length(declarationTransform.diagnostics)) {
  92010. for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
  92011. var diagnostic = _b[_a];
  92012. emitterDiagnostics.add(diagnostic);
  92013. }
  92014. }
  92015. var printerOptions = {
  92016. removeComments: compilerOptions.removeComments,
  92017. newLine: compilerOptions.newLine,
  92018. noEmitHelpers: true,
  92019. module: compilerOptions.module,
  92020. target: compilerOptions.target,
  92021. sourceMap: compilerOptions.sourceMap,
  92022. inlineSourceMap: compilerOptions.inlineSourceMap,
  92023. extendedDiagnostics: compilerOptions.extendedDiagnostics,
  92024. onlyPrintJsDocStyle: true,
  92025. writeBundleFileInfo: !!bundleBuildInfo,
  92026. recordInternalSection: !!bundleBuildInfo,
  92027. relativeToBuildInfo: relativeToBuildInfo
  92028. };
  92029. var declarationPrinter = createPrinter(printerOptions, {
  92030. // resolver hooks
  92031. hasGlobalName: resolver.hasGlobalName,
  92032. // transform hooks
  92033. onEmitNode: declarationTransform.emitNodeWithNotification,
  92034. isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
  92035. substituteNode: declarationTransform.substituteNode,
  92036. });
  92037. var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
  92038. emitSkipped = emitSkipped || declBlocked;
  92039. if (!declBlocked || forceDtsEmit) {
  92040. ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
  92041. printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
  92042. sourceMap: compilerOptions.declarationMap,
  92043. sourceRoot: compilerOptions.sourceRoot,
  92044. mapRoot: compilerOptions.mapRoot,
  92045. extendedDiagnostics: compilerOptions.extendedDiagnostics,
  92046. });
  92047. if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
  92048. var sourceFile = declarationTransform.transformed[0];
  92049. exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
  92050. }
  92051. }
  92052. declarationTransform.dispose();
  92053. if (bundleBuildInfo)
  92054. bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
  92055. }
  92056. function collectLinkedAliases(node) {
  92057. if (ts.isExportAssignment(node)) {
  92058. if (node.expression.kind === 75 /* Identifier */) {
  92059. resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
  92060. }
  92061. return;
  92062. }
  92063. else if (ts.isExportSpecifier(node)) {
  92064. resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
  92065. return;
  92066. }
  92067. ts.forEachChild(node, collectLinkedAliases);
  92068. }
  92069. function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
  92070. var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
  92071. var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
  92072. var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
  92073. var sourceMapGenerator;
  92074. if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
  92075. sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
  92076. }
  92077. if (bundle) {
  92078. printer.writeBundle(bundle, writer, sourceMapGenerator);
  92079. }
  92080. else {
  92081. printer.writeFile(sourceFile, writer, sourceMapGenerator);
  92082. }
  92083. if (sourceMapGenerator) {
  92084. if (sourceMapDataList) {
  92085. sourceMapDataList.push({
  92086. inputSourceFileNames: sourceMapGenerator.getSources(),
  92087. sourceMap: sourceMapGenerator.toJSON()
  92088. });
  92089. }
  92090. var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
  92091. if (sourceMappingURL) {
  92092. if (!writer.isAtStartOfLine())
  92093. writer.rawWrite(newLine);
  92094. writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
  92095. }
  92096. // Write the source map
  92097. if (sourceMapFilePath) {
  92098. var sourceMap = sourceMapGenerator.toString();
  92099. ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
  92100. }
  92101. }
  92102. else {
  92103. writer.writeLine();
  92104. }
  92105. // Write the output file
  92106. ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
  92107. // Reset state
  92108. writer.clear();
  92109. }
  92110. function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
  92111. return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
  92112. && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
  92113. }
  92114. function getSourceRoot(mapOptions) {
  92115. // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
  92116. // relative paths of the sources list in the sourcemap
  92117. var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
  92118. return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
  92119. }
  92120. function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
  92121. if (mapOptions.sourceRoot)
  92122. return host.getCommonSourceDirectory();
  92123. if (mapOptions.mapRoot) {
  92124. var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
  92125. if (sourceFile) {
  92126. // For modules or multiple emit files the mapRoot will have directory structure like the sources
  92127. // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
  92128. sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
  92129. }
  92130. if (ts.getRootLength(sourceMapDir) === 0) {
  92131. // The relative paths are relative to the common directory
  92132. sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
  92133. }
  92134. return sourceMapDir;
  92135. }
  92136. return ts.getDirectoryPath(ts.normalizePath(filePath));
  92137. }
  92138. function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
  92139. if (mapOptions.inlineSourceMap) {
  92140. // Encode the sourceMap into the sourceMap url
  92141. var sourceMapText = sourceMapGenerator.toString();
  92142. var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
  92143. return "data:application/json;base64," + base64SourceMapText;
  92144. }
  92145. var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath)));
  92146. if (mapOptions.mapRoot) {
  92147. var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
  92148. if (sourceFile) {
  92149. // For modules or multiple emit files the mapRoot will have directory structure like the sources
  92150. // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
  92151. sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
  92152. }
  92153. if (ts.getRootLength(sourceMapDir) === 0) {
  92154. // The relative paths are relative to the common directory
  92155. sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
  92156. return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
  92157. ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
  92158. host.getCurrentDirectory(), host.getCanonicalFileName,
  92159. /*isAbsolutePathAnUrl*/ true);
  92160. }
  92161. else {
  92162. return ts.combinePaths(sourceMapDir, sourceMapFile);
  92163. }
  92164. }
  92165. return sourceMapFile;
  92166. }
  92167. }
  92168. ts.emitFiles = emitFiles;
  92169. /*@internal*/
  92170. function getBuildInfoText(buildInfo) {
  92171. return JSON.stringify(buildInfo, undefined, 2);
  92172. }
  92173. ts.getBuildInfoText = getBuildInfoText;
  92174. /*@internal*/
  92175. function getBuildInfo(buildInfoText) {
  92176. return JSON.parse(buildInfoText);
  92177. }
  92178. ts.getBuildInfo = getBuildInfo;
  92179. /*@internal*/
  92180. ts.notImplementedResolver = {
  92181. hasGlobalName: ts.notImplemented,
  92182. getReferencedExportContainer: ts.notImplemented,
  92183. getReferencedImportDeclaration: ts.notImplemented,
  92184. getReferencedDeclarationWithCollidingName: ts.notImplemented,
  92185. isDeclarationWithCollidingName: ts.notImplemented,
  92186. isValueAliasDeclaration: ts.notImplemented,
  92187. isReferencedAliasDeclaration: ts.notImplemented,
  92188. isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
  92189. getNodeCheckFlags: ts.notImplemented,
  92190. isDeclarationVisible: ts.notImplemented,
  92191. isLateBound: function (_node) { return false; },
  92192. collectLinkedAliases: ts.notImplemented,
  92193. isImplementationOfOverload: ts.notImplemented,
  92194. isRequiredInitializedParameter: ts.notImplemented,
  92195. isOptionalUninitializedParameterProperty: ts.notImplemented,
  92196. isExpandoFunctionDeclaration: ts.notImplemented,
  92197. getPropertiesOfContainerFunction: ts.notImplemented,
  92198. createTypeOfDeclaration: ts.notImplemented,
  92199. createReturnTypeOfSignatureDeclaration: ts.notImplemented,
  92200. createTypeOfExpression: ts.notImplemented,
  92201. createLiteralConstValue: ts.notImplemented,
  92202. isSymbolAccessible: ts.notImplemented,
  92203. isEntityNameVisible: ts.notImplemented,
  92204. // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
  92205. getConstantValue: ts.notImplemented,
  92206. getReferencedValueDeclaration: ts.notImplemented,
  92207. getTypeReferenceSerializationKind: ts.notImplemented,
  92208. isOptionalParameter: ts.notImplemented,
  92209. moduleExportsSomeValue: ts.notImplemented,
  92210. isArgumentsLocalBinding: ts.notImplemented,
  92211. getExternalModuleFileFromDeclaration: ts.notImplemented,
  92212. getTypeReferenceDirectivesForEntityName: ts.notImplemented,
  92213. getTypeReferenceDirectivesForSymbol: ts.notImplemented,
  92214. isLiteralConstDeclaration: ts.notImplemented,
  92215. getJsxFactoryEntity: ts.notImplemented,
  92216. getAllAccessorDeclarations: ts.notImplemented,
  92217. getSymbolOfExternalModuleSpecifier: ts.notImplemented,
  92218. isBindingCapturedByNode: ts.notImplemented,
  92219. getDeclarationStatementsForSourceFile: ts.notImplemented,
  92220. };
  92221. function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
  92222. var sourceFiles = bundle.sourceFiles.map(function (fileName) {
  92223. var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
  92224. sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
  92225. sourceFile.text = "";
  92226. sourceFile.statements = ts.createNodeArray();
  92227. return sourceFile;
  92228. });
  92229. var jsBundle = ts.Debug.assertDefined(bundle.js);
  92230. ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
  92231. var sourceFile = sourceFiles[prologueInfo.file];
  92232. sourceFile.text = prologueInfo.text;
  92233. sourceFile.end = prologueInfo.text.length;
  92234. sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
  92235. var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
  92236. statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
  92237. statement.expression.text = directive.expression.text;
  92238. return statement;
  92239. }));
  92240. });
  92241. return sourceFiles;
  92242. }
  92243. /*@internal*/
  92244. function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
  92245. var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
  92246. var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
  92247. if (!buildInfoText)
  92248. return buildInfoPath;
  92249. var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
  92250. if (!jsFileText)
  92251. return jsFilePath;
  92252. var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
  92253. // error if no source map or for now if inline sourcemap
  92254. if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
  92255. return sourceMapFilePath || "inline sourcemap decoding";
  92256. // read declaration text
  92257. var declarationText = declarationFilePath && host.readFile(declarationFilePath);
  92258. if (declarationFilePath && !declarationText)
  92259. return declarationFilePath;
  92260. var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
  92261. // error if no source map or for now if inline sourcemap
  92262. if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
  92263. return declarationMapPath || "inline sourcemap decoding";
  92264. var buildInfo = getBuildInfo(buildInfoText);
  92265. if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
  92266. return buildInfoPath;
  92267. var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
  92268. var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
  92269. /*onlyOwnText*/ true);
  92270. var outputFiles = [];
  92271. var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
  92272. var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
  92273. var emitHost = {
  92274. getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
  92275. getCanonicalFileName: host.getCanonicalFileName,
  92276. getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
  92277. getCompilerOptions: function () { return config.options; },
  92278. getCurrentDirectory: function () { return host.getCurrentDirectory(); },
  92279. getNewLine: function () { return host.getNewLine(); },
  92280. getSourceFile: ts.returnUndefined,
  92281. getSourceFileByPath: ts.returnUndefined,
  92282. getSourceFiles: function () { return sourceFilesForJsEmit; },
  92283. getLibFileFromReference: ts.notImplemented,
  92284. isSourceFileFromExternalLibrary: ts.returnFalse,
  92285. getResolvedProjectReferenceToRedirect: ts.returnUndefined,
  92286. isSourceOfProjectReferenceRedirect: ts.returnFalse,
  92287. writeFile: function (name, text, writeByteOrderMark) {
  92288. switch (name) {
  92289. case jsFilePath:
  92290. if (jsFileText === text)
  92291. return;
  92292. break;
  92293. case sourceMapFilePath:
  92294. if (sourceMapText === text)
  92295. return;
  92296. break;
  92297. case buildInfoPath:
  92298. var newBuildInfo = getBuildInfo(text);
  92299. newBuildInfo.program = buildInfo.program;
  92300. // Update sourceFileInfo
  92301. var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
  92302. newBuildInfo.bundle.js.sources = js.sources;
  92303. if (dts) {
  92304. newBuildInfo.bundle.dts.sources = dts.sources;
  92305. }
  92306. newBuildInfo.bundle.sourceFiles = sourceFiles;
  92307. outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
  92308. return;
  92309. case declarationFilePath:
  92310. if (declarationText === text)
  92311. return;
  92312. break;
  92313. case declarationMapPath:
  92314. if (declarationMapText === text)
  92315. return;
  92316. break;
  92317. default:
  92318. ts.Debug.fail("Unexpected path: " + name);
  92319. }
  92320. outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
  92321. },
  92322. isEmitBlocked: ts.returnFalse,
  92323. readFile: function (f) { return host.readFile(f); },
  92324. fileExists: function (f) { return host.fileExists(f); },
  92325. directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
  92326. useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
  92327. getProgramBuildInfo: ts.returnUndefined,
  92328. getSourceFileFromReference: ts.returnUndefined,
  92329. redirectTargetsMap: ts.createMultiMap()
  92330. };
  92331. emitFiles(ts.notImplementedResolver, emitHost,
  92332. /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
  92333. return outputFiles;
  92334. }
  92335. ts.emitUsingBuildInfo = emitUsingBuildInfo;
  92336. var PipelinePhase;
  92337. (function (PipelinePhase) {
  92338. PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
  92339. PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
  92340. PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
  92341. PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
  92342. PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
  92343. })(PipelinePhase || (PipelinePhase = {}));
  92344. function createPrinter(printerOptions, handlers) {
  92345. if (printerOptions === void 0) { printerOptions = {}; }
  92346. if (handlers === void 0) { handlers = {}; }
  92347. var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
  92348. var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
  92349. var newLine = ts.getNewLineCharacter(printerOptions);
  92350. var moduleKind = ts.getEmitModuleKind(printerOptions);
  92351. var bundledHelpers = ts.createMap();
  92352. var currentSourceFile;
  92353. var nodeIdToGeneratedName; // Map of generated names for specific nodes.
  92354. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
  92355. var generatedNames; // Set of names generated by the NameGenerator.
  92356. var tempFlagsStack; // Stack of enclosing name generation scopes.
  92357. var tempFlags; // TempFlags for the current name generation scope.
  92358. var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
  92359. var reservedNames; // TempFlags to reserve in nested name generation scopes.
  92360. var writer;
  92361. var ownWriter; // Reusable `EmitTextWriter` for basic printing.
  92362. var write = writeBase;
  92363. var isOwnFileEmit;
  92364. var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
  92365. var relativeToBuildInfo = bundleFileInfo ? ts.Debug.assertDefined(printerOptions.relativeToBuildInfo) : undefined;
  92366. var recordInternalSection = printerOptions.recordInternalSection;
  92367. var sourceFileTextPos = 0;
  92368. var sourceFileTextKind = "text" /* Text */;
  92369. // Source Maps
  92370. var sourceMapsDisabled = true;
  92371. var sourceMapGenerator;
  92372. var sourceMapSource;
  92373. var sourceMapSourceIndex = -1;
  92374. // Comments
  92375. var containerPos = -1;
  92376. var containerEnd = -1;
  92377. var declarationListContainerEnd = -1;
  92378. var currentLineMap;
  92379. var detachedCommentsInfo;
  92380. var hasWrittenComment = false;
  92381. var commentsDisabled = !!printerOptions.removeComments;
  92382. var lastNode;
  92383. var lastSubstitution;
  92384. var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
  92385. reset();
  92386. return {
  92387. // public API
  92388. printNode: printNode,
  92389. printList: printList,
  92390. printFile: printFile,
  92391. printBundle: printBundle,
  92392. // internal API
  92393. writeNode: writeNode,
  92394. writeList: writeList,
  92395. writeFile: writeFile,
  92396. writeBundle: writeBundle,
  92397. bundleFileInfo: bundleFileInfo
  92398. };
  92399. function printNode(hint, node, sourceFile) {
  92400. switch (hint) {
  92401. case 0 /* SourceFile */:
  92402. ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
  92403. break;
  92404. case 2 /* IdentifierName */:
  92405. ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
  92406. break;
  92407. case 1 /* Expression */:
  92408. ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
  92409. break;
  92410. }
  92411. switch (node.kind) {
  92412. case 290 /* SourceFile */: return printFile(node);
  92413. case 291 /* Bundle */: return printBundle(node);
  92414. case 292 /* UnparsedSource */: return printUnparsedSource(node);
  92415. }
  92416. writeNode(hint, node, sourceFile, beginPrint());
  92417. return endPrint();
  92418. }
  92419. function printList(format, nodes, sourceFile) {
  92420. writeList(format, nodes, sourceFile, beginPrint());
  92421. return endPrint();
  92422. }
  92423. function printBundle(bundle) {
  92424. writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
  92425. return endPrint();
  92426. }
  92427. function printFile(sourceFile) {
  92428. writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
  92429. return endPrint();
  92430. }
  92431. function printUnparsedSource(unparsed) {
  92432. writeUnparsedSource(unparsed, beginPrint());
  92433. return endPrint();
  92434. }
  92435. function writeNode(hint, node, sourceFile, output) {
  92436. var previousWriter = writer;
  92437. setWriter(output, /*_sourceMapGenerator*/ undefined);
  92438. print(hint, node, sourceFile);
  92439. reset();
  92440. writer = previousWriter;
  92441. }
  92442. function writeList(format, nodes, sourceFile, output) {
  92443. var previousWriter = writer;
  92444. setWriter(output, /*_sourceMapGenerator*/ undefined);
  92445. if (sourceFile) {
  92446. setSourceFile(sourceFile);
  92447. }
  92448. emitList(syntheticParent, nodes, format);
  92449. reset();
  92450. writer = previousWriter;
  92451. }
  92452. function getTextPosWithWriteLine() {
  92453. return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
  92454. }
  92455. function updateOrPushBundleFileTextLike(pos, end, kind) {
  92456. var last = ts.lastOrUndefined(bundleFileInfo.sections);
  92457. if (last && last.kind === kind) {
  92458. last.end = end;
  92459. }
  92460. else {
  92461. bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
  92462. }
  92463. }
  92464. function recordBundleFileInternalSectionStart(node) {
  92465. if (recordInternalSection &&
  92466. bundleFileInfo &&
  92467. currentSourceFile &&
  92468. (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
  92469. ts.isInternalDeclaration(node, currentSourceFile) &&
  92470. sourceFileTextKind !== "internal" /* Internal */) {
  92471. var prevSourceFileTextKind = sourceFileTextKind;
  92472. recordBundleFileTextLikeSection(writer.getTextPos());
  92473. sourceFileTextPos = getTextPosWithWriteLine();
  92474. sourceFileTextKind = "internal" /* Internal */;
  92475. return prevSourceFileTextKind;
  92476. }
  92477. return undefined;
  92478. }
  92479. function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
  92480. if (prevSourceFileTextKind) {
  92481. recordBundleFileTextLikeSection(writer.getTextPos());
  92482. sourceFileTextPos = getTextPosWithWriteLine();
  92483. sourceFileTextKind = prevSourceFileTextKind;
  92484. }
  92485. }
  92486. function recordBundleFileTextLikeSection(end) {
  92487. if (sourceFileTextPos < end) {
  92488. updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
  92489. return true;
  92490. }
  92491. return false;
  92492. }
  92493. function writeBundle(bundle, output, sourceMapGenerator) {
  92494. var _a;
  92495. isOwnFileEmit = false;
  92496. var previousWriter = writer;
  92497. setWriter(output, sourceMapGenerator);
  92498. emitShebangIfNeeded(bundle);
  92499. emitPrologueDirectivesIfNeeded(bundle);
  92500. emitHelpers(bundle);
  92501. emitSyntheticTripleSlashReferencesIfNeeded(bundle);
  92502. for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
  92503. var prepend = _c[_b];
  92504. writeLine();
  92505. var pos = writer.getTextPos();
  92506. var savedSections = bundleFileInfo && bundleFileInfo.sections;
  92507. if (savedSections)
  92508. bundleFileInfo.sections = [];
  92509. print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
  92510. if (bundleFileInfo) {
  92511. var newSections = bundleFileInfo.sections;
  92512. bundleFileInfo.sections = savedSections;
  92513. if (prepend.oldFileOfCurrentEmit)
  92514. (_a = bundleFileInfo.sections).push.apply(_a, newSections);
  92515. else {
  92516. newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
  92517. bundleFileInfo.sections.push({
  92518. pos: pos,
  92519. end: writer.getTextPos(),
  92520. kind: "prepend" /* Prepend */,
  92521. data: relativeToBuildInfo(prepend.fileName),
  92522. texts: newSections
  92523. });
  92524. }
  92525. }
  92526. }
  92527. sourceFileTextPos = getTextPosWithWriteLine();
  92528. for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
  92529. var sourceFile = _e[_d];
  92530. print(0 /* SourceFile */, sourceFile, sourceFile);
  92531. }
  92532. if (bundleFileInfo && bundle.sourceFiles.length) {
  92533. var end = writer.getTextPos();
  92534. if (recordBundleFileTextLikeSection(end)) {
  92535. // Store prologues
  92536. var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
  92537. if (prologues) {
  92538. if (!bundleFileInfo.sources)
  92539. bundleFileInfo.sources = {};
  92540. bundleFileInfo.sources.prologues = prologues;
  92541. }
  92542. // Store helpes
  92543. var helpers = getHelpersFromBundledSourceFiles(bundle);
  92544. if (helpers) {
  92545. if (!bundleFileInfo.sources)
  92546. bundleFileInfo.sources = {};
  92547. bundleFileInfo.sources.helpers = helpers;
  92548. }
  92549. }
  92550. }
  92551. reset();
  92552. writer = previousWriter;
  92553. }
  92554. function writeUnparsedSource(unparsed, output) {
  92555. var previousWriter = writer;
  92556. setWriter(output, /*_sourceMapGenerator*/ undefined);
  92557. print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
  92558. reset();
  92559. writer = previousWriter;
  92560. }
  92561. function writeFile(sourceFile, output, sourceMapGenerator) {
  92562. isOwnFileEmit = true;
  92563. var previousWriter = writer;
  92564. setWriter(output, sourceMapGenerator);
  92565. emitShebangIfNeeded(sourceFile);
  92566. emitPrologueDirectivesIfNeeded(sourceFile);
  92567. print(0 /* SourceFile */, sourceFile, sourceFile);
  92568. reset();
  92569. writer = previousWriter;
  92570. }
  92571. function beginPrint() {
  92572. return ownWriter || (ownWriter = ts.createTextWriter(newLine));
  92573. }
  92574. function endPrint() {
  92575. var text = ownWriter.getText();
  92576. ownWriter.clear();
  92577. return text;
  92578. }
  92579. function print(hint, node, sourceFile) {
  92580. if (sourceFile) {
  92581. setSourceFile(sourceFile);
  92582. }
  92583. pipelineEmit(hint, node);
  92584. }
  92585. function setSourceFile(sourceFile) {
  92586. currentSourceFile = sourceFile;
  92587. currentLineMap = undefined;
  92588. detachedCommentsInfo = undefined;
  92589. if (sourceFile) {
  92590. setSourceMapSource(sourceFile);
  92591. }
  92592. }
  92593. function setWriter(_writer, _sourceMapGenerator) {
  92594. if (_writer && printerOptions.omitTrailingSemicolon) {
  92595. _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
  92596. }
  92597. writer = _writer; // TODO: GH#18217
  92598. sourceMapGenerator = _sourceMapGenerator;
  92599. sourceMapsDisabled = !writer || !sourceMapGenerator;
  92600. }
  92601. function reset() {
  92602. nodeIdToGeneratedName = [];
  92603. autoGeneratedIdToGeneratedName = [];
  92604. generatedNames = ts.createMap();
  92605. tempFlagsStack = [];
  92606. tempFlags = 0 /* Auto */;
  92607. reservedNamesStack = [];
  92608. currentSourceFile = undefined;
  92609. currentLineMap = undefined;
  92610. detachedCommentsInfo = undefined;
  92611. lastNode = undefined;
  92612. lastSubstitution = undefined;
  92613. setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
  92614. }
  92615. function getCurrentLineMap() {
  92616. return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
  92617. }
  92618. function emit(node) {
  92619. if (node === undefined)
  92620. return;
  92621. var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
  92622. var substitute = pipelineEmit(4 /* Unspecified */, node);
  92623. recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
  92624. return substitute;
  92625. }
  92626. function emitIdentifierName(node) {
  92627. if (node === undefined)
  92628. return;
  92629. return pipelineEmit(2 /* IdentifierName */, node);
  92630. }
  92631. function emitExpression(node) {
  92632. if (node === undefined)
  92633. return;
  92634. return pipelineEmit(1 /* Expression */, node);
  92635. }
  92636. function emitJsxAttributeValue(node) {
  92637. return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
  92638. }
  92639. function pipelineEmit(emitHint, node) {
  92640. var savedLastNode = lastNode;
  92641. var savedLastSubstitution = lastSubstitution;
  92642. lastNode = node;
  92643. lastSubstitution = undefined;
  92644. var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
  92645. pipelinePhase(emitHint, node);
  92646. ts.Debug.assert(lastNode === node);
  92647. var substitute = lastSubstitution;
  92648. lastNode = savedLastNode;
  92649. lastSubstitution = savedLastSubstitution;
  92650. return substitute || node;
  92651. }
  92652. function getPipelinePhase(phase, emitHint, node) {
  92653. switch (phase) {
  92654. case 0 /* Notification */:
  92655. if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
  92656. return pipelineEmitWithNotification;
  92657. }
  92658. // falls through
  92659. case 1 /* Substitution */:
  92660. if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
  92661. return pipelineEmitWithSubstitution;
  92662. }
  92663. // falls through
  92664. case 2 /* Comments */:
  92665. if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
  92666. return pipelineEmitWithComments;
  92667. }
  92668. // falls through
  92669. case 3 /* SourceMaps */:
  92670. if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
  92671. return pipelineEmitWithSourceMap;
  92672. }
  92673. // falls through
  92674. case 4 /* Emit */:
  92675. return pipelineEmitWithHint;
  92676. default:
  92677. return ts.Debug.assertNever(phase);
  92678. }
  92679. }
  92680. function getNextPipelinePhase(currentPhase, emitHint, node) {
  92681. return getPipelinePhase(currentPhase + 1, emitHint, node);
  92682. }
  92683. function pipelineEmitWithNotification(hint, node) {
  92684. ts.Debug.assert(lastNode === node);
  92685. var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
  92686. onEmitNode(hint, node, pipelinePhase);
  92687. ts.Debug.assert(lastNode === node);
  92688. }
  92689. function pipelineEmitWithHint(hint, node) {
  92690. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  92691. if (hint === 0 /* SourceFile */)
  92692. return emitSourceFile(ts.cast(node, ts.isSourceFile));
  92693. if (hint === 2 /* IdentifierName */)
  92694. return emitIdentifier(ts.cast(node, ts.isIdentifier));
  92695. if (hint === 6 /* JsxAttributeValue */)
  92696. return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
  92697. if (hint === 3 /* MappedTypeParameter */)
  92698. return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
  92699. if (hint === 5 /* EmbeddedStatement */) {
  92700. ts.Debug.assertNode(node, ts.isEmptyStatement);
  92701. return emitEmptyStatement(/*isEmbeddedStatement*/ true);
  92702. }
  92703. if (hint === 4 /* Unspecified */) {
  92704. if (ts.isKeyword(node.kind))
  92705. return writeTokenNode(node, writeKeyword);
  92706. switch (node.kind) {
  92707. // Pseudo-literals
  92708. case 15 /* TemplateHead */:
  92709. case 16 /* TemplateMiddle */:
  92710. case 17 /* TemplateTail */:
  92711. return emitLiteral(node, /*jsxAttributeEscape*/ false);
  92712. case 292 /* UnparsedSource */:
  92713. case 286 /* UnparsedPrepend */:
  92714. return emitUnparsedSourceOrPrepend(node);
  92715. case 285 /* UnparsedPrologue */:
  92716. return writeUnparsedNode(node);
  92717. case 287 /* UnparsedText */:
  92718. case 288 /* UnparsedInternalText */:
  92719. return emitUnparsedTextLike(node);
  92720. case 289 /* UnparsedSyntheticReference */:
  92721. return emitUnparsedSyntheticReference(node);
  92722. // Identifiers
  92723. case 75 /* Identifier */:
  92724. return emitIdentifier(node);
  92725. // PrivateIdentifiers
  92726. case 76 /* PrivateIdentifier */:
  92727. return emitPrivateIdentifier(node);
  92728. // Parse tree nodes
  92729. // Names
  92730. case 153 /* QualifiedName */:
  92731. return emitQualifiedName(node);
  92732. case 154 /* ComputedPropertyName */:
  92733. return emitComputedPropertyName(node);
  92734. // Signature elements
  92735. case 155 /* TypeParameter */:
  92736. return emitTypeParameter(node);
  92737. case 156 /* Parameter */:
  92738. return emitParameter(node);
  92739. case 157 /* Decorator */:
  92740. return emitDecorator(node);
  92741. // Type members
  92742. case 158 /* PropertySignature */:
  92743. return emitPropertySignature(node);
  92744. case 159 /* PropertyDeclaration */:
  92745. return emitPropertyDeclaration(node);
  92746. case 160 /* MethodSignature */:
  92747. return emitMethodSignature(node);
  92748. case 161 /* MethodDeclaration */:
  92749. return emitMethodDeclaration(node);
  92750. case 162 /* Constructor */:
  92751. return emitConstructor(node);
  92752. case 163 /* GetAccessor */:
  92753. case 164 /* SetAccessor */:
  92754. return emitAccessorDeclaration(node);
  92755. case 165 /* CallSignature */:
  92756. return emitCallSignature(node);
  92757. case 166 /* ConstructSignature */:
  92758. return emitConstructSignature(node);
  92759. case 167 /* IndexSignature */:
  92760. return emitIndexSignature(node);
  92761. // Types
  92762. case 168 /* TypePredicate */:
  92763. return emitTypePredicate(node);
  92764. case 169 /* TypeReference */:
  92765. return emitTypeReference(node);
  92766. case 170 /* FunctionType */:
  92767. return emitFunctionType(node);
  92768. case 300 /* JSDocFunctionType */:
  92769. return emitJSDocFunctionType(node);
  92770. case 171 /* ConstructorType */:
  92771. return emitConstructorType(node);
  92772. case 172 /* TypeQuery */:
  92773. return emitTypeQuery(node);
  92774. case 173 /* TypeLiteral */:
  92775. return emitTypeLiteral(node);
  92776. case 174 /* ArrayType */:
  92777. return emitArrayType(node);
  92778. case 175 /* TupleType */:
  92779. return emitTupleType(node);
  92780. case 176 /* OptionalType */:
  92781. return emitOptionalType(node);
  92782. case 178 /* UnionType */:
  92783. return emitUnionType(node);
  92784. case 179 /* IntersectionType */:
  92785. return emitIntersectionType(node);
  92786. case 180 /* ConditionalType */:
  92787. return emitConditionalType(node);
  92788. case 181 /* InferType */:
  92789. return emitInferType(node);
  92790. case 182 /* ParenthesizedType */:
  92791. return emitParenthesizedType(node);
  92792. case 216 /* ExpressionWithTypeArguments */:
  92793. return emitExpressionWithTypeArguments(node);
  92794. case 183 /* ThisType */:
  92795. return emitThisType();
  92796. case 184 /* TypeOperator */:
  92797. return emitTypeOperator(node);
  92798. case 185 /* IndexedAccessType */:
  92799. return emitIndexedAccessType(node);
  92800. case 186 /* MappedType */:
  92801. return emitMappedType(node);
  92802. case 187 /* LiteralType */:
  92803. return emitLiteralType(node);
  92804. case 188 /* ImportType */:
  92805. return emitImportTypeNode(node);
  92806. case 295 /* JSDocAllType */:
  92807. writePunctuation("*");
  92808. return;
  92809. case 296 /* JSDocUnknownType */:
  92810. writePunctuation("?");
  92811. return;
  92812. case 297 /* JSDocNullableType */:
  92813. return emitJSDocNullableType(node);
  92814. case 298 /* JSDocNonNullableType */:
  92815. return emitJSDocNonNullableType(node);
  92816. case 299 /* JSDocOptionalType */:
  92817. return emitJSDocOptionalType(node);
  92818. case 177 /* RestType */:
  92819. case 301 /* JSDocVariadicType */:
  92820. return emitRestOrJSDocVariadicType(node);
  92821. // Binding patterns
  92822. case 189 /* ObjectBindingPattern */:
  92823. return emitObjectBindingPattern(node);
  92824. case 190 /* ArrayBindingPattern */:
  92825. return emitArrayBindingPattern(node);
  92826. case 191 /* BindingElement */:
  92827. return emitBindingElement(node);
  92828. // Misc
  92829. case 221 /* TemplateSpan */:
  92830. return emitTemplateSpan(node);
  92831. case 222 /* SemicolonClassElement */:
  92832. return emitSemicolonClassElement();
  92833. // Statements
  92834. case 223 /* Block */:
  92835. return emitBlock(node);
  92836. case 225 /* VariableStatement */:
  92837. return emitVariableStatement(node);
  92838. case 224 /* EmptyStatement */:
  92839. return emitEmptyStatement(/*isEmbeddedStatement*/ false);
  92840. case 226 /* ExpressionStatement */:
  92841. return emitExpressionStatement(node);
  92842. case 227 /* IfStatement */:
  92843. return emitIfStatement(node);
  92844. case 228 /* DoStatement */:
  92845. return emitDoStatement(node);
  92846. case 229 /* WhileStatement */:
  92847. return emitWhileStatement(node);
  92848. case 230 /* ForStatement */:
  92849. return emitForStatement(node);
  92850. case 231 /* ForInStatement */:
  92851. return emitForInStatement(node);
  92852. case 232 /* ForOfStatement */:
  92853. return emitForOfStatement(node);
  92854. case 233 /* ContinueStatement */:
  92855. return emitContinueStatement(node);
  92856. case 234 /* BreakStatement */:
  92857. return emitBreakStatement(node);
  92858. case 235 /* ReturnStatement */:
  92859. return emitReturnStatement(node);
  92860. case 236 /* WithStatement */:
  92861. return emitWithStatement(node);
  92862. case 237 /* SwitchStatement */:
  92863. return emitSwitchStatement(node);
  92864. case 238 /* LabeledStatement */:
  92865. return emitLabeledStatement(node);
  92866. case 239 /* ThrowStatement */:
  92867. return emitThrowStatement(node);
  92868. case 240 /* TryStatement */:
  92869. return emitTryStatement(node);
  92870. case 241 /* DebuggerStatement */:
  92871. return emitDebuggerStatement(node);
  92872. // Declarations
  92873. case 242 /* VariableDeclaration */:
  92874. return emitVariableDeclaration(node);
  92875. case 243 /* VariableDeclarationList */:
  92876. return emitVariableDeclarationList(node);
  92877. case 244 /* FunctionDeclaration */:
  92878. return emitFunctionDeclaration(node);
  92879. case 245 /* ClassDeclaration */:
  92880. return emitClassDeclaration(node);
  92881. case 246 /* InterfaceDeclaration */:
  92882. return emitInterfaceDeclaration(node);
  92883. case 247 /* TypeAliasDeclaration */:
  92884. return emitTypeAliasDeclaration(node);
  92885. case 248 /* EnumDeclaration */:
  92886. return emitEnumDeclaration(node);
  92887. case 249 /* ModuleDeclaration */:
  92888. return emitModuleDeclaration(node);
  92889. case 250 /* ModuleBlock */:
  92890. return emitModuleBlock(node);
  92891. case 251 /* CaseBlock */:
  92892. return emitCaseBlock(node);
  92893. case 252 /* NamespaceExportDeclaration */:
  92894. return emitNamespaceExportDeclaration(node);
  92895. case 253 /* ImportEqualsDeclaration */:
  92896. return emitImportEqualsDeclaration(node);
  92897. case 254 /* ImportDeclaration */:
  92898. return emitImportDeclaration(node);
  92899. case 255 /* ImportClause */:
  92900. return emitImportClause(node);
  92901. case 256 /* NamespaceImport */:
  92902. return emitNamespaceImport(node);
  92903. case 262 /* NamespaceExport */:
  92904. return emitNamespaceExport(node);
  92905. case 257 /* NamedImports */:
  92906. return emitNamedImports(node);
  92907. case 258 /* ImportSpecifier */:
  92908. return emitImportSpecifier(node);
  92909. case 259 /* ExportAssignment */:
  92910. return emitExportAssignment(node);
  92911. case 260 /* ExportDeclaration */:
  92912. return emitExportDeclaration(node);
  92913. case 261 /* NamedExports */:
  92914. return emitNamedExports(node);
  92915. case 263 /* ExportSpecifier */:
  92916. return emitExportSpecifier(node);
  92917. case 264 /* MissingDeclaration */:
  92918. return;
  92919. // Module references
  92920. case 265 /* ExternalModuleReference */:
  92921. return emitExternalModuleReference(node);
  92922. // JSX (non-expression)
  92923. case 11 /* JsxText */:
  92924. return emitJsxText(node);
  92925. case 268 /* JsxOpeningElement */:
  92926. case 271 /* JsxOpeningFragment */:
  92927. return emitJsxOpeningElementOrFragment(node);
  92928. case 269 /* JsxClosingElement */:
  92929. case 272 /* JsxClosingFragment */:
  92930. return emitJsxClosingElementOrFragment(node);
  92931. case 273 /* JsxAttribute */:
  92932. return emitJsxAttribute(node);
  92933. case 274 /* JsxAttributes */:
  92934. return emitJsxAttributes(node);
  92935. case 275 /* JsxSpreadAttribute */:
  92936. return emitJsxSpreadAttribute(node);
  92937. case 276 /* JsxExpression */:
  92938. return emitJsxExpression(node);
  92939. // Clauses
  92940. case 277 /* CaseClause */:
  92941. return emitCaseClause(node);
  92942. case 278 /* DefaultClause */:
  92943. return emitDefaultClause(node);
  92944. case 279 /* HeritageClause */:
  92945. return emitHeritageClause(node);
  92946. case 280 /* CatchClause */:
  92947. return emitCatchClause(node);
  92948. // Property assignments
  92949. case 281 /* PropertyAssignment */:
  92950. return emitPropertyAssignment(node);
  92951. case 282 /* ShorthandPropertyAssignment */:
  92952. return emitShorthandPropertyAssignment(node);
  92953. case 283 /* SpreadAssignment */:
  92954. return emitSpreadAssignment(node);
  92955. // Enum
  92956. case 284 /* EnumMember */:
  92957. return emitEnumMember(node);
  92958. // JSDoc nodes (only used in codefixes currently)
  92959. case 316 /* JSDocParameterTag */:
  92960. case 322 /* JSDocPropertyTag */:
  92961. return emitJSDocPropertyLikeTag(node);
  92962. case 317 /* JSDocReturnTag */:
  92963. case 319 /* JSDocTypeTag */:
  92964. case 318 /* JSDocThisTag */:
  92965. case 315 /* JSDocEnumTag */:
  92966. return emitJSDocSimpleTypedTag(node);
  92967. case 307 /* JSDocAugmentsTag */:
  92968. return emitJSDocAugmentsTag(node);
  92969. case 320 /* JSDocTemplateTag */:
  92970. return emitJSDocTemplateTag(node);
  92971. case 321 /* JSDocTypedefTag */:
  92972. return emitJSDocTypedefTag(node);
  92973. case 314 /* JSDocCallbackTag */:
  92974. return emitJSDocCallbackTag(node);
  92975. case 305 /* JSDocSignature */:
  92976. return emitJSDocSignature(node);
  92977. case 304 /* JSDocTypeLiteral */:
  92978. return emitJSDocTypeLiteral(node);
  92979. case 309 /* JSDocClassTag */:
  92980. case 306 /* JSDocTag */:
  92981. return emitJSDocSimpleTag(node);
  92982. case 303 /* JSDocComment */:
  92983. return emitJSDoc(node);
  92984. // Transformation nodes (ignored)
  92985. }
  92986. if (ts.isExpression(node)) {
  92987. hint = 1 /* Expression */;
  92988. if (substituteNode !== ts.noEmitSubstitution) {
  92989. lastSubstitution = node = substituteNode(hint, node);
  92990. }
  92991. }
  92992. else if (ts.isToken(node)) {
  92993. return writeTokenNode(node, writePunctuation);
  92994. }
  92995. }
  92996. if (hint === 1 /* Expression */) {
  92997. switch (node.kind) {
  92998. // Literals
  92999. case 8 /* NumericLiteral */:
  93000. case 9 /* BigIntLiteral */:
  93001. return emitNumericOrBigIntLiteral(node);
  93002. case 10 /* StringLiteral */:
  93003. case 13 /* RegularExpressionLiteral */:
  93004. case 14 /* NoSubstitutionTemplateLiteral */:
  93005. return emitLiteral(node, /*jsxAttributeEscape*/ false);
  93006. // Identifiers
  93007. case 75 /* Identifier */:
  93008. return emitIdentifier(node);
  93009. // Reserved words
  93010. case 91 /* FalseKeyword */:
  93011. case 100 /* NullKeyword */:
  93012. case 102 /* SuperKeyword */:
  93013. case 106 /* TrueKeyword */:
  93014. case 104 /* ThisKeyword */:
  93015. case 96 /* ImportKeyword */:
  93016. writeTokenNode(node, writeKeyword);
  93017. return;
  93018. // Expressions
  93019. case 192 /* ArrayLiteralExpression */:
  93020. return emitArrayLiteralExpression(node);
  93021. case 193 /* ObjectLiteralExpression */:
  93022. return emitObjectLiteralExpression(node);
  93023. case 194 /* PropertyAccessExpression */:
  93024. return emitPropertyAccessExpression(node);
  93025. case 195 /* ElementAccessExpression */:
  93026. return emitElementAccessExpression(node);
  93027. case 196 /* CallExpression */:
  93028. return emitCallExpression(node);
  93029. case 197 /* NewExpression */:
  93030. return emitNewExpression(node);
  93031. case 198 /* TaggedTemplateExpression */:
  93032. return emitTaggedTemplateExpression(node);
  93033. case 199 /* TypeAssertionExpression */:
  93034. return emitTypeAssertionExpression(node);
  93035. case 200 /* ParenthesizedExpression */:
  93036. return emitParenthesizedExpression(node);
  93037. case 201 /* FunctionExpression */:
  93038. return emitFunctionExpression(node);
  93039. case 202 /* ArrowFunction */:
  93040. return emitArrowFunction(node);
  93041. case 203 /* DeleteExpression */:
  93042. return emitDeleteExpression(node);
  93043. case 204 /* TypeOfExpression */:
  93044. return emitTypeOfExpression(node);
  93045. case 205 /* VoidExpression */:
  93046. return emitVoidExpression(node);
  93047. case 206 /* AwaitExpression */:
  93048. return emitAwaitExpression(node);
  93049. case 207 /* PrefixUnaryExpression */:
  93050. return emitPrefixUnaryExpression(node);
  93051. case 208 /* PostfixUnaryExpression */:
  93052. return emitPostfixUnaryExpression(node);
  93053. case 209 /* BinaryExpression */:
  93054. return emitBinaryExpression(node);
  93055. case 210 /* ConditionalExpression */:
  93056. return emitConditionalExpression(node);
  93057. case 211 /* TemplateExpression */:
  93058. return emitTemplateExpression(node);
  93059. case 212 /* YieldExpression */:
  93060. return emitYieldExpression(node);
  93061. case 213 /* SpreadElement */:
  93062. return emitSpreadExpression(node);
  93063. case 214 /* ClassExpression */:
  93064. return emitClassExpression(node);
  93065. case 215 /* OmittedExpression */:
  93066. return;
  93067. case 217 /* AsExpression */:
  93068. return emitAsExpression(node);
  93069. case 218 /* NonNullExpression */:
  93070. return emitNonNullExpression(node);
  93071. case 219 /* MetaProperty */:
  93072. return emitMetaProperty(node);
  93073. // JSX
  93074. case 266 /* JsxElement */:
  93075. return emitJsxElement(node);
  93076. case 267 /* JsxSelfClosingElement */:
  93077. return emitJsxSelfClosingElement(node);
  93078. case 270 /* JsxFragment */:
  93079. return emitJsxFragment(node);
  93080. // Transformation nodes
  93081. case 325 /* PartiallyEmittedExpression */:
  93082. return emitPartiallyEmittedExpression(node);
  93083. case 326 /* CommaListExpression */:
  93084. return emitCommaList(node);
  93085. }
  93086. }
  93087. }
  93088. function emitMappedTypeParameter(node) {
  93089. emit(node.name);
  93090. writeSpace();
  93091. writeKeyword("in");
  93092. writeSpace();
  93093. emit(node.constraint);
  93094. }
  93095. function pipelineEmitWithSubstitution(hint, node) {
  93096. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  93097. var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
  93098. pipelinePhase(hint, lastSubstitution);
  93099. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  93100. }
  93101. function getHelpersFromBundledSourceFiles(bundle) {
  93102. var result;
  93103. if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
  93104. return undefined;
  93105. }
  93106. var bundledHelpers = ts.createMap();
  93107. for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
  93108. var sourceFile = _b[_a];
  93109. var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
  93110. var helpers = getSortedEmitHelpers(sourceFile);
  93111. if (!helpers)
  93112. continue;
  93113. for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
  93114. var helper = helpers_4[_c];
  93115. if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
  93116. bundledHelpers.set(helper.name, true);
  93117. (result || (result = [])).push(helper.name);
  93118. }
  93119. }
  93120. }
  93121. return result;
  93122. }
  93123. function emitHelpers(node) {
  93124. var helpersEmitted = false;
  93125. var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
  93126. if (bundle && moduleKind === ts.ModuleKind.None) {
  93127. return;
  93128. }
  93129. var numPrepends = bundle ? bundle.prepends.length : 0;
  93130. var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
  93131. for (var i = 0; i < numNodes; i++) {
  93132. var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
  93133. var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
  93134. var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
  93135. var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
  93136. var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
  93137. if (helpers) {
  93138. for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
  93139. var helper = helpers_5[_a];
  93140. if (!helper.scoped) {
  93141. // Skip the helper if it can be skipped and the noEmitHelpers compiler
  93142. // option is set, or if it can be imported and the importHelpers compiler
  93143. // option is set.
  93144. if (shouldSkip)
  93145. continue;
  93146. // Skip the helper if it can be bundled but hasn't already been emitted and we
  93147. // are emitting a bundled module.
  93148. if (shouldBundle) {
  93149. if (bundledHelpers.get(helper.name)) {
  93150. continue;
  93151. }
  93152. bundledHelpers.set(helper.name, true);
  93153. }
  93154. }
  93155. else if (bundle) {
  93156. // Skip the helper if it is scoped and we are emitting bundled helpers
  93157. continue;
  93158. }
  93159. var pos = getTextPosWithWriteLine();
  93160. if (typeof helper.text === "string") {
  93161. writeLines(helper.text);
  93162. }
  93163. else {
  93164. writeLines(helper.text(makeFileLevelOptimisticUniqueName));
  93165. }
  93166. if (bundleFileInfo)
  93167. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
  93168. helpersEmitted = true;
  93169. }
  93170. }
  93171. }
  93172. return helpersEmitted;
  93173. }
  93174. function getSortedEmitHelpers(node) {
  93175. var helpers = ts.getEmitHelpers(node);
  93176. return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
  93177. }
  93178. //
  93179. // Literals/Pseudo-literals
  93180. //
  93181. // SyntaxKind.NumericLiteral
  93182. // SyntaxKind.BigIntLiteral
  93183. function emitNumericOrBigIntLiteral(node) {
  93184. emitLiteral(node, /*jsxAttributeEscape*/ false);
  93185. }
  93186. // SyntaxKind.StringLiteral
  93187. // SyntaxKind.RegularExpressionLiteral
  93188. // SyntaxKind.NoSubstitutionTemplateLiteral
  93189. // SyntaxKind.TemplateHead
  93190. // SyntaxKind.TemplateMiddle
  93191. // SyntaxKind.TemplateTail
  93192. function emitLiteral(node, jsxAttributeEscape) {
  93193. var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
  93194. if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
  93195. && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
  93196. writeLiteral(text);
  93197. }
  93198. else {
  93199. // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
  93200. writeStringLiteral(text);
  93201. }
  93202. }
  93203. // SyntaxKind.UnparsedSource
  93204. // SyntaxKind.UnparsedPrepend
  93205. function emitUnparsedSourceOrPrepend(unparsed) {
  93206. for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
  93207. var text = _b[_a];
  93208. writeLine();
  93209. emit(text);
  93210. }
  93211. }
  93212. // SyntaxKind.UnparsedPrologue
  93213. // SyntaxKind.UnparsedText
  93214. // SyntaxKind.UnparsedInternal
  93215. // SyntaxKind.UnparsedSyntheticReference
  93216. function writeUnparsedNode(unparsed) {
  93217. writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
  93218. }
  93219. // SyntaxKind.UnparsedText
  93220. // SyntaxKind.UnparsedInternal
  93221. function emitUnparsedTextLike(unparsed) {
  93222. var pos = getTextPosWithWriteLine();
  93223. writeUnparsedNode(unparsed);
  93224. if (bundleFileInfo) {
  93225. updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
  93226. "text" /* Text */ :
  93227. "internal" /* Internal */);
  93228. }
  93229. }
  93230. // SyntaxKind.UnparsedSyntheticReference
  93231. function emitUnparsedSyntheticReference(unparsed) {
  93232. var pos = getTextPosWithWriteLine();
  93233. writeUnparsedNode(unparsed);
  93234. if (bundleFileInfo) {
  93235. var section = ts.clone(unparsed.section);
  93236. section.pos = pos;
  93237. section.end = writer.getTextPos();
  93238. bundleFileInfo.sections.push(section);
  93239. }
  93240. }
  93241. //
  93242. // Identifiers
  93243. //
  93244. function emitIdentifier(node) {
  93245. var writeText = node.symbol ? writeSymbol : write;
  93246. writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
  93247. emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
  93248. }
  93249. //
  93250. // Names
  93251. //
  93252. function emitPrivateIdentifier(node) {
  93253. var writeText = node.symbol ? writeSymbol : write;
  93254. writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
  93255. }
  93256. function emitQualifiedName(node) {
  93257. emitEntityName(node.left);
  93258. writePunctuation(".");
  93259. emit(node.right);
  93260. }
  93261. function emitEntityName(node) {
  93262. if (node.kind === 75 /* Identifier */) {
  93263. emitExpression(node);
  93264. }
  93265. else {
  93266. emit(node);
  93267. }
  93268. }
  93269. function emitComputedPropertyName(node) {
  93270. writePunctuation("[");
  93271. emitExpression(node.expression);
  93272. writePunctuation("]");
  93273. }
  93274. //
  93275. // Signature elements
  93276. //
  93277. function emitTypeParameter(node) {
  93278. emit(node.name);
  93279. if (node.constraint) {
  93280. writeSpace();
  93281. writeKeyword("extends");
  93282. writeSpace();
  93283. emit(node.constraint);
  93284. }
  93285. if (node.default) {
  93286. writeSpace();
  93287. writeOperator("=");
  93288. writeSpace();
  93289. emit(node.default);
  93290. }
  93291. }
  93292. function emitParameter(node) {
  93293. emitDecorators(node, node.decorators);
  93294. emitModifiers(node, node.modifiers);
  93295. emit(node.dotDotDotToken);
  93296. emitNodeWithWriter(node.name, writeParameter);
  93297. emit(node.questionToken);
  93298. if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
  93299. emit(node.type);
  93300. }
  93301. else {
  93302. emitTypeAnnotation(node.type);
  93303. }
  93304. // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer.
  93305. emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node);
  93306. }
  93307. function emitDecorator(decorator) {
  93308. writePunctuation("@");
  93309. emitExpression(decorator.expression);
  93310. }
  93311. //
  93312. // Type members
  93313. //
  93314. function emitPropertySignature(node) {
  93315. emitDecorators(node, node.decorators);
  93316. emitModifiers(node, node.modifiers);
  93317. emitNodeWithWriter(node.name, writeProperty);
  93318. emit(node.questionToken);
  93319. emitTypeAnnotation(node.type);
  93320. writeTrailingSemicolon();
  93321. }
  93322. function emitPropertyDeclaration(node) {
  93323. emitDecorators(node, node.decorators);
  93324. emitModifiers(node, node.modifiers);
  93325. emit(node.name);
  93326. emit(node.questionToken);
  93327. emit(node.exclamationToken);
  93328. emitTypeAnnotation(node.type);
  93329. emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
  93330. writeTrailingSemicolon();
  93331. }
  93332. function emitMethodSignature(node) {
  93333. pushNameGenerationScope(node);
  93334. emitDecorators(node, node.decorators);
  93335. emitModifiers(node, node.modifiers);
  93336. emit(node.name);
  93337. emit(node.questionToken);
  93338. emitTypeParameters(node, node.typeParameters);
  93339. emitParameters(node, node.parameters);
  93340. emitTypeAnnotation(node.type);
  93341. writeTrailingSemicolon();
  93342. popNameGenerationScope(node);
  93343. }
  93344. function emitMethodDeclaration(node) {
  93345. emitDecorators(node, node.decorators);
  93346. emitModifiers(node, node.modifiers);
  93347. emit(node.asteriskToken);
  93348. emit(node.name);
  93349. emit(node.questionToken);
  93350. emitSignatureAndBody(node, emitSignatureHead);
  93351. }
  93352. function emitConstructor(node) {
  93353. emitModifiers(node, node.modifiers);
  93354. writeKeyword("constructor");
  93355. emitSignatureAndBody(node, emitSignatureHead);
  93356. }
  93357. function emitAccessorDeclaration(node) {
  93358. emitDecorators(node, node.decorators);
  93359. emitModifiers(node, node.modifiers);
  93360. writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
  93361. writeSpace();
  93362. emit(node.name);
  93363. emitSignatureAndBody(node, emitSignatureHead);
  93364. }
  93365. function emitCallSignature(node) {
  93366. pushNameGenerationScope(node);
  93367. emitDecorators(node, node.decorators);
  93368. emitModifiers(node, node.modifiers);
  93369. emitTypeParameters(node, node.typeParameters);
  93370. emitParameters(node, node.parameters);
  93371. emitTypeAnnotation(node.type);
  93372. writeTrailingSemicolon();
  93373. popNameGenerationScope(node);
  93374. }
  93375. function emitConstructSignature(node) {
  93376. pushNameGenerationScope(node);
  93377. emitDecorators(node, node.decorators);
  93378. emitModifiers(node, node.modifiers);
  93379. writeKeyword("new");
  93380. writeSpace();
  93381. emitTypeParameters(node, node.typeParameters);
  93382. emitParameters(node, node.parameters);
  93383. emitTypeAnnotation(node.type);
  93384. writeTrailingSemicolon();
  93385. popNameGenerationScope(node);
  93386. }
  93387. function emitIndexSignature(node) {
  93388. emitDecorators(node, node.decorators);
  93389. emitModifiers(node, node.modifiers);
  93390. emitParametersForIndexSignature(node, node.parameters);
  93391. emitTypeAnnotation(node.type);
  93392. writeTrailingSemicolon();
  93393. }
  93394. function emitSemicolonClassElement() {
  93395. writeTrailingSemicolon();
  93396. }
  93397. //
  93398. // Types
  93399. //
  93400. function emitTypePredicate(node) {
  93401. if (node.assertsModifier) {
  93402. emit(node.assertsModifier);
  93403. writeSpace();
  93404. }
  93405. emit(node.parameterName);
  93406. if (node.type) {
  93407. writeSpace();
  93408. writeKeyword("is");
  93409. writeSpace();
  93410. emit(node.type);
  93411. }
  93412. }
  93413. function emitTypeReference(node) {
  93414. emit(node.typeName);
  93415. emitTypeArguments(node, node.typeArguments);
  93416. }
  93417. function emitFunctionType(node) {
  93418. pushNameGenerationScope(node);
  93419. emitTypeParameters(node, node.typeParameters);
  93420. emitParametersForArrow(node, node.parameters);
  93421. writeSpace();
  93422. writePunctuation("=>");
  93423. writeSpace();
  93424. emit(node.type);
  93425. popNameGenerationScope(node);
  93426. }
  93427. function emitJSDocFunctionType(node) {
  93428. writeKeyword("function");
  93429. emitParameters(node, node.parameters);
  93430. writePunctuation(":");
  93431. emit(node.type);
  93432. }
  93433. function emitJSDocNullableType(node) {
  93434. writePunctuation("?");
  93435. emit(node.type);
  93436. }
  93437. function emitJSDocNonNullableType(node) {
  93438. writePunctuation("!");
  93439. emit(node.type);
  93440. }
  93441. function emitJSDocOptionalType(node) {
  93442. emit(node.type);
  93443. writePunctuation("=");
  93444. }
  93445. function emitConstructorType(node) {
  93446. pushNameGenerationScope(node);
  93447. writeKeyword("new");
  93448. writeSpace();
  93449. emitTypeParameters(node, node.typeParameters);
  93450. emitParameters(node, node.parameters);
  93451. writeSpace();
  93452. writePunctuation("=>");
  93453. writeSpace();
  93454. emit(node.type);
  93455. popNameGenerationScope(node);
  93456. }
  93457. function emitTypeQuery(node) {
  93458. writeKeyword("typeof");
  93459. writeSpace();
  93460. emit(node.exprName);
  93461. }
  93462. function emitTypeLiteral(node) {
  93463. writePunctuation("{");
  93464. var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
  93465. emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
  93466. writePunctuation("}");
  93467. }
  93468. function emitArrayType(node) {
  93469. emit(node.elementType);
  93470. writePunctuation("[");
  93471. writePunctuation("]");
  93472. }
  93473. function emitRestOrJSDocVariadicType(node) {
  93474. writePunctuation("...");
  93475. emit(node.type);
  93476. }
  93477. function emitTupleType(node) {
  93478. writePunctuation("[");
  93479. emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
  93480. writePunctuation("]");
  93481. }
  93482. function emitOptionalType(node) {
  93483. emit(node.type);
  93484. writePunctuation("?");
  93485. }
  93486. function emitUnionType(node) {
  93487. emitList(node, node.types, 516 /* UnionTypeConstituents */);
  93488. }
  93489. function emitIntersectionType(node) {
  93490. emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
  93491. }
  93492. function emitConditionalType(node) {
  93493. emit(node.checkType);
  93494. writeSpace();
  93495. writeKeyword("extends");
  93496. writeSpace();
  93497. emit(node.extendsType);
  93498. writeSpace();
  93499. writePunctuation("?");
  93500. writeSpace();
  93501. emit(node.trueType);
  93502. writeSpace();
  93503. writePunctuation(":");
  93504. writeSpace();
  93505. emit(node.falseType);
  93506. }
  93507. function emitInferType(node) {
  93508. writeKeyword("infer");
  93509. writeSpace();
  93510. emit(node.typeParameter);
  93511. }
  93512. function emitParenthesizedType(node) {
  93513. writePunctuation("(");
  93514. emit(node.type);
  93515. writePunctuation(")");
  93516. }
  93517. function emitThisType() {
  93518. writeKeyword("this");
  93519. }
  93520. function emitTypeOperator(node) {
  93521. writeTokenText(node.operator, writeKeyword);
  93522. writeSpace();
  93523. emit(node.type);
  93524. }
  93525. function emitIndexedAccessType(node) {
  93526. emit(node.objectType);
  93527. writePunctuation("[");
  93528. emit(node.indexType);
  93529. writePunctuation("]");
  93530. }
  93531. function emitMappedType(node) {
  93532. var emitFlags = ts.getEmitFlags(node);
  93533. writePunctuation("{");
  93534. if (emitFlags & 1 /* SingleLine */) {
  93535. writeSpace();
  93536. }
  93537. else {
  93538. writeLine();
  93539. increaseIndent();
  93540. }
  93541. if (node.readonlyToken) {
  93542. emit(node.readonlyToken);
  93543. if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
  93544. writeKeyword("readonly");
  93545. }
  93546. writeSpace();
  93547. }
  93548. writePunctuation("[");
  93549. pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
  93550. writePunctuation("]");
  93551. if (node.questionToken) {
  93552. emit(node.questionToken);
  93553. if (node.questionToken.kind !== 57 /* QuestionToken */) {
  93554. writePunctuation("?");
  93555. }
  93556. }
  93557. writePunctuation(":");
  93558. writeSpace();
  93559. emit(node.type);
  93560. writeTrailingSemicolon();
  93561. if (emitFlags & 1 /* SingleLine */) {
  93562. writeSpace();
  93563. }
  93564. else {
  93565. writeLine();
  93566. decreaseIndent();
  93567. }
  93568. writePunctuation("}");
  93569. }
  93570. function emitLiteralType(node) {
  93571. emitExpression(node.literal);
  93572. }
  93573. function emitImportTypeNode(node) {
  93574. if (node.isTypeOf) {
  93575. writeKeyword("typeof");
  93576. writeSpace();
  93577. }
  93578. writeKeyword("import");
  93579. writePunctuation("(");
  93580. emit(node.argument);
  93581. writePunctuation(")");
  93582. if (node.qualifier) {
  93583. writePunctuation(".");
  93584. emit(node.qualifier);
  93585. }
  93586. emitTypeArguments(node, node.typeArguments);
  93587. }
  93588. //
  93589. // Binding patterns
  93590. //
  93591. function emitObjectBindingPattern(node) {
  93592. writePunctuation("{");
  93593. emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
  93594. writePunctuation("}");
  93595. }
  93596. function emitArrayBindingPattern(node) {
  93597. writePunctuation("[");
  93598. emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
  93599. writePunctuation("]");
  93600. }
  93601. function emitBindingElement(node) {
  93602. emit(node.dotDotDotToken);
  93603. if (node.propertyName) {
  93604. emit(node.propertyName);
  93605. writePunctuation(":");
  93606. writeSpace();
  93607. }
  93608. emit(node.name);
  93609. emitInitializer(node.initializer, node.name.end, node);
  93610. }
  93611. //
  93612. // Expressions
  93613. //
  93614. function emitArrayLiteralExpression(node) {
  93615. var elements = node.elements;
  93616. var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
  93617. emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
  93618. }
  93619. function emitObjectLiteralExpression(node) {
  93620. ts.forEach(node.properties, generateMemberNames);
  93621. var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
  93622. if (indentedFlag) {
  93623. increaseIndent();
  93624. }
  93625. var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
  93626. var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
  93627. emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
  93628. if (indentedFlag) {
  93629. decreaseIndent();
  93630. }
  93631. }
  93632. function emitPropertyAccessExpression(node) {
  93633. var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
  93634. var token = ts.getDotOrQuestionDotToken(node);
  93635. var indentBeforeDot = needsIndentation(node, node.expression, token);
  93636. var indentAfterDot = needsIndentation(node, token, node.name);
  93637. increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false);
  93638. var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
  93639. mayNeedDotDotForPropertyAccess(expression) &&
  93640. !writer.hasTrailingComment() &&
  93641. !writer.hasTrailingWhitespace();
  93642. if (shouldEmitDotDot) {
  93643. writePunctuation(".");
  93644. }
  93645. emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
  93646. increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false);
  93647. emit(node.name);
  93648. decreaseIndentIf(indentBeforeDot, indentAfterDot);
  93649. }
  93650. // 1..toString is a valid property access, emit a dot after the literal
  93651. // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
  93652. function mayNeedDotDotForPropertyAccess(expression) {
  93653. expression = ts.skipPartiallyEmittedExpressions(expression);
  93654. if (ts.isNumericLiteral(expression)) {
  93655. // check if numeric literal is a decimal literal that was originally written with a dot
  93656. var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
  93657. // If he number will be printed verbatim and it doesn't already contain a dot, add one
  93658. // if the expression doesn't have any comments that will be emitted.
  93659. return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
  93660. }
  93661. else if (ts.isAccessExpression(expression)) {
  93662. // check if constant enum value is integer
  93663. var constantValue = ts.getConstantValue(expression);
  93664. // isFinite handles cases when constantValue is undefined
  93665. return typeof constantValue === "number" && isFinite(constantValue)
  93666. && Math.floor(constantValue) === constantValue;
  93667. }
  93668. }
  93669. function emitElementAccessExpression(node) {
  93670. emitExpression(node.expression);
  93671. emit(node.questionDotToken);
  93672. emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
  93673. emitExpression(node.argumentExpression);
  93674. emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
  93675. }
  93676. function emitCallExpression(node) {
  93677. emitExpression(node.expression);
  93678. emit(node.questionDotToken);
  93679. emitTypeArguments(node, node.typeArguments);
  93680. emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
  93681. }
  93682. function emitNewExpression(node) {
  93683. emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
  93684. writeSpace();
  93685. emitExpression(node.expression);
  93686. emitTypeArguments(node, node.typeArguments);
  93687. emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
  93688. }
  93689. function emitTaggedTemplateExpression(node) {
  93690. emitExpression(node.tag);
  93691. emitTypeArguments(node, node.typeArguments);
  93692. writeSpace();
  93693. emitExpression(node.template);
  93694. }
  93695. function emitTypeAssertionExpression(node) {
  93696. writePunctuation("<");
  93697. emit(node.type);
  93698. writePunctuation(">");
  93699. emitExpression(node.expression);
  93700. }
  93701. function emitParenthesizedExpression(node) {
  93702. var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
  93703. emitExpression(node.expression);
  93704. emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
  93705. }
  93706. function emitFunctionExpression(node) {
  93707. generateNameIfNeeded(node.name);
  93708. emitFunctionDeclarationOrExpression(node);
  93709. }
  93710. function emitArrowFunction(node) {
  93711. emitDecorators(node, node.decorators);
  93712. emitModifiers(node, node.modifiers);
  93713. emitSignatureAndBody(node, emitArrowFunctionHead);
  93714. }
  93715. function emitArrowFunctionHead(node) {
  93716. emitTypeParameters(node, node.typeParameters);
  93717. emitParametersForArrow(node, node.parameters);
  93718. emitTypeAnnotation(node.type);
  93719. writeSpace();
  93720. emit(node.equalsGreaterThanToken);
  93721. }
  93722. function emitDeleteExpression(node) {
  93723. emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
  93724. writeSpace();
  93725. emitExpression(node.expression);
  93726. }
  93727. function emitTypeOfExpression(node) {
  93728. emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
  93729. writeSpace();
  93730. emitExpression(node.expression);
  93731. }
  93732. function emitVoidExpression(node) {
  93733. emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
  93734. writeSpace();
  93735. emitExpression(node.expression);
  93736. }
  93737. function emitAwaitExpression(node) {
  93738. emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
  93739. writeSpace();
  93740. emitExpression(node.expression);
  93741. }
  93742. function emitPrefixUnaryExpression(node) {
  93743. writeTokenText(node.operator, writeOperator);
  93744. if (shouldEmitWhitespaceBeforeOperand(node)) {
  93745. writeSpace();
  93746. }
  93747. emitExpression(node.operand);
  93748. }
  93749. function shouldEmitWhitespaceBeforeOperand(node) {
  93750. // In some cases, we need to emit a space between the operator and the operand. One obvious case
  93751. // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
  93752. // and minus expressions in certain cases. Specifically, consider the following two cases (parens
  93753. // are just for clarity of exposition, and not part of the source code):
  93754. //
  93755. // (+(+1))
  93756. // (+(++1))
  93757. //
  93758. // We need to emit a space in both cases. In the first case, the absence of a space will make
  93759. // the resulting expression a prefix increment operation. And in the second, it will make the resulting
  93760. // expression a prefix increment whose operand is a plus expression - (++(+x))
  93761. // The same is true of minus of course.
  93762. var operand = node.operand;
  93763. return operand.kind === 207 /* PrefixUnaryExpression */
  93764. && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
  93765. || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
  93766. }
  93767. function emitPostfixUnaryExpression(node) {
  93768. emitExpression(node.operand);
  93769. writeTokenText(node.operator, writeOperator);
  93770. }
  93771. var EmitBinaryExpressionState;
  93772. (function (EmitBinaryExpressionState) {
  93773. EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
  93774. EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
  93775. EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
  93776. })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
  93777. /**
  93778. * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
  93779. * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
  93780. * not require notification/substitution/comment/sourcemap decorations.
  93781. */
  93782. function emitBinaryExpression(node) {
  93783. var nodeStack = [node];
  93784. var stateStack = [0 /* EmitLeft */];
  93785. var stackIndex = 0;
  93786. while (stackIndex >= 0) {
  93787. node = nodeStack[stackIndex];
  93788. switch (stateStack[stackIndex]) {
  93789. case 0 /* EmitLeft */: {
  93790. maybePipelineEmitExpression(node.left);
  93791. break;
  93792. }
  93793. case 1 /* EmitRight */: {
  93794. var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
  93795. var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
  93796. var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
  93797. increaseIndentIf(indentBeforeOperator, isCommaOperator);
  93798. emitLeadingCommentsOfPosition(node.operatorToken.pos);
  93799. writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
  93800. emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
  93801. increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true);
  93802. maybePipelineEmitExpression(node.right);
  93803. break;
  93804. }
  93805. case 2 /* FinishEmit */: {
  93806. var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
  93807. var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
  93808. decreaseIndentIf(indentBeforeOperator, indentAfterOperator);
  93809. stackIndex--;
  93810. break;
  93811. }
  93812. default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
  93813. }
  93814. }
  93815. function maybePipelineEmitExpression(next) {
  93816. // Advance the state of this unit of work,
  93817. stateStack[stackIndex]++;
  93818. // Then actually do the work of emitting the node `next` returned by the prior state
  93819. // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
  93820. // binary expression handling, where possible, to the contained work queue
  93821. // #region trampolinePipelineEmit
  93822. var savedLastNode = lastNode;
  93823. var savedLastSubstitution = lastSubstitution;
  93824. lastNode = next;
  93825. lastSubstitution = undefined;
  93826. var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
  93827. if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
  93828. // If the target pipeline phase is emit directly, and the next node's also a binary expression,
  93829. // skip all the intermediate indirection and push the expression directly onto the work stack
  93830. stackIndex++;
  93831. stateStack[stackIndex] = 0 /* EmitLeft */;
  93832. nodeStack[stackIndex] = next;
  93833. }
  93834. else {
  93835. pipelinePhase(1 /* Expression */, next);
  93836. }
  93837. ts.Debug.assert(lastNode === next);
  93838. lastNode = savedLastNode;
  93839. lastSubstitution = savedLastSubstitution;
  93840. // #endregion trampolinePipelineEmit
  93841. }
  93842. }
  93843. function emitConditionalExpression(node) {
  93844. var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken);
  93845. var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue);
  93846. var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken);
  93847. var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse);
  93848. emitExpression(node.condition);
  93849. increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
  93850. emit(node.questionToken);
  93851. increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
  93852. emitExpression(node.whenTrue);
  93853. decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion);
  93854. increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true);
  93855. emit(node.colonToken);
  93856. increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true);
  93857. emitExpression(node.whenFalse);
  93858. decreaseIndentIf(indentBeforeColon, indentAfterColon);
  93859. }
  93860. function emitTemplateExpression(node) {
  93861. emit(node.head);
  93862. emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
  93863. }
  93864. function emitYieldExpression(node) {
  93865. emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
  93866. emit(node.asteriskToken);
  93867. emitExpressionWithLeadingSpace(node.expression);
  93868. }
  93869. function emitSpreadExpression(node) {
  93870. emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
  93871. emitExpression(node.expression);
  93872. }
  93873. function emitClassExpression(node) {
  93874. generateNameIfNeeded(node.name);
  93875. emitClassDeclarationOrExpression(node);
  93876. }
  93877. function emitExpressionWithTypeArguments(node) {
  93878. emitExpression(node.expression);
  93879. emitTypeArguments(node, node.typeArguments);
  93880. }
  93881. function emitAsExpression(node) {
  93882. emitExpression(node.expression);
  93883. if (node.type) {
  93884. writeSpace();
  93885. writeKeyword("as");
  93886. writeSpace();
  93887. emit(node.type);
  93888. }
  93889. }
  93890. function emitNonNullExpression(node) {
  93891. emitExpression(node.expression);
  93892. writeOperator("!");
  93893. }
  93894. function emitMetaProperty(node) {
  93895. writeToken(node.keywordToken, node.pos, writePunctuation);
  93896. writePunctuation(".");
  93897. emit(node.name);
  93898. }
  93899. //
  93900. // Misc
  93901. //
  93902. function emitTemplateSpan(node) {
  93903. emitExpression(node.expression);
  93904. emit(node.literal);
  93905. }
  93906. //
  93907. // Statements
  93908. //
  93909. function emitBlock(node) {
  93910. emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
  93911. }
  93912. function emitBlockStatements(node, forceSingleLine) {
  93913. emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
  93914. var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
  93915. emitList(node, node.statements, format);
  93916. emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
  93917. }
  93918. function emitVariableStatement(node) {
  93919. emitModifiers(node, node.modifiers);
  93920. emit(node.declarationList);
  93921. writeTrailingSemicolon();
  93922. }
  93923. function emitEmptyStatement(isEmbeddedStatement) {
  93924. // While most trailing semicolons are possibly insignificant, an embedded "empty"
  93925. // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
  93926. if (isEmbeddedStatement) {
  93927. writePunctuation(";");
  93928. }
  93929. else {
  93930. writeTrailingSemicolon();
  93931. }
  93932. }
  93933. function emitExpressionStatement(node) {
  93934. emitExpression(node.expression);
  93935. // Emit semicolon in non json files
  93936. // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
  93937. if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
  93938. writeTrailingSemicolon();
  93939. }
  93940. }
  93941. function emitIfStatement(node) {
  93942. var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
  93943. writeSpace();
  93944. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  93945. emitExpression(node.expression);
  93946. emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  93947. emitEmbeddedStatement(node, node.thenStatement);
  93948. if (node.elseStatement) {
  93949. writeLineOrSpace(node);
  93950. emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
  93951. if (node.elseStatement.kind === 227 /* IfStatement */) {
  93952. writeSpace();
  93953. emit(node.elseStatement);
  93954. }
  93955. else {
  93956. emitEmbeddedStatement(node, node.elseStatement);
  93957. }
  93958. }
  93959. }
  93960. function emitWhileClause(node, startPos) {
  93961. var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
  93962. writeSpace();
  93963. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  93964. emitExpression(node.expression);
  93965. emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  93966. }
  93967. function emitDoStatement(node) {
  93968. emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
  93969. emitEmbeddedStatement(node, node.statement);
  93970. if (ts.isBlock(node.statement)) {
  93971. writeSpace();
  93972. }
  93973. else {
  93974. writeLineOrSpace(node);
  93975. }
  93976. emitWhileClause(node, node.statement.end);
  93977. writeTrailingSemicolon();
  93978. }
  93979. function emitWhileStatement(node) {
  93980. emitWhileClause(node, node.pos);
  93981. emitEmbeddedStatement(node, node.statement);
  93982. }
  93983. function emitForStatement(node) {
  93984. var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
  93985. writeSpace();
  93986. var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
  93987. emitForBinding(node.initializer);
  93988. pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
  93989. emitExpressionWithLeadingSpace(node.condition);
  93990. pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
  93991. emitExpressionWithLeadingSpace(node.incrementor);
  93992. emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
  93993. emitEmbeddedStatement(node, node.statement);
  93994. }
  93995. function emitForInStatement(node) {
  93996. var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
  93997. writeSpace();
  93998. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  93999. emitForBinding(node.initializer);
  94000. writeSpace();
  94001. emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
  94002. writeSpace();
  94003. emitExpression(node.expression);
  94004. emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  94005. emitEmbeddedStatement(node, node.statement);
  94006. }
  94007. function emitForOfStatement(node) {
  94008. var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
  94009. writeSpace();
  94010. emitWithTrailingSpace(node.awaitModifier);
  94011. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  94012. emitForBinding(node.initializer);
  94013. writeSpace();
  94014. emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
  94015. writeSpace();
  94016. emitExpression(node.expression);
  94017. emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  94018. emitEmbeddedStatement(node, node.statement);
  94019. }
  94020. function emitForBinding(node) {
  94021. if (node !== undefined) {
  94022. if (node.kind === 243 /* VariableDeclarationList */) {
  94023. emit(node);
  94024. }
  94025. else {
  94026. emitExpression(node);
  94027. }
  94028. }
  94029. }
  94030. function emitContinueStatement(node) {
  94031. emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
  94032. emitWithLeadingSpace(node.label);
  94033. writeTrailingSemicolon();
  94034. }
  94035. function emitBreakStatement(node) {
  94036. emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
  94037. emitWithLeadingSpace(node.label);
  94038. writeTrailingSemicolon();
  94039. }
  94040. function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
  94041. var node = ts.getParseTreeNode(contextNode);
  94042. var isSimilarNode = node && node.kind === contextNode.kind;
  94043. var startPos = pos;
  94044. if (isSimilarNode && currentSourceFile) {
  94045. pos = ts.skipTrivia(currentSourceFile.text, pos);
  94046. }
  94047. if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
  94048. var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
  94049. if (needsIndent) {
  94050. increaseIndent();
  94051. }
  94052. emitLeadingCommentsOfPosition(startPos);
  94053. if (needsIndent) {
  94054. decreaseIndent();
  94055. }
  94056. }
  94057. pos = writeTokenText(token, writer, pos);
  94058. if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
  94059. emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
  94060. }
  94061. return pos;
  94062. }
  94063. function emitReturnStatement(node) {
  94064. emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
  94065. emitExpressionWithLeadingSpace(node.expression);
  94066. writeTrailingSemicolon();
  94067. }
  94068. function emitWithStatement(node) {
  94069. var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
  94070. writeSpace();
  94071. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  94072. emitExpression(node.expression);
  94073. emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  94074. emitEmbeddedStatement(node, node.statement);
  94075. }
  94076. function emitSwitchStatement(node) {
  94077. var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
  94078. writeSpace();
  94079. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  94080. emitExpression(node.expression);
  94081. emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  94082. writeSpace();
  94083. emit(node.caseBlock);
  94084. }
  94085. function emitLabeledStatement(node) {
  94086. emit(node.label);
  94087. emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
  94088. writeSpace();
  94089. emit(node.statement);
  94090. }
  94091. function emitThrowStatement(node) {
  94092. emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
  94093. emitExpressionWithLeadingSpace(node.expression);
  94094. writeTrailingSemicolon();
  94095. }
  94096. function emitTryStatement(node) {
  94097. emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
  94098. writeSpace();
  94099. emit(node.tryBlock);
  94100. if (node.catchClause) {
  94101. writeLineOrSpace(node);
  94102. emit(node.catchClause);
  94103. }
  94104. if (node.finallyBlock) {
  94105. writeLineOrSpace(node);
  94106. emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
  94107. writeSpace();
  94108. emit(node.finallyBlock);
  94109. }
  94110. }
  94111. function emitDebuggerStatement(node) {
  94112. writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
  94113. writeTrailingSemicolon();
  94114. }
  94115. //
  94116. // Declarations
  94117. //
  94118. function emitVariableDeclaration(node) {
  94119. emit(node.name);
  94120. emit(node.exclamationToken);
  94121. emitTypeAnnotation(node.type);
  94122. emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
  94123. }
  94124. function emitVariableDeclarationList(node) {
  94125. writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
  94126. writeSpace();
  94127. emitList(node, node.declarations, 528 /* VariableDeclarationList */);
  94128. }
  94129. function emitFunctionDeclaration(node) {
  94130. emitFunctionDeclarationOrExpression(node);
  94131. }
  94132. function emitFunctionDeclarationOrExpression(node) {
  94133. emitDecorators(node, node.decorators);
  94134. emitModifiers(node, node.modifiers);
  94135. writeKeyword("function");
  94136. emit(node.asteriskToken);
  94137. writeSpace();
  94138. emitIdentifierName(node.name);
  94139. emitSignatureAndBody(node, emitSignatureHead);
  94140. }
  94141. function emitBlockCallback(_hint, body) {
  94142. emitBlockFunctionBody(body);
  94143. }
  94144. function emitSignatureAndBody(node, emitSignatureHead) {
  94145. var body = node.body;
  94146. if (body) {
  94147. if (ts.isBlock(body)) {
  94148. var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
  94149. if (indentedFlag) {
  94150. increaseIndent();
  94151. }
  94152. pushNameGenerationScope(node);
  94153. ts.forEach(node.parameters, generateNames);
  94154. generateNames(node.body);
  94155. emitSignatureHead(node);
  94156. if (onEmitNode) {
  94157. onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
  94158. }
  94159. else {
  94160. emitBlockFunctionBody(body);
  94161. }
  94162. popNameGenerationScope(node);
  94163. if (indentedFlag) {
  94164. decreaseIndent();
  94165. }
  94166. }
  94167. else {
  94168. emitSignatureHead(node);
  94169. writeSpace();
  94170. emitExpression(body);
  94171. }
  94172. }
  94173. else {
  94174. emitSignatureHead(node);
  94175. writeTrailingSemicolon();
  94176. }
  94177. }
  94178. function emitSignatureHead(node) {
  94179. emitTypeParameters(node, node.typeParameters);
  94180. emitParameters(node, node.parameters);
  94181. emitTypeAnnotation(node.type);
  94182. }
  94183. function shouldEmitBlockFunctionBodyOnSingleLine(body) {
  94184. // We must emit a function body as a single-line body in the following case:
  94185. // * The body has NodeEmitFlags.SingleLine specified.
  94186. // We must emit a function body as a multi-line body in the following cases:
  94187. // * The body is explicitly marked as multi-line.
  94188. // * A non-synthesized body's start and end position are on different lines.
  94189. // * Any statement in the body starts on a new line.
  94190. if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
  94191. return true;
  94192. }
  94193. if (body.multiLine) {
  94194. return false;
  94195. }
  94196. if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
  94197. return false;
  94198. }
  94199. if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */)
  94200. || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) {
  94201. return false;
  94202. }
  94203. var previousStatement;
  94204. for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
  94205. var statement = _b[_a];
  94206. if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) {
  94207. return false;
  94208. }
  94209. previousStatement = statement;
  94210. }
  94211. return true;
  94212. }
  94213. function emitBlockFunctionBody(body) {
  94214. writeSpace();
  94215. writePunctuation("{");
  94216. increaseIndent();
  94217. var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
  94218. ? emitBlockFunctionBodyOnSingleLine
  94219. : emitBlockFunctionBodyWorker;
  94220. if (emitBodyWithDetachedComments) {
  94221. emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
  94222. }
  94223. else {
  94224. emitBlockFunctionBody(body);
  94225. }
  94226. decreaseIndent();
  94227. writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
  94228. }
  94229. function emitBlockFunctionBodyOnSingleLine(body) {
  94230. emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
  94231. }
  94232. function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
  94233. // Emit all the prologue directives (like "use strict").
  94234. var statementOffset = emitPrologueDirectives(body.statements);
  94235. var pos = writer.getTextPos();
  94236. emitHelpers(body);
  94237. if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
  94238. decreaseIndent();
  94239. emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
  94240. increaseIndent();
  94241. }
  94242. else {
  94243. emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
  94244. }
  94245. }
  94246. function emitClassDeclaration(node) {
  94247. emitClassDeclarationOrExpression(node);
  94248. }
  94249. function emitClassDeclarationOrExpression(node) {
  94250. ts.forEach(node.members, generateMemberNames);
  94251. emitDecorators(node, node.decorators);
  94252. emitModifiers(node, node.modifiers);
  94253. writeKeyword("class");
  94254. if (node.name) {
  94255. writeSpace();
  94256. emitIdentifierName(node.name);
  94257. }
  94258. var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
  94259. if (indentedFlag) {
  94260. increaseIndent();
  94261. }
  94262. emitTypeParameters(node, node.typeParameters);
  94263. emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
  94264. writeSpace();
  94265. writePunctuation("{");
  94266. emitList(node, node.members, 129 /* ClassMembers */);
  94267. writePunctuation("}");
  94268. if (indentedFlag) {
  94269. decreaseIndent();
  94270. }
  94271. }
  94272. function emitInterfaceDeclaration(node) {
  94273. emitDecorators(node, node.decorators);
  94274. emitModifiers(node, node.modifiers);
  94275. writeKeyword("interface");
  94276. writeSpace();
  94277. emit(node.name);
  94278. emitTypeParameters(node, node.typeParameters);
  94279. emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
  94280. writeSpace();
  94281. writePunctuation("{");
  94282. emitList(node, node.members, 129 /* InterfaceMembers */);
  94283. writePunctuation("}");
  94284. }
  94285. function emitTypeAliasDeclaration(node) {
  94286. emitDecorators(node, node.decorators);
  94287. emitModifiers(node, node.modifiers);
  94288. writeKeyword("type");
  94289. writeSpace();
  94290. emit(node.name);
  94291. emitTypeParameters(node, node.typeParameters);
  94292. writeSpace();
  94293. writePunctuation("=");
  94294. writeSpace();
  94295. emit(node.type);
  94296. writeTrailingSemicolon();
  94297. }
  94298. function emitEnumDeclaration(node) {
  94299. emitModifiers(node, node.modifiers);
  94300. writeKeyword("enum");
  94301. writeSpace();
  94302. emit(node.name);
  94303. writeSpace();
  94304. writePunctuation("{");
  94305. emitList(node, node.members, 145 /* EnumMembers */);
  94306. writePunctuation("}");
  94307. }
  94308. function emitModuleDeclaration(node) {
  94309. emitModifiers(node, node.modifiers);
  94310. if (~node.flags & 1024 /* GlobalAugmentation */) {
  94311. writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
  94312. writeSpace();
  94313. }
  94314. emit(node.name);
  94315. var body = node.body;
  94316. if (!body)
  94317. return writeTrailingSemicolon();
  94318. while (body.kind === 249 /* ModuleDeclaration */) {
  94319. writePunctuation(".");
  94320. emit(body.name);
  94321. body = body.body;
  94322. }
  94323. writeSpace();
  94324. emit(body);
  94325. }
  94326. function emitModuleBlock(node) {
  94327. pushNameGenerationScope(node);
  94328. ts.forEach(node.statements, generateNames);
  94329. emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
  94330. popNameGenerationScope(node);
  94331. }
  94332. function emitCaseBlock(node) {
  94333. emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
  94334. emitList(node, node.clauses, 129 /* CaseBlockClauses */);
  94335. emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
  94336. }
  94337. function emitImportEqualsDeclaration(node) {
  94338. emitModifiers(node, node.modifiers);
  94339. emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
  94340. writeSpace();
  94341. emit(node.name);
  94342. writeSpace();
  94343. emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
  94344. writeSpace();
  94345. emitModuleReference(node.moduleReference);
  94346. writeTrailingSemicolon();
  94347. }
  94348. function emitModuleReference(node) {
  94349. if (node.kind === 75 /* Identifier */) {
  94350. emitExpression(node);
  94351. }
  94352. else {
  94353. emit(node);
  94354. }
  94355. }
  94356. function emitImportDeclaration(node) {
  94357. emitModifiers(node, node.modifiers);
  94358. emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
  94359. writeSpace();
  94360. if (node.importClause) {
  94361. emit(node.importClause);
  94362. writeSpace();
  94363. emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
  94364. writeSpace();
  94365. }
  94366. emitExpression(node.moduleSpecifier);
  94367. writeTrailingSemicolon();
  94368. }
  94369. function emitImportClause(node) {
  94370. if (node.isTypeOnly) {
  94371. emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
  94372. writeSpace();
  94373. }
  94374. emit(node.name);
  94375. if (node.name && node.namedBindings) {
  94376. emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
  94377. writeSpace();
  94378. }
  94379. emit(node.namedBindings);
  94380. }
  94381. function emitNamespaceImport(node) {
  94382. var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
  94383. writeSpace();
  94384. emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
  94385. writeSpace();
  94386. emit(node.name);
  94387. }
  94388. function emitNamedImports(node) {
  94389. emitNamedImportsOrExports(node);
  94390. }
  94391. function emitImportSpecifier(node) {
  94392. emitImportOrExportSpecifier(node);
  94393. }
  94394. function emitExportAssignment(node) {
  94395. var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
  94396. writeSpace();
  94397. if (node.isExportEquals) {
  94398. emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
  94399. }
  94400. else {
  94401. emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
  94402. }
  94403. writeSpace();
  94404. emitExpression(node.expression);
  94405. writeTrailingSemicolon();
  94406. }
  94407. function emitExportDeclaration(node) {
  94408. var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
  94409. writeSpace();
  94410. if (node.isTypeOnly) {
  94411. nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
  94412. writeSpace();
  94413. }
  94414. if (node.exportClause) {
  94415. emit(node.exportClause);
  94416. }
  94417. else {
  94418. nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
  94419. }
  94420. if (node.moduleSpecifier) {
  94421. writeSpace();
  94422. var fromPos = node.exportClause ? node.exportClause.end : nextPos;
  94423. emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
  94424. writeSpace();
  94425. emitExpression(node.moduleSpecifier);
  94426. }
  94427. writeTrailingSemicolon();
  94428. }
  94429. function emitNamespaceExportDeclaration(node) {
  94430. var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
  94431. writeSpace();
  94432. nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
  94433. writeSpace();
  94434. nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
  94435. writeSpace();
  94436. emit(node.name);
  94437. writeTrailingSemicolon();
  94438. }
  94439. function emitNamespaceExport(node) {
  94440. var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
  94441. writeSpace();
  94442. emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
  94443. writeSpace();
  94444. emit(node.name);
  94445. }
  94446. function emitNamedExports(node) {
  94447. emitNamedImportsOrExports(node);
  94448. }
  94449. function emitExportSpecifier(node) {
  94450. emitImportOrExportSpecifier(node);
  94451. }
  94452. function emitNamedImportsOrExports(node) {
  94453. writePunctuation("{");
  94454. emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
  94455. writePunctuation("}");
  94456. }
  94457. function emitImportOrExportSpecifier(node) {
  94458. if (node.propertyName) {
  94459. emit(node.propertyName);
  94460. writeSpace();
  94461. emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
  94462. writeSpace();
  94463. }
  94464. emit(node.name);
  94465. }
  94466. //
  94467. // Module references
  94468. //
  94469. function emitExternalModuleReference(node) {
  94470. writeKeyword("require");
  94471. writePunctuation("(");
  94472. emitExpression(node.expression);
  94473. writePunctuation(")");
  94474. }
  94475. //
  94476. // JSX
  94477. //
  94478. function emitJsxElement(node) {
  94479. emit(node.openingElement);
  94480. emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
  94481. emit(node.closingElement);
  94482. }
  94483. function emitJsxSelfClosingElement(node) {
  94484. writePunctuation("<");
  94485. emitJsxTagName(node.tagName);
  94486. emitTypeArguments(node, node.typeArguments);
  94487. writeSpace();
  94488. emit(node.attributes);
  94489. writePunctuation("/>");
  94490. }
  94491. function emitJsxFragment(node) {
  94492. emit(node.openingFragment);
  94493. emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
  94494. emit(node.closingFragment);
  94495. }
  94496. function emitJsxOpeningElementOrFragment(node) {
  94497. writePunctuation("<");
  94498. if (ts.isJsxOpeningElement(node)) {
  94499. emitJsxTagName(node.tagName);
  94500. emitTypeArguments(node, node.typeArguments);
  94501. if (node.attributes.properties && node.attributes.properties.length > 0) {
  94502. writeSpace();
  94503. }
  94504. emit(node.attributes);
  94505. }
  94506. writePunctuation(">");
  94507. }
  94508. function emitJsxText(node) {
  94509. writer.writeLiteral(node.text);
  94510. }
  94511. function emitJsxClosingElementOrFragment(node) {
  94512. writePunctuation("</");
  94513. if (ts.isJsxClosingElement(node)) {
  94514. emitJsxTagName(node.tagName);
  94515. }
  94516. writePunctuation(">");
  94517. }
  94518. function emitJsxAttributes(node) {
  94519. emitList(node, node.properties, 262656 /* JsxElementAttributes */);
  94520. }
  94521. function emitJsxAttribute(node) {
  94522. emit(node.name);
  94523. emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
  94524. }
  94525. function emitJsxSpreadAttribute(node) {
  94526. writePunctuation("{...");
  94527. emitExpression(node.expression);
  94528. writePunctuation("}");
  94529. }
  94530. function emitJsxExpression(node) {
  94531. if (node.expression) {
  94532. writePunctuation("{");
  94533. emit(node.dotDotDotToken);
  94534. emitExpression(node.expression);
  94535. writePunctuation("}");
  94536. }
  94537. }
  94538. function emitJsxTagName(node) {
  94539. if (node.kind === 75 /* Identifier */) {
  94540. emitExpression(node);
  94541. }
  94542. else {
  94543. emit(node);
  94544. }
  94545. }
  94546. //
  94547. // Clauses
  94548. //
  94549. function emitCaseClause(node) {
  94550. emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
  94551. writeSpace();
  94552. emitExpression(node.expression);
  94553. emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
  94554. }
  94555. function emitDefaultClause(node) {
  94556. var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
  94557. emitCaseOrDefaultClauseRest(node, node.statements, pos);
  94558. }
  94559. function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
  94560. var emitAsSingleStatement = statements.length === 1 &&
  94561. (
  94562. // treat synthesized nodes as located on the same line for emit purposes
  94563. ts.nodeIsSynthesized(parentNode) ||
  94564. ts.nodeIsSynthesized(statements[0]) ||
  94565. ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
  94566. var format = 163969 /* CaseOrDefaultClauseStatements */;
  94567. if (emitAsSingleStatement) {
  94568. writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
  94569. writeSpace();
  94570. format &= ~(1 /* MultiLine */ | 128 /* Indented */);
  94571. }
  94572. else {
  94573. emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
  94574. }
  94575. emitList(parentNode, statements, format);
  94576. }
  94577. function emitHeritageClause(node) {
  94578. writeSpace();
  94579. writeTokenText(node.token, writeKeyword);
  94580. writeSpace();
  94581. emitList(node, node.types, 528 /* HeritageClauseTypes */);
  94582. }
  94583. function emitCatchClause(node) {
  94584. var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
  94585. writeSpace();
  94586. if (node.variableDeclaration) {
  94587. emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
  94588. emit(node.variableDeclaration);
  94589. emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
  94590. writeSpace();
  94591. }
  94592. emit(node.block);
  94593. }
  94594. //
  94595. // Property assignments
  94596. //
  94597. function emitPropertyAssignment(node) {
  94598. emit(node.name);
  94599. writePunctuation(":");
  94600. writeSpace();
  94601. // This is to ensure that we emit comment in the following case:
  94602. // For example:
  94603. // obj = {
  94604. // id: /*comment1*/ ()=>void
  94605. // }
  94606. // "comment1" is not considered to be leading comment for node.initializer
  94607. // but rather a trailing comment on the previous node.
  94608. var initializer = node.initializer;
  94609. if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
  94610. var commentRange = ts.getCommentRange(initializer);
  94611. emitTrailingCommentsOfPosition(commentRange.pos);
  94612. }
  94613. emitExpression(initializer);
  94614. }
  94615. function emitShorthandPropertyAssignment(node) {
  94616. emit(node.name);
  94617. if (node.objectAssignmentInitializer) {
  94618. writeSpace();
  94619. writePunctuation("=");
  94620. writeSpace();
  94621. emitExpression(node.objectAssignmentInitializer);
  94622. }
  94623. }
  94624. function emitSpreadAssignment(node) {
  94625. if (node.expression) {
  94626. emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
  94627. emitExpression(node.expression);
  94628. }
  94629. }
  94630. //
  94631. // Enum
  94632. //
  94633. function emitEnumMember(node) {
  94634. emit(node.name);
  94635. emitInitializer(node.initializer, node.name.end, node);
  94636. }
  94637. //
  94638. // JSDoc
  94639. //
  94640. function emitJSDoc(node) {
  94641. write("/**");
  94642. if (node.comment) {
  94643. var lines = node.comment.split(/\r\n?|\n/g);
  94644. for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
  94645. var line = lines_2[_a];
  94646. writeLine();
  94647. writeSpace();
  94648. writePunctuation("*");
  94649. writeSpace();
  94650. write(line);
  94651. }
  94652. }
  94653. if (node.tags) {
  94654. if (node.tags.length === 1 && node.tags[0].kind === 319 /* JSDocTypeTag */ && !node.comment) {
  94655. writeSpace();
  94656. emit(node.tags[0]);
  94657. }
  94658. else {
  94659. emitList(node, node.tags, 33 /* JSDocComment */);
  94660. }
  94661. }
  94662. writeSpace();
  94663. write("*/");
  94664. }
  94665. function emitJSDocSimpleTypedTag(tag) {
  94666. emitJSDocTagName(tag.tagName);
  94667. emitJSDocTypeExpression(tag.typeExpression);
  94668. emitJSDocComment(tag.comment);
  94669. }
  94670. function emitJSDocAugmentsTag(tag) {
  94671. emitJSDocTagName(tag.tagName);
  94672. writeSpace();
  94673. writePunctuation("{");
  94674. emit(tag.class);
  94675. writePunctuation("}");
  94676. emitJSDocComment(tag.comment);
  94677. }
  94678. function emitJSDocTemplateTag(tag) {
  94679. emitJSDocTagName(tag.tagName);
  94680. emitJSDocTypeExpression(tag.constraint);
  94681. writeSpace();
  94682. emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
  94683. emitJSDocComment(tag.comment);
  94684. }
  94685. function emitJSDocTypedefTag(tag) {
  94686. emitJSDocTagName(tag.tagName);
  94687. if (tag.typeExpression) {
  94688. if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
  94689. emitJSDocTypeExpression(tag.typeExpression);
  94690. }
  94691. else {
  94692. writeSpace();
  94693. writePunctuation("{");
  94694. write("Object");
  94695. if (tag.typeExpression.isArrayType) {
  94696. writePunctuation("[");
  94697. writePunctuation("]");
  94698. }
  94699. writePunctuation("}");
  94700. }
  94701. }
  94702. if (tag.fullName) {
  94703. writeSpace();
  94704. emit(tag.fullName);
  94705. }
  94706. emitJSDocComment(tag.comment);
  94707. if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
  94708. emitJSDocTypeLiteral(tag.typeExpression);
  94709. }
  94710. }
  94711. function emitJSDocCallbackTag(tag) {
  94712. emitJSDocTagName(tag.tagName);
  94713. if (tag.name) {
  94714. writeSpace();
  94715. emit(tag.name);
  94716. }
  94717. emitJSDocComment(tag.comment);
  94718. emitJSDocSignature(tag.typeExpression);
  94719. }
  94720. function emitJSDocSimpleTag(tag) {
  94721. emitJSDocTagName(tag.tagName);
  94722. emitJSDocComment(tag.comment);
  94723. }
  94724. function emitJSDocTypeLiteral(lit) {
  94725. emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
  94726. }
  94727. function emitJSDocSignature(sig) {
  94728. if (sig.typeParameters) {
  94729. emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
  94730. }
  94731. if (sig.parameters) {
  94732. emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
  94733. }
  94734. if (sig.type) {
  94735. writeLine();
  94736. writeSpace();
  94737. writePunctuation("*");
  94738. writeSpace();
  94739. emit(sig.type);
  94740. }
  94741. }
  94742. function emitJSDocPropertyLikeTag(param) {
  94743. emitJSDocTagName(param.tagName);
  94744. emitJSDocTypeExpression(param.typeExpression);
  94745. writeSpace();
  94746. if (param.isBracketed) {
  94747. writePunctuation("[");
  94748. }
  94749. emit(param.name);
  94750. if (param.isBracketed) {
  94751. writePunctuation("]");
  94752. }
  94753. emitJSDocComment(param.comment);
  94754. }
  94755. function emitJSDocTagName(tagName) {
  94756. writePunctuation("@");
  94757. emit(tagName);
  94758. }
  94759. function emitJSDocComment(comment) {
  94760. if (comment) {
  94761. writeSpace();
  94762. write(comment);
  94763. }
  94764. }
  94765. function emitJSDocTypeExpression(typeExpression) {
  94766. if (typeExpression) {
  94767. writeSpace();
  94768. writePunctuation("{");
  94769. emit(typeExpression.type);
  94770. writePunctuation("}");
  94771. }
  94772. }
  94773. //
  94774. // Top-level nodes
  94775. //
  94776. function emitSourceFile(node) {
  94777. writeLine();
  94778. var statements = node.statements;
  94779. if (emitBodyWithDetachedComments) {
  94780. // Emit detached comment if there are no prologue directives or if the first node is synthesized.
  94781. // The synthesized node will have no leading comment so some comments may be missed.
  94782. var shouldEmitDetachedComment = statements.length === 0 ||
  94783. !ts.isPrologueDirective(statements[0]) ||
  94784. ts.nodeIsSynthesized(statements[0]);
  94785. if (shouldEmitDetachedComment) {
  94786. emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
  94787. return;
  94788. }
  94789. }
  94790. emitSourceFileWorker(node);
  94791. }
  94792. function emitSyntheticTripleSlashReferencesIfNeeded(node) {
  94793. emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
  94794. for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
  94795. var prepend = _b[_a];
  94796. if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
  94797. for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
  94798. var ref = _d[_c];
  94799. emit(ref);
  94800. writeLine();
  94801. }
  94802. }
  94803. }
  94804. }
  94805. function emitTripleSlashDirectivesIfNeeded(node) {
  94806. if (node.isDeclarationFile)
  94807. emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
  94808. }
  94809. function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
  94810. if (hasNoDefaultLib) {
  94811. var pos = writer.getTextPos();
  94812. writeComment("/// <reference no-default-lib=\"true\"/>");
  94813. if (bundleFileInfo)
  94814. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
  94815. writeLine();
  94816. }
  94817. if (currentSourceFile && currentSourceFile.moduleName) {
  94818. writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
  94819. writeLine();
  94820. }
  94821. if (currentSourceFile && currentSourceFile.amdDependencies) {
  94822. for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
  94823. var dep = _b[_a];
  94824. if (dep.name) {
  94825. writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
  94826. }
  94827. else {
  94828. writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
  94829. }
  94830. writeLine();
  94831. }
  94832. }
  94833. for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
  94834. var directive = files_1[_c];
  94835. var pos = writer.getTextPos();
  94836. writeComment("/// <reference path=\"" + directive.fileName + "\" />");
  94837. if (bundleFileInfo)
  94838. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
  94839. writeLine();
  94840. }
  94841. for (var _d = 0, types_21 = types; _d < types_21.length; _d++) {
  94842. var directive = types_21[_d];
  94843. var pos = writer.getTextPos();
  94844. writeComment("/// <reference types=\"" + directive.fileName + "\" />");
  94845. if (bundleFileInfo)
  94846. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
  94847. writeLine();
  94848. }
  94849. for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
  94850. var directive = libs_1[_e];
  94851. var pos = writer.getTextPos();
  94852. writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
  94853. if (bundleFileInfo)
  94854. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
  94855. writeLine();
  94856. }
  94857. }
  94858. function emitSourceFileWorker(node) {
  94859. var statements = node.statements;
  94860. pushNameGenerationScope(node);
  94861. ts.forEach(node.statements, generateNames);
  94862. emitHelpers(node);
  94863. var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
  94864. emitTripleSlashDirectivesIfNeeded(node);
  94865. emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
  94866. popNameGenerationScope(node);
  94867. }
  94868. // Transformation nodes
  94869. function emitPartiallyEmittedExpression(node) {
  94870. emitExpression(node.expression);
  94871. }
  94872. function emitCommaList(node) {
  94873. emitExpressionList(node, node.elements, 528 /* CommaListElements */);
  94874. }
  94875. /**
  94876. * Emits any prologue directives at the start of a Statement list, returning the
  94877. * number of prologue directives written to the output.
  94878. */
  94879. function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
  94880. var needsToSetSourceFile = !!sourceFile;
  94881. for (var i = 0; i < statements.length; i++) {
  94882. var statement = statements[i];
  94883. if (ts.isPrologueDirective(statement)) {
  94884. var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
  94885. if (shouldEmitPrologueDirective) {
  94886. if (needsToSetSourceFile) {
  94887. needsToSetSourceFile = false;
  94888. setSourceFile(sourceFile);
  94889. }
  94890. writeLine();
  94891. var pos = writer.getTextPos();
  94892. emit(statement);
  94893. if (recordBundleFileSection && bundleFileInfo)
  94894. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
  94895. if (seenPrologueDirectives) {
  94896. seenPrologueDirectives.set(statement.expression.text, true);
  94897. }
  94898. }
  94899. }
  94900. else {
  94901. // return index of the first non prologue directive
  94902. return i;
  94903. }
  94904. }
  94905. return statements.length;
  94906. }
  94907. function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
  94908. for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
  94909. var prologue = prologues_1[_a];
  94910. if (!seenPrologueDirectives.has(prologue.data)) {
  94911. writeLine();
  94912. var pos = writer.getTextPos();
  94913. emit(prologue);
  94914. if (bundleFileInfo)
  94915. bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
  94916. if (seenPrologueDirectives) {
  94917. seenPrologueDirectives.set(prologue.data, true);
  94918. }
  94919. }
  94920. }
  94921. }
  94922. function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
  94923. if (ts.isSourceFile(sourceFileOrBundle)) {
  94924. emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
  94925. }
  94926. else {
  94927. var seenPrologueDirectives = ts.createMap();
  94928. for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
  94929. var prepend = _b[_a];
  94930. emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
  94931. }
  94932. for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
  94933. var sourceFile = _d[_c];
  94934. emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
  94935. }
  94936. setSourceFile(undefined);
  94937. }
  94938. }
  94939. function getPrologueDirectivesFromBundledSourceFiles(bundle) {
  94940. var seenPrologueDirectives = ts.createMap();
  94941. var prologues;
  94942. for (var index = 0; index < bundle.sourceFiles.length; index++) {
  94943. var sourceFile = bundle.sourceFiles[index];
  94944. var directives = void 0;
  94945. var end = 0;
  94946. for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
  94947. var statement = _b[_a];
  94948. if (!ts.isPrologueDirective(statement))
  94949. break;
  94950. if (seenPrologueDirectives.has(statement.expression.text))
  94951. continue;
  94952. seenPrologueDirectives.set(statement.expression.text, true);
  94953. (directives || (directives = [])).push({
  94954. pos: statement.pos,
  94955. end: statement.end,
  94956. expression: {
  94957. pos: statement.expression.pos,
  94958. end: statement.expression.end,
  94959. text: statement.expression.text
  94960. }
  94961. });
  94962. end = end < statement.end ? statement.end : end;
  94963. }
  94964. if (directives)
  94965. (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
  94966. }
  94967. return prologues;
  94968. }
  94969. function emitShebangIfNeeded(sourceFileOrBundle) {
  94970. if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
  94971. var shebang = ts.getShebang(sourceFileOrBundle.text);
  94972. if (shebang) {
  94973. writeComment(shebang);
  94974. writeLine();
  94975. return true;
  94976. }
  94977. }
  94978. else {
  94979. for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
  94980. var prepend = _b[_a];
  94981. ts.Debug.assertNode(prepend, ts.isUnparsedSource);
  94982. if (emitShebangIfNeeded(prepend)) {
  94983. return true;
  94984. }
  94985. }
  94986. for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
  94987. var sourceFile = _d[_c];
  94988. // Emit only the first encountered shebang
  94989. if (emitShebangIfNeeded(sourceFile)) {
  94990. return true;
  94991. }
  94992. }
  94993. }
  94994. }
  94995. //
  94996. // Helpers
  94997. //
  94998. function emitNodeWithWriter(node, writer) {
  94999. if (!node)
  95000. return;
  95001. var savedWrite = write;
  95002. write = writer;
  95003. emit(node);
  95004. write = savedWrite;
  95005. }
  95006. function emitModifiers(node, modifiers) {
  95007. if (modifiers && modifiers.length) {
  95008. emitList(node, modifiers, 262656 /* Modifiers */);
  95009. writeSpace();
  95010. }
  95011. }
  95012. function emitTypeAnnotation(node) {
  95013. if (node) {
  95014. writePunctuation(":");
  95015. writeSpace();
  95016. emit(node);
  95017. }
  95018. }
  95019. function emitInitializer(node, equalCommentStartPos, container) {
  95020. if (node) {
  95021. writeSpace();
  95022. emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
  95023. writeSpace();
  95024. emitExpression(node);
  95025. }
  95026. }
  95027. function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
  95028. if (node) {
  95029. prefixWriter(prefix);
  95030. emit(node);
  95031. }
  95032. }
  95033. function emitWithLeadingSpace(node) {
  95034. if (node) {
  95035. writeSpace();
  95036. emit(node);
  95037. }
  95038. }
  95039. function emitExpressionWithLeadingSpace(node) {
  95040. if (node) {
  95041. writeSpace();
  95042. emitExpression(node);
  95043. }
  95044. }
  95045. function emitWithTrailingSpace(node) {
  95046. if (node) {
  95047. emit(node);
  95048. writeSpace();
  95049. }
  95050. }
  95051. function emitEmbeddedStatement(parent, node) {
  95052. if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
  95053. writeSpace();
  95054. emit(node);
  95055. }
  95056. else {
  95057. writeLine();
  95058. increaseIndent();
  95059. if (ts.isEmptyStatement(node)) {
  95060. pipelineEmit(5 /* EmbeddedStatement */, node);
  95061. }
  95062. else {
  95063. emit(node);
  95064. }
  95065. decreaseIndent();
  95066. }
  95067. }
  95068. function emitDecorators(parentNode, decorators) {
  95069. emitList(parentNode, decorators, 49153 /* Decorators */);
  95070. }
  95071. function emitTypeArguments(parentNode, typeArguments) {
  95072. emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
  95073. }
  95074. function emitTypeParameters(parentNode, typeParameters) {
  95075. if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
  95076. return emitTypeArguments(parentNode, parentNode.typeArguments);
  95077. }
  95078. emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
  95079. }
  95080. function emitParameters(parentNode, parameters) {
  95081. emitList(parentNode, parameters, 2576 /* Parameters */);
  95082. }
  95083. function canEmitSimpleArrowHead(parentNode, parameters) {
  95084. var parameter = ts.singleOrUndefined(parameters);
  95085. return parameter
  95086. && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
  95087. && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
  95088. && !parentNode.type // arrow function may not have return type annotation
  95089. && !ts.some(parentNode.decorators) // parent may not have decorators
  95090. && !ts.some(parentNode.modifiers) // parent may not have modifiers
  95091. && !ts.some(parentNode.typeParameters) // parent may not have type parameters
  95092. && !ts.some(parameter.decorators) // parameter may not have decorators
  95093. && !ts.some(parameter.modifiers) // parameter may not have modifiers
  95094. && !parameter.dotDotDotToken // parameter may not be rest
  95095. && !parameter.questionToken // parameter may not be optional
  95096. && !parameter.type // parameter may not have a type annotation
  95097. && !parameter.initializer // parameter may not have an initializer
  95098. && ts.isIdentifier(parameter.name); // parameter name must be identifier
  95099. }
  95100. function emitParametersForArrow(parentNode, parameters) {
  95101. if (canEmitSimpleArrowHead(parentNode, parameters)) {
  95102. emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
  95103. }
  95104. else {
  95105. emitParameters(parentNode, parameters);
  95106. }
  95107. }
  95108. function emitParametersForIndexSignature(parentNode, parameters) {
  95109. emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
  95110. }
  95111. function emitList(parentNode, children, format, start, count) {
  95112. emitNodeList(emit, parentNode, children, format, start, count);
  95113. }
  95114. function emitExpressionList(parentNode, children, format, start, count) {
  95115. emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
  95116. }
  95117. function writeDelimiter(format) {
  95118. switch (format & 60 /* DelimitersMask */) {
  95119. case 0 /* None */:
  95120. break;
  95121. case 16 /* CommaDelimited */:
  95122. writePunctuation(",");
  95123. break;
  95124. case 4 /* BarDelimited */:
  95125. writeSpace();
  95126. writePunctuation("|");
  95127. break;
  95128. case 32 /* AsteriskDelimited */:
  95129. writeSpace();
  95130. writePunctuation("*");
  95131. writeSpace();
  95132. break;
  95133. case 8 /* AmpersandDelimited */:
  95134. writeSpace();
  95135. writePunctuation("&");
  95136. break;
  95137. }
  95138. }
  95139. function emitNodeList(emit, parentNode, children, format, start, count) {
  95140. if (start === void 0) { start = 0; }
  95141. if (count === void 0) { count = children ? children.length - start : 0; }
  95142. var isUndefined = children === undefined;
  95143. if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
  95144. return;
  95145. }
  95146. var isEmpty = children === undefined || start >= children.length || count === 0;
  95147. if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
  95148. if (onBeforeEmitNodeArray) {
  95149. onBeforeEmitNodeArray(children);
  95150. }
  95151. if (onAfterEmitNodeArray) {
  95152. onAfterEmitNodeArray(children);
  95153. }
  95154. return;
  95155. }
  95156. if (format & 15360 /* BracketsMask */) {
  95157. writePunctuation(getOpeningBracket(format));
  95158. if (isEmpty && !isUndefined) {
  95159. // TODO: GH#18217
  95160. emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
  95161. }
  95162. }
  95163. if (onBeforeEmitNodeArray) {
  95164. onBeforeEmitNodeArray(children);
  95165. }
  95166. if (isEmpty) {
  95167. // Write a line terminator if the parent node was multi-line
  95168. if (format & 1 /* MultiLine */) {
  95169. writeLine();
  95170. }
  95171. else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
  95172. writeSpace();
  95173. }
  95174. }
  95175. else {
  95176. // Write the opening line terminator or leading whitespace.
  95177. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
  95178. var shouldEmitInterveningComments = mayEmitInterveningComments;
  95179. if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217
  95180. writeLine();
  95181. shouldEmitInterveningComments = false;
  95182. }
  95183. else if (format & 256 /* SpaceBetweenBraces */) {
  95184. writeSpace();
  95185. }
  95186. // Increase the indent, if requested.
  95187. if (format & 128 /* Indented */) {
  95188. increaseIndent();
  95189. }
  95190. // Emit each child.
  95191. var previousSibling = void 0;
  95192. var previousSourceFileTextKind = void 0;
  95193. var shouldDecreaseIndentAfterEmit = false;
  95194. for (var i = 0; i < count; i++) {
  95195. var child = children[start + i];
  95196. // Write the delimiter if this is not the first node.
  95197. if (format & 32 /* AsteriskDelimited */) {
  95198. // always write JSDoc in the format "\n *"
  95199. writeLine();
  95200. writeDelimiter(format);
  95201. }
  95202. else if (previousSibling) {
  95203. // i.e
  95204. // function commentedParameters(
  95205. // /* Parameter a */
  95206. // a
  95207. // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
  95208. // ,
  95209. if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
  95210. emitLeadingCommentsOfPosition(previousSibling.end);
  95211. }
  95212. writeDelimiter(format);
  95213. recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
  95214. // Write either a line terminator or whitespace to separate the elements.
  95215. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
  95216. // If a synthesized node in a single-line list starts on a new
  95217. // line, we should increase the indent.
  95218. if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
  95219. increaseIndent();
  95220. shouldDecreaseIndentAfterEmit = true;
  95221. }
  95222. writeLine();
  95223. shouldEmitInterveningComments = false;
  95224. }
  95225. else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
  95226. writeSpace();
  95227. }
  95228. }
  95229. // Emit this child.
  95230. previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
  95231. if (shouldEmitInterveningComments) {
  95232. if (emitTrailingCommentsOfPosition) {
  95233. var commentRange = ts.getCommentRange(child);
  95234. emitTrailingCommentsOfPosition(commentRange.pos);
  95235. }
  95236. }
  95237. else {
  95238. shouldEmitInterveningComments = mayEmitInterveningComments;
  95239. }
  95240. emit(child);
  95241. if (shouldDecreaseIndentAfterEmit) {
  95242. decreaseIndent();
  95243. shouldDecreaseIndentAfterEmit = false;
  95244. }
  95245. previousSibling = child;
  95246. }
  95247. // Write a trailing comma, if requested.
  95248. var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
  95249. if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
  95250. writePunctuation(",");
  95251. }
  95252. // Emit any trailing comment of the last element in the list
  95253. // i.e
  95254. // var array = [...
  95255. // 2
  95256. // /* end of element 2 */
  95257. // ];
  95258. if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
  95259. emitLeadingCommentsOfPosition(previousSibling.end);
  95260. }
  95261. // Decrease the indent, if requested.
  95262. if (format & 128 /* Indented */) {
  95263. decreaseIndent();
  95264. }
  95265. recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
  95266. // Write the closing line terminator or closing whitespace.
  95267. if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
  95268. writeLine();
  95269. }
  95270. else if (format & 256 /* SpaceBetweenBraces */) {
  95271. writeSpace();
  95272. }
  95273. }
  95274. if (onAfterEmitNodeArray) {
  95275. onAfterEmitNodeArray(children);
  95276. }
  95277. if (format & 15360 /* BracketsMask */) {
  95278. if (isEmpty && !isUndefined) {
  95279. // TODO: GH#18217
  95280. emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
  95281. }
  95282. writePunctuation(getClosingBracket(format));
  95283. }
  95284. }
  95285. // Writers
  95286. function writeLiteral(s) {
  95287. writer.writeLiteral(s);
  95288. }
  95289. function writeStringLiteral(s) {
  95290. writer.writeStringLiteral(s);
  95291. }
  95292. function writeBase(s) {
  95293. writer.write(s);
  95294. }
  95295. function writeSymbol(s, sym) {
  95296. writer.writeSymbol(s, sym);
  95297. }
  95298. function writePunctuation(s) {
  95299. writer.writePunctuation(s);
  95300. }
  95301. function writeTrailingSemicolon() {
  95302. writer.writeTrailingSemicolon(";");
  95303. }
  95304. function writeKeyword(s) {
  95305. writer.writeKeyword(s);
  95306. }
  95307. function writeOperator(s) {
  95308. writer.writeOperator(s);
  95309. }
  95310. function writeParameter(s) {
  95311. writer.writeParameter(s);
  95312. }
  95313. function writeComment(s) {
  95314. writer.writeComment(s);
  95315. }
  95316. function writeSpace() {
  95317. writer.writeSpace(" ");
  95318. }
  95319. function writeProperty(s) {
  95320. writer.writeProperty(s);
  95321. }
  95322. function writeLine() {
  95323. writer.writeLine();
  95324. }
  95325. function increaseIndent() {
  95326. writer.increaseIndent();
  95327. }
  95328. function decreaseIndent() {
  95329. writer.decreaseIndent();
  95330. }
  95331. function writeToken(token, pos, writer, contextNode) {
  95332. return !sourceMapsDisabled
  95333. ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
  95334. : writeTokenText(token, writer, pos);
  95335. }
  95336. function writeTokenNode(node, writer) {
  95337. if (onBeforeEmitToken) {
  95338. onBeforeEmitToken(node);
  95339. }
  95340. writer(ts.tokenToString(node.kind));
  95341. if (onAfterEmitToken) {
  95342. onAfterEmitToken(node);
  95343. }
  95344. }
  95345. function writeTokenText(token, writer, pos) {
  95346. var tokenString = ts.tokenToString(token);
  95347. writer(tokenString);
  95348. return pos < 0 ? pos : pos + tokenString.length;
  95349. }
  95350. function writeLineOrSpace(node) {
  95351. if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
  95352. writeSpace();
  95353. }
  95354. else {
  95355. writeLine();
  95356. }
  95357. }
  95358. function writeLines(text) {
  95359. var lines = text.split(/\r\n?|\n/g);
  95360. var indentation = ts.guessIndentation(lines);
  95361. for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
  95362. var lineText = lines_3[_a];
  95363. var line = indentation ? lineText.slice(indentation) : lineText;
  95364. if (line.length) {
  95365. writeLine();
  95366. write(line);
  95367. }
  95368. }
  95369. }
  95370. function increaseIndentIf(value, writeSpaceIfNotIndenting) {
  95371. if (value) {
  95372. increaseIndent();
  95373. writeLine();
  95374. }
  95375. else if (writeSpaceIfNotIndenting) {
  95376. writeSpace();
  95377. }
  95378. }
  95379. // Helper function to decrease the indent if we previously indented. Allows multiple
  95380. // previous indent values to be considered at a time. This also allows caller to just
  95381. // call this once, passing in all their appropriate indent values, instead of needing
  95382. // to call this helper function multiple times.
  95383. function decreaseIndentIf(value1, value2) {
  95384. if (value1) {
  95385. decreaseIndent();
  95386. }
  95387. if (value2) {
  95388. decreaseIndent();
  95389. }
  95390. }
  95391. function shouldWriteLeadingLineTerminator(parentNode, children, format) {
  95392. if (format & 1 /* MultiLine */) {
  95393. return true;
  95394. }
  95395. if (format & 2 /* PreserveLines */) {
  95396. if (format & 65536 /* PreferNewLine */) {
  95397. return true;
  95398. }
  95399. var firstChild = children[0];
  95400. if (firstChild === undefined) {
  95401. return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile);
  95402. }
  95403. else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) {
  95404. return synthesizedNodeStartsOnNewLine(firstChild, format);
  95405. }
  95406. else {
  95407. return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile);
  95408. }
  95409. }
  95410. else {
  95411. return false;
  95412. }
  95413. }
  95414. function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) {
  95415. if (format & 1 /* MultiLine */) {
  95416. return true;
  95417. }
  95418. else if (format & 2 /* PreserveLines */) {
  95419. if (previousNode === undefined || nextNode === undefined) {
  95420. return false;
  95421. }
  95422. else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) {
  95423. return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format);
  95424. }
  95425. else {
  95426. return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile);
  95427. }
  95428. }
  95429. else {
  95430. return ts.getStartsOnNewLine(nextNode);
  95431. }
  95432. }
  95433. function shouldWriteClosingLineTerminator(parentNode, children, format) {
  95434. if (format & 1 /* MultiLine */) {
  95435. return (format & 131072 /* NoTrailingNewLine */) === 0;
  95436. }
  95437. else if (format & 2 /* PreserveLines */) {
  95438. if (format & 65536 /* PreferNewLine */) {
  95439. return true;
  95440. }
  95441. var lastChild = ts.lastOrUndefined(children);
  95442. if (lastChild === undefined) {
  95443. return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile);
  95444. }
  95445. else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) {
  95446. return synthesizedNodeStartsOnNewLine(lastChild, format);
  95447. }
  95448. else {
  95449. return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile);
  95450. }
  95451. }
  95452. else {
  95453. return false;
  95454. }
  95455. }
  95456. function synthesizedNodeStartsOnNewLine(node, format) {
  95457. if (ts.nodeIsSynthesized(node)) {
  95458. var startsOnNewLine = ts.getStartsOnNewLine(node);
  95459. if (startsOnNewLine === undefined) {
  95460. return (format & 65536 /* PreferNewLine */) !== 0;
  95461. }
  95462. return startsOnNewLine;
  95463. }
  95464. return (format & 65536 /* PreferNewLine */) !== 0;
  95465. }
  95466. function needsIndentation(parent, node1, node2) {
  95467. if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
  95468. return false;
  95469. }
  95470. parent = skipSynthesizedParentheses(parent);
  95471. node1 = skipSynthesizedParentheses(node1);
  95472. node2 = skipSynthesizedParentheses(node2);
  95473. // Always use a newline for synthesized code if the synthesizer desires it.
  95474. if (ts.getStartsOnNewLine(node2)) {
  95475. return true;
  95476. }
  95477. return !ts.nodeIsSynthesized(parent)
  95478. && !ts.nodeIsSynthesized(node1)
  95479. && !ts.nodeIsSynthesized(node2)
  95480. && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile);
  95481. }
  95482. function isEmptyBlock(block) {
  95483. return block.statements.length === 0
  95484. && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
  95485. }
  95486. function skipSynthesizedParentheses(node) {
  95487. while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
  95488. node = node.expression;
  95489. }
  95490. return node;
  95491. }
  95492. function getTextOfNode(node, includeTrivia) {
  95493. if (ts.isGeneratedIdentifier(node)) {
  95494. return generateName(node);
  95495. }
  95496. else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
  95497. return ts.idText(node);
  95498. }
  95499. else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
  95500. return getTextOfNode(node.textSourceNode, includeTrivia);
  95501. }
  95502. else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
  95503. return node.text;
  95504. }
  95505. return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
  95506. }
  95507. function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
  95508. if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
  95509. var textSourceNode = node.textSourceNode;
  95510. if (ts.isIdentifier(textSourceNode)) {
  95511. return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
  95512. neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
  95513. "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
  95514. }
  95515. else {
  95516. return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
  95517. }
  95518. }
  95519. return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
  95520. }
  95521. /**
  95522. * Push a new name generation scope.
  95523. */
  95524. function pushNameGenerationScope(node) {
  95525. if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
  95526. return;
  95527. }
  95528. tempFlagsStack.push(tempFlags);
  95529. tempFlags = 0;
  95530. reservedNamesStack.push(reservedNames);
  95531. }
  95532. /**
  95533. * Pop the current name generation scope.
  95534. */
  95535. function popNameGenerationScope(node) {
  95536. if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
  95537. return;
  95538. }
  95539. tempFlags = tempFlagsStack.pop();
  95540. reservedNames = reservedNamesStack.pop();
  95541. }
  95542. function reserveNameInNestedScopes(name) {
  95543. if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
  95544. reservedNames = ts.createMap();
  95545. }
  95546. reservedNames.set(name, true);
  95547. }
  95548. function generateNames(node) {
  95549. if (!node)
  95550. return;
  95551. switch (node.kind) {
  95552. case 223 /* Block */:
  95553. ts.forEach(node.statements, generateNames);
  95554. break;
  95555. case 238 /* LabeledStatement */:
  95556. case 236 /* WithStatement */:
  95557. case 228 /* DoStatement */:
  95558. case 229 /* WhileStatement */:
  95559. generateNames(node.statement);
  95560. break;
  95561. case 227 /* IfStatement */:
  95562. generateNames(node.thenStatement);
  95563. generateNames(node.elseStatement);
  95564. break;
  95565. case 230 /* ForStatement */:
  95566. case 232 /* ForOfStatement */:
  95567. case 231 /* ForInStatement */:
  95568. generateNames(node.initializer);
  95569. generateNames(node.statement);
  95570. break;
  95571. case 237 /* SwitchStatement */:
  95572. generateNames(node.caseBlock);
  95573. break;
  95574. case 251 /* CaseBlock */:
  95575. ts.forEach(node.clauses, generateNames);
  95576. break;
  95577. case 277 /* CaseClause */:
  95578. case 278 /* DefaultClause */:
  95579. ts.forEach(node.statements, generateNames);
  95580. break;
  95581. case 240 /* TryStatement */:
  95582. generateNames(node.tryBlock);
  95583. generateNames(node.catchClause);
  95584. generateNames(node.finallyBlock);
  95585. break;
  95586. case 280 /* CatchClause */:
  95587. generateNames(node.variableDeclaration);
  95588. generateNames(node.block);
  95589. break;
  95590. case 225 /* VariableStatement */:
  95591. generateNames(node.declarationList);
  95592. break;
  95593. case 243 /* VariableDeclarationList */:
  95594. ts.forEach(node.declarations, generateNames);
  95595. break;
  95596. case 242 /* VariableDeclaration */:
  95597. case 156 /* Parameter */:
  95598. case 191 /* BindingElement */:
  95599. case 245 /* ClassDeclaration */:
  95600. generateNameIfNeeded(node.name);
  95601. break;
  95602. case 244 /* FunctionDeclaration */:
  95603. generateNameIfNeeded(node.name);
  95604. if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
  95605. ts.forEach(node.parameters, generateNames);
  95606. generateNames(node.body);
  95607. }
  95608. break;
  95609. case 189 /* ObjectBindingPattern */:
  95610. case 190 /* ArrayBindingPattern */:
  95611. ts.forEach(node.elements, generateNames);
  95612. break;
  95613. case 254 /* ImportDeclaration */:
  95614. generateNames(node.importClause);
  95615. break;
  95616. case 255 /* ImportClause */:
  95617. generateNameIfNeeded(node.name);
  95618. generateNames(node.namedBindings);
  95619. break;
  95620. case 256 /* NamespaceImport */:
  95621. generateNameIfNeeded(node.name);
  95622. break;
  95623. case 262 /* NamespaceExport */:
  95624. generateNameIfNeeded(node.name);
  95625. break;
  95626. case 257 /* NamedImports */:
  95627. ts.forEach(node.elements, generateNames);
  95628. break;
  95629. case 258 /* ImportSpecifier */:
  95630. generateNameIfNeeded(node.propertyName || node.name);
  95631. break;
  95632. }
  95633. }
  95634. function generateMemberNames(node) {
  95635. if (!node)
  95636. return;
  95637. switch (node.kind) {
  95638. case 281 /* PropertyAssignment */:
  95639. case 282 /* ShorthandPropertyAssignment */:
  95640. case 159 /* PropertyDeclaration */:
  95641. case 161 /* MethodDeclaration */:
  95642. case 163 /* GetAccessor */:
  95643. case 164 /* SetAccessor */:
  95644. generateNameIfNeeded(node.name);
  95645. break;
  95646. }
  95647. }
  95648. function generateNameIfNeeded(name) {
  95649. if (name) {
  95650. if (ts.isGeneratedIdentifier(name)) {
  95651. generateName(name);
  95652. }
  95653. else if (ts.isBindingPattern(name)) {
  95654. generateNames(name);
  95655. }
  95656. }
  95657. }
  95658. /**
  95659. * Generate the text for a generated identifier.
  95660. */
  95661. function generateName(name) {
  95662. if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
  95663. // Node names generate unique names based on their original node
  95664. // and are cached based on that node's id.
  95665. return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
  95666. }
  95667. else {
  95668. // Auto, Loop, and Unique names are cached based on their unique
  95669. // autoGenerateId.
  95670. var autoGenerateId = name.autoGenerateId;
  95671. return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
  95672. }
  95673. }
  95674. function generateNameCached(node, flags) {
  95675. var nodeId = ts.getNodeId(node);
  95676. return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
  95677. }
  95678. /**
  95679. * Returns a value indicating whether a name is unique globally, within the current file,
  95680. * or within the NameGenerator.
  95681. */
  95682. function isUniqueName(name) {
  95683. return isFileLevelUniqueName(name)
  95684. && !generatedNames.has(name)
  95685. && !(reservedNames && reservedNames.has(name));
  95686. }
  95687. /**
  95688. * Returns a value indicating whether a name is unique globally or within the current file.
  95689. */
  95690. function isFileLevelUniqueName(name) {
  95691. return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
  95692. }
  95693. /**
  95694. * Returns a value indicating whether a name is unique within a container.
  95695. */
  95696. function isUniqueLocalName(name, container) {
  95697. for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
  95698. if (node.locals) {
  95699. var local = node.locals.get(ts.escapeLeadingUnderscores(name));
  95700. // We conservatively include alias symbols to cover cases where they're emitted as locals
  95701. if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
  95702. return false;
  95703. }
  95704. }
  95705. }
  95706. return true;
  95707. }
  95708. /**
  95709. * Return the next available name in the pattern _a ... _z, _0, _1, ...
  95710. * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
  95711. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
  95712. */
  95713. function makeTempVariableName(flags, reservedInNestedScopes) {
  95714. if (flags && !(tempFlags & flags)) {
  95715. var name = flags === 268435456 /* _i */ ? "_i" : "_n";
  95716. if (isUniqueName(name)) {
  95717. tempFlags |= flags;
  95718. if (reservedInNestedScopes) {
  95719. reserveNameInNestedScopes(name);
  95720. }
  95721. return name;
  95722. }
  95723. }
  95724. while (true) {
  95725. var count = tempFlags & 268435455 /* CountMask */;
  95726. tempFlags++;
  95727. // Skip over 'i' and 'n'
  95728. if (count !== 8 && count !== 13) {
  95729. var name = count < 26
  95730. ? "_" + String.fromCharCode(97 /* a */ + count)
  95731. : "_" + (count - 26);
  95732. if (isUniqueName(name)) {
  95733. if (reservedInNestedScopes) {
  95734. reserveNameInNestedScopes(name);
  95735. }
  95736. return name;
  95737. }
  95738. }
  95739. }
  95740. }
  95741. /**
  95742. * Generate a name that is unique within the current file and doesn't conflict with any names
  95743. * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
  95744. * where n is a positive integer. Note that names generated by makeTempVariableName and
  95745. * makeUniqueName are guaranteed to never conflict.
  95746. * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
  95747. */
  95748. function makeUniqueName(baseName, checkFn, optimistic, scoped) {
  95749. if (checkFn === void 0) { checkFn = isUniqueName; }
  95750. if (optimistic) {
  95751. if (checkFn(baseName)) {
  95752. if (scoped) {
  95753. reserveNameInNestedScopes(baseName);
  95754. }
  95755. else {
  95756. generatedNames.set(baseName, true);
  95757. }
  95758. return baseName;
  95759. }
  95760. }
  95761. // Find the first unique 'name_n', where n is a positive number
  95762. if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
  95763. baseName += "_";
  95764. }
  95765. var i = 1;
  95766. while (true) {
  95767. var generatedName = baseName + i;
  95768. if (checkFn(generatedName)) {
  95769. if (scoped) {
  95770. reserveNameInNestedScopes(generatedName);
  95771. }
  95772. else {
  95773. generatedNames.set(generatedName, true);
  95774. }
  95775. return generatedName;
  95776. }
  95777. i++;
  95778. }
  95779. }
  95780. function makeFileLevelOptimisticUniqueName(name) {
  95781. return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
  95782. }
  95783. /**
  95784. * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
  95785. */
  95786. function generateNameForModuleOrEnum(node) {
  95787. var name = getTextOfNode(node.name);
  95788. // Use module/enum name itself if it is unique, otherwise make a unique variation
  95789. return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
  95790. }
  95791. /**
  95792. * Generates a unique name for an ImportDeclaration or ExportDeclaration.
  95793. */
  95794. function generateNameForImportOrExportDeclaration(node) {
  95795. var expr = ts.getExternalModuleName(node); // TODO: GH#18217
  95796. var baseName = ts.isStringLiteral(expr) ?
  95797. ts.makeIdentifierFromModuleName(expr.text) : "module";
  95798. return makeUniqueName(baseName);
  95799. }
  95800. /**
  95801. * Generates a unique name for a default export.
  95802. */
  95803. function generateNameForExportDefault() {
  95804. return makeUniqueName("default");
  95805. }
  95806. /**
  95807. * Generates a unique name for a class expression.
  95808. */
  95809. function generateNameForClassExpression() {
  95810. return makeUniqueName("class");
  95811. }
  95812. function generateNameForMethodOrAccessor(node) {
  95813. if (ts.isIdentifier(node.name)) {
  95814. return generateNameCached(node.name);
  95815. }
  95816. return makeTempVariableName(0 /* Auto */);
  95817. }
  95818. /**
  95819. * Generates a unique name from a node.
  95820. */
  95821. function generateNameForNode(node, flags) {
  95822. switch (node.kind) {
  95823. case 75 /* Identifier */:
  95824. return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
  95825. case 249 /* ModuleDeclaration */:
  95826. case 248 /* EnumDeclaration */:
  95827. return generateNameForModuleOrEnum(node);
  95828. case 254 /* ImportDeclaration */:
  95829. case 260 /* ExportDeclaration */:
  95830. return generateNameForImportOrExportDeclaration(node);
  95831. case 244 /* FunctionDeclaration */:
  95832. case 245 /* ClassDeclaration */:
  95833. case 259 /* ExportAssignment */:
  95834. return generateNameForExportDefault();
  95835. case 214 /* ClassExpression */:
  95836. return generateNameForClassExpression();
  95837. case 161 /* MethodDeclaration */:
  95838. case 163 /* GetAccessor */:
  95839. case 164 /* SetAccessor */:
  95840. return generateNameForMethodOrAccessor(node);
  95841. case 154 /* ComputedPropertyName */:
  95842. return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
  95843. default:
  95844. return makeTempVariableName(0 /* Auto */);
  95845. }
  95846. }
  95847. /**
  95848. * Generates a unique identifier for a node.
  95849. */
  95850. function makeName(name) {
  95851. switch (name.autoGenerateFlags & 7 /* KindMask */) {
  95852. case 1 /* Auto */:
  95853. return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
  95854. case 2 /* Loop */:
  95855. return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
  95856. case 3 /* Unique */:
  95857. return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
  95858. }
  95859. return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
  95860. }
  95861. /**
  95862. * Gets the node from which a name should be generated.
  95863. */
  95864. function getNodeForGeneratedName(name) {
  95865. var autoGenerateId = name.autoGenerateId;
  95866. var node = name;
  95867. var original = node.original;
  95868. while (original) {
  95869. node = original;
  95870. // if "node" is a different generated name (having a different
  95871. // "autoGenerateId"), use it and stop traversing.
  95872. if (ts.isIdentifier(node)
  95873. && !!(node.autoGenerateFlags & 4 /* Node */)
  95874. && node.autoGenerateId !== autoGenerateId) {
  95875. break;
  95876. }
  95877. original = node.original;
  95878. }
  95879. // otherwise, return the original node for the source;
  95880. return node;
  95881. }
  95882. // Comments
  95883. function pipelineEmitWithComments(hint, node) {
  95884. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  95885. enterComment();
  95886. hasWrittenComment = false;
  95887. var emitFlags = ts.getEmitFlags(node);
  95888. var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
  95889. var isEmittedNode = node.kind !== 324 /* NotEmittedStatement */;
  95890. // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
  95891. // It is expensive to walk entire tree just to set one kind of node to have no comments.
  95892. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
  95893. var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
  95894. // Save current container state on the stack.
  95895. var savedContainerPos = containerPos;
  95896. var savedContainerEnd = containerEnd;
  95897. var savedDeclarationListContainerEnd = declarationListContainerEnd;
  95898. if ((pos > 0 || end > 0) && pos !== end) {
  95899. // Emit leading comments if the position is not synthesized and the node
  95900. // has not opted out from emitting leading comments.
  95901. if (!skipLeadingComments) {
  95902. emitLeadingComments(pos, isEmittedNode);
  95903. }
  95904. if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
  95905. // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
  95906. containerPos = pos;
  95907. }
  95908. if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
  95909. // As above.
  95910. containerEnd = end;
  95911. // To avoid invalid comment emit in a down-level binding pattern, we
  95912. // keep track of the last declaration list container's end
  95913. if (node.kind === 243 /* VariableDeclarationList */) {
  95914. declarationListContainerEnd = end;
  95915. }
  95916. }
  95917. }
  95918. ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
  95919. exitComment();
  95920. var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
  95921. if (emitFlags & 2048 /* NoNestedComments */) {
  95922. commentsDisabled = true;
  95923. pipelinePhase(hint, node);
  95924. commentsDisabled = false;
  95925. }
  95926. else {
  95927. pipelinePhase(hint, node);
  95928. }
  95929. enterComment();
  95930. ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
  95931. if ((pos > 0 || end > 0) && pos !== end) {
  95932. // Restore previous container state.
  95933. containerPos = savedContainerPos;
  95934. containerEnd = savedContainerEnd;
  95935. declarationListContainerEnd = savedDeclarationListContainerEnd;
  95936. // Emit trailing comments if the position is not synthesized and the node
  95937. // has not opted out from emitting leading comments and is an emitted node.
  95938. if (!skipTrailingComments && isEmittedNode) {
  95939. emitTrailingComments(end);
  95940. }
  95941. }
  95942. exitComment();
  95943. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  95944. }
  95945. function emitLeadingSynthesizedComment(comment) {
  95946. if (comment.kind === 2 /* SingleLineCommentTrivia */) {
  95947. writer.writeLine();
  95948. }
  95949. writeSynthesizedComment(comment);
  95950. if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
  95951. writer.writeLine();
  95952. }
  95953. else {
  95954. writer.writeSpace(" ");
  95955. }
  95956. }
  95957. function emitTrailingSynthesizedComment(comment) {
  95958. if (!writer.isAtStartOfLine()) {
  95959. writer.writeSpace(" ");
  95960. }
  95961. writeSynthesizedComment(comment);
  95962. if (comment.hasTrailingNewLine) {
  95963. writer.writeLine();
  95964. }
  95965. }
  95966. function writeSynthesizedComment(comment) {
  95967. var text = formatSynthesizedComment(comment);
  95968. var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
  95969. ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
  95970. }
  95971. function formatSynthesizedComment(comment) {
  95972. return comment.kind === 3 /* MultiLineCommentTrivia */
  95973. ? "/*" + comment.text + "*/"
  95974. : "//" + comment.text;
  95975. }
  95976. function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
  95977. enterComment();
  95978. var pos = detachedRange.pos, end = detachedRange.end;
  95979. var emitFlags = ts.getEmitFlags(node);
  95980. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
  95981. var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
  95982. if (!skipLeadingComments) {
  95983. emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
  95984. }
  95985. exitComment();
  95986. if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
  95987. commentsDisabled = true;
  95988. emitCallback(node);
  95989. commentsDisabled = false;
  95990. }
  95991. else {
  95992. emitCallback(node);
  95993. }
  95994. enterComment();
  95995. if (!skipTrailingComments) {
  95996. emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
  95997. if (hasWrittenComment && !writer.isAtStartOfLine()) {
  95998. writer.writeLine();
  95999. }
  96000. }
  96001. exitComment();
  96002. }
  96003. function emitLeadingComments(pos, isEmittedNode) {
  96004. hasWrittenComment = false;
  96005. if (isEmittedNode) {
  96006. forEachLeadingCommentToEmit(pos, emitLeadingComment);
  96007. }
  96008. else if (pos === 0) {
  96009. // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
  96010. // unless it is a triple slash comment at the top of the file.
  96011. // For Example:
  96012. // /// <reference-path ...>
  96013. // declare var x;
  96014. // /// <reference-path ...>
  96015. // interface F {}
  96016. // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
  96017. forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
  96018. }
  96019. }
  96020. function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
  96021. if (isTripleSlashComment(commentPos, commentEnd)) {
  96022. emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
  96023. }
  96024. }
  96025. function shouldWriteComment(text, pos) {
  96026. if (printerOptions.onlyPrintJsDocStyle) {
  96027. return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
  96028. }
  96029. return true;
  96030. }
  96031. function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
  96032. if (!shouldWriteComment(currentSourceFile.text, commentPos))
  96033. return;
  96034. if (!hasWrittenComment) {
  96035. ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
  96036. hasWrittenComment = true;
  96037. }
  96038. // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
  96039. emitPos(commentPos);
  96040. ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
  96041. emitPos(commentEnd);
  96042. if (hasTrailingNewLine) {
  96043. writer.writeLine();
  96044. }
  96045. else if (kind === 3 /* MultiLineCommentTrivia */) {
  96046. writer.writeSpace(" ");
  96047. }
  96048. }
  96049. function emitLeadingCommentsOfPosition(pos) {
  96050. if (commentsDisabled || pos === -1) {
  96051. return;
  96052. }
  96053. emitLeadingComments(pos, /*isEmittedNode*/ true);
  96054. }
  96055. function emitTrailingComments(pos) {
  96056. forEachTrailingCommentToEmit(pos, emitTrailingComment);
  96057. }
  96058. function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
  96059. if (!shouldWriteComment(currentSourceFile.text, commentPos))
  96060. return;
  96061. // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
  96062. if (!writer.isAtStartOfLine()) {
  96063. writer.writeSpace(" ");
  96064. }
  96065. emitPos(commentPos);
  96066. ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
  96067. emitPos(commentEnd);
  96068. if (hasTrailingNewLine) {
  96069. writer.writeLine();
  96070. }
  96071. }
  96072. function emitTrailingCommentsOfPosition(pos, prefixSpace) {
  96073. if (commentsDisabled) {
  96074. return;
  96075. }
  96076. enterComment();
  96077. forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
  96078. exitComment();
  96079. }
  96080. function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
  96081. // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
  96082. emitPos(commentPos);
  96083. ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
  96084. emitPos(commentEnd);
  96085. if (hasTrailingNewLine) {
  96086. writer.writeLine();
  96087. }
  96088. else {
  96089. writer.writeSpace(" ");
  96090. }
  96091. }
  96092. function forEachLeadingCommentToEmit(pos, cb) {
  96093. // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
  96094. if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
  96095. if (hasDetachedComments(pos)) {
  96096. forEachLeadingCommentWithoutDetachedComments(cb);
  96097. }
  96098. else {
  96099. ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
  96100. }
  96101. }
  96102. }
  96103. function forEachTrailingCommentToEmit(end, cb) {
  96104. // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
  96105. if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
  96106. ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
  96107. }
  96108. }
  96109. function hasDetachedComments(pos) {
  96110. return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
  96111. }
  96112. function forEachLeadingCommentWithoutDetachedComments(cb) {
  96113. // get the leading comments from detachedPos
  96114. var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
  96115. if (detachedCommentsInfo.length - 1) {
  96116. detachedCommentsInfo.pop();
  96117. }
  96118. else {
  96119. detachedCommentsInfo = undefined;
  96120. }
  96121. ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
  96122. }
  96123. function emitDetachedCommentsAndUpdateCommentsInfo(range) {
  96124. var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
  96125. if (currentDetachedCommentInfo) {
  96126. if (detachedCommentsInfo) {
  96127. detachedCommentsInfo.push(currentDetachedCommentInfo);
  96128. }
  96129. else {
  96130. detachedCommentsInfo = [currentDetachedCommentInfo];
  96131. }
  96132. }
  96133. }
  96134. function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
  96135. if (!shouldWriteComment(currentSourceFile.text, commentPos))
  96136. return;
  96137. emitPos(commentPos);
  96138. ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
  96139. emitPos(commentEnd);
  96140. }
  96141. /**
  96142. * Determine if the given comment is a triple-slash
  96143. *
  96144. * @return true if the comment is a triple-slash comment else false
  96145. */
  96146. function isTripleSlashComment(commentPos, commentEnd) {
  96147. return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
  96148. }
  96149. // Source Maps
  96150. function getParsedSourceMap(node) {
  96151. if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
  96152. node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
  96153. }
  96154. return node.parsedSourceMap || undefined;
  96155. }
  96156. function pipelineEmitWithSourceMap(hint, node) {
  96157. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  96158. var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
  96159. if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
  96160. pipelinePhase(hint, node);
  96161. }
  96162. else if (ts.isUnparsedNode(node)) {
  96163. var parsed = getParsedSourceMap(node.parent);
  96164. if (parsed && sourceMapGenerator) {
  96165. sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
  96166. }
  96167. pipelinePhase(hint, node);
  96168. }
  96169. else {
  96170. var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
  96171. var emitFlags = ts.getEmitFlags(node);
  96172. if (node.kind !== 324 /* NotEmittedStatement */
  96173. && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
  96174. && pos >= 0) {
  96175. emitSourcePos(source, skipSourceTrivia(source, pos));
  96176. }
  96177. if (emitFlags & 64 /* NoNestedSourceMaps */) {
  96178. sourceMapsDisabled = true;
  96179. pipelinePhase(hint, node);
  96180. sourceMapsDisabled = false;
  96181. }
  96182. else {
  96183. pipelinePhase(hint, node);
  96184. }
  96185. if (node.kind !== 324 /* NotEmittedStatement */
  96186. && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
  96187. && end >= 0) {
  96188. emitSourcePos(source, end);
  96189. }
  96190. }
  96191. ts.Debug.assert(lastNode === node || lastSubstitution === node);
  96192. }
  96193. /**
  96194. * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
  96195. */
  96196. function skipSourceTrivia(source, pos) {
  96197. return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
  96198. }
  96199. /**
  96200. * Emits a mapping.
  96201. *
  96202. * If the position is synthetic (undefined or a negative value), no mapping will be
  96203. * created.
  96204. *
  96205. * @param pos The position.
  96206. */
  96207. function emitPos(pos) {
  96208. if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
  96209. return;
  96210. }
  96211. var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
  96212. sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter,
  96213. /*nameIndex*/ undefined);
  96214. }
  96215. function emitSourcePos(source, pos) {
  96216. if (source !== sourceMapSource) {
  96217. var savedSourceMapSource = sourceMapSource;
  96218. setSourceMapSource(source);
  96219. emitPos(pos);
  96220. setSourceMapSource(savedSourceMapSource);
  96221. }
  96222. else {
  96223. emitPos(pos);
  96224. }
  96225. }
  96226. /**
  96227. * Emits a token of a node with possible leading and trailing source maps.
  96228. *
  96229. * @param node The node containing the token.
  96230. * @param token The token to emit.
  96231. * @param tokenStartPos The start pos of the token.
  96232. * @param emitCallback The callback used to emit the token.
  96233. */
  96234. function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
  96235. if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
  96236. return emitCallback(token, writer, tokenPos);
  96237. }
  96238. var emitNode = node && node.emitNode;
  96239. var emitFlags = emitNode && emitNode.flags || 0 /* None */;
  96240. var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
  96241. var source = range && range.source || sourceMapSource;
  96242. tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
  96243. if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
  96244. emitSourcePos(source, tokenPos);
  96245. }
  96246. tokenPos = emitCallback(token, writer, tokenPos);
  96247. if (range)
  96248. tokenPos = range.end;
  96249. if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
  96250. emitSourcePos(source, tokenPos);
  96251. }
  96252. return tokenPos;
  96253. }
  96254. function setSourceMapSource(source) {
  96255. if (sourceMapsDisabled) {
  96256. return;
  96257. }
  96258. sourceMapSource = source;
  96259. if (isJsonSourceMapSource(source)) {
  96260. return;
  96261. }
  96262. sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
  96263. if (printerOptions.inlineSources) {
  96264. sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
  96265. }
  96266. }
  96267. function isJsonSourceMapSource(sourceFile) {
  96268. return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
  96269. }
  96270. }
  96271. ts.createPrinter = createPrinter;
  96272. function createBracketsMap() {
  96273. var brackets = [];
  96274. brackets[1024 /* Braces */] = ["{", "}"];
  96275. brackets[2048 /* Parenthesis */] = ["(", ")"];
  96276. brackets[4096 /* AngleBrackets */] = ["<", ">"];
  96277. brackets[8192 /* SquareBrackets */] = ["[", "]"];
  96278. return brackets;
  96279. }
  96280. function getOpeningBracket(format) {
  96281. return brackets[format & 15360 /* BracketsMask */][0];
  96282. }
  96283. function getClosingBracket(format) {
  96284. return brackets[format & 15360 /* BracketsMask */][1];
  96285. }
  96286. // Flags enum to track count of temp variables and a few dedicated names
  96287. var TempFlags;
  96288. (function (TempFlags) {
  96289. TempFlags[TempFlags["Auto"] = 0] = "Auto";
  96290. TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
  96291. TempFlags[TempFlags["_i"] = 268435456] = "_i";
  96292. })(TempFlags || (TempFlags = {}));
  96293. })(ts || (ts = {}));
  96294. /* @internal */
  96295. var ts;
  96296. (function (ts) {
  96297. function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
  96298. if (!host.getDirectories || !host.readDirectory) {
  96299. return undefined;
  96300. }
  96301. var cachedReadDirectoryResult = ts.createMap();
  96302. var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  96303. return {
  96304. useCaseSensitiveFileNames: useCaseSensitiveFileNames,
  96305. fileExists: fileExists,
  96306. readFile: function (path, encoding) { return host.readFile(path, encoding); },
  96307. directoryExists: host.directoryExists && directoryExists,
  96308. getDirectories: getDirectories,
  96309. readDirectory: readDirectory,
  96310. createDirectory: host.createDirectory && createDirectory,
  96311. writeFile: host.writeFile && writeFile,
  96312. addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
  96313. addOrDeleteFile: addOrDeleteFile,
  96314. clearCache: clearCache,
  96315. realpath: host.realpath && realpath
  96316. };
  96317. function toPath(fileName) {
  96318. return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  96319. }
  96320. function getCachedFileSystemEntries(rootDirPath) {
  96321. return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
  96322. }
  96323. function getCachedFileSystemEntriesForBaseDir(path) {
  96324. return getCachedFileSystemEntries(ts.getDirectoryPath(path));
  96325. }
  96326. function getBaseNameOfFileName(fileName) {
  96327. return ts.getBaseFileName(ts.normalizePath(fileName));
  96328. }
  96329. function createCachedFileSystemEntries(rootDir, rootDirPath) {
  96330. var resultFromHost = {
  96331. files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
  96332. directories: host.getDirectories(rootDir) || []
  96333. };
  96334. cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
  96335. return resultFromHost;
  96336. }
  96337. /**
  96338. * If the readDirectory result was already cached, it returns that
  96339. * Otherwise gets result from host and caches it.
  96340. * The host request is done under try catch block to avoid caching incorrect result
  96341. */
  96342. function tryReadDirectory(rootDir, rootDirPath) {
  96343. rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
  96344. var cachedResult = getCachedFileSystemEntries(rootDirPath);
  96345. if (cachedResult) {
  96346. return cachedResult;
  96347. }
  96348. try {
  96349. return createCachedFileSystemEntries(rootDir, rootDirPath);
  96350. }
  96351. catch (_e) {
  96352. // If there is exception to read directories, dont cache the result and direct the calls to host
  96353. ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
  96354. return undefined;
  96355. }
  96356. }
  96357. function fileNameEqual(name1, name2) {
  96358. return getCanonicalFileName(name1) === getCanonicalFileName(name2);
  96359. }
  96360. function hasEntry(entries, name) {
  96361. return ts.some(entries, function (file) { return fileNameEqual(file, name); });
  96362. }
  96363. function updateFileSystemEntry(entries, baseName, isValid) {
  96364. if (hasEntry(entries, baseName)) {
  96365. if (!isValid) {
  96366. return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
  96367. }
  96368. }
  96369. else if (isValid) {
  96370. return entries.push(baseName);
  96371. }
  96372. }
  96373. function writeFile(fileName, data, writeByteOrderMark) {
  96374. var path = toPath(fileName);
  96375. var result = getCachedFileSystemEntriesForBaseDir(path);
  96376. if (result) {
  96377. updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
  96378. }
  96379. return host.writeFile(fileName, data, writeByteOrderMark);
  96380. }
  96381. function fileExists(fileName) {
  96382. var path = toPath(fileName);
  96383. var result = getCachedFileSystemEntriesForBaseDir(path);
  96384. return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
  96385. host.fileExists(fileName);
  96386. }
  96387. function directoryExists(dirPath) {
  96388. var path = toPath(dirPath);
  96389. return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
  96390. }
  96391. function createDirectory(dirPath) {
  96392. var path = toPath(dirPath);
  96393. var result = getCachedFileSystemEntriesForBaseDir(path);
  96394. var baseFileName = getBaseNameOfFileName(dirPath);
  96395. if (result) {
  96396. updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
  96397. }
  96398. host.createDirectory(dirPath);
  96399. }
  96400. function getDirectories(rootDir) {
  96401. var rootDirPath = toPath(rootDir);
  96402. var result = tryReadDirectory(rootDir, rootDirPath);
  96403. if (result) {
  96404. return result.directories.slice();
  96405. }
  96406. return host.getDirectories(rootDir);
  96407. }
  96408. function readDirectory(rootDir, extensions, excludes, includes, depth) {
  96409. var rootDirPath = toPath(rootDir);
  96410. var result = tryReadDirectory(rootDir, rootDirPath);
  96411. if (result) {
  96412. return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
  96413. }
  96414. return host.readDirectory(rootDir, extensions, excludes, includes, depth);
  96415. function getFileSystemEntries(dir) {
  96416. var path = toPath(dir);
  96417. if (path === rootDirPath) {
  96418. return result;
  96419. }
  96420. return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
  96421. }
  96422. }
  96423. function realpath(s) {
  96424. return host.realpath ? host.realpath(s) : s;
  96425. }
  96426. function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
  96427. var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
  96428. if (existingResult) {
  96429. // Just clear the cache for now
  96430. // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
  96431. clearCache();
  96432. return undefined;
  96433. }
  96434. var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
  96435. if (!parentResult) {
  96436. return undefined;
  96437. }
  96438. // This was earlier a file (hence not in cached directory contents)
  96439. // or we never cached the directory containing it
  96440. if (!host.directoryExists) {
  96441. // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
  96442. clearCache();
  96443. return undefined;
  96444. }
  96445. var baseName = getBaseNameOfFileName(fileOrDirectory);
  96446. var fsQueryResult = {
  96447. fileExists: host.fileExists(fileOrDirectoryPath),
  96448. directoryExists: host.directoryExists(fileOrDirectoryPath)
  96449. };
  96450. if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
  96451. // Folder added or removed, clear the cache instead of updating the folder and its structure
  96452. clearCache();
  96453. }
  96454. else {
  96455. // No need to update the directory structure, just files
  96456. updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
  96457. }
  96458. return fsQueryResult;
  96459. }
  96460. function addOrDeleteFile(fileName, filePath, eventKind) {
  96461. if (eventKind === ts.FileWatcherEventKind.Changed) {
  96462. return;
  96463. }
  96464. var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
  96465. if (parentResult) {
  96466. updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
  96467. }
  96468. }
  96469. function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
  96470. updateFileSystemEntry(parentResult.files, baseName, fileExists);
  96471. }
  96472. function clearCache() {
  96473. cachedReadDirectoryResult.clear();
  96474. }
  96475. }
  96476. ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
  96477. var ConfigFileProgramReloadLevel;
  96478. (function (ConfigFileProgramReloadLevel) {
  96479. ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
  96480. /** Update the file name list from the disk */
  96481. ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
  96482. /** Reload completely by re-reading contents of config file from disk and updating program */
  96483. ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
  96484. })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
  96485. /**
  96486. * Updates the existing missing file watches with the new set of missing files after new program is created
  96487. */
  96488. function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
  96489. var missingFilePaths = program.getMissingFilePaths();
  96490. var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
  96491. // Update the missing file paths watcher
  96492. ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
  96493. // Watch the missing files
  96494. createNewValue: createMissingFileWatch,
  96495. // Files that are no longer missing (e.g. because they are no longer required)
  96496. // should no longer be watched.
  96497. onDeleteValue: ts.closeFileWatcher
  96498. });
  96499. }
  96500. ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
  96501. /**
  96502. * Updates the existing wild card directory watches with the new set of wild card directories from the config file
  96503. * after new program is created because the config file was reloaded or program was created first time from the config file
  96504. * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
  96505. * as wildcard directories wont change unless reloading config file
  96506. */
  96507. function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
  96508. ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
  96509. // Create new watch and recursive info
  96510. createNewValue: createWildcardDirectoryWatcher,
  96511. // Close existing watch thats not needed any more
  96512. onDeleteValue: closeFileWatcherOf,
  96513. // Close existing watch that doesnt match in the flags
  96514. onExistingValue: updateWildcardDirectoryWatcher
  96515. });
  96516. function createWildcardDirectoryWatcher(directory, flags) {
  96517. // Create new watch and recursive info
  96518. return {
  96519. watcher: watchDirectory(directory, flags),
  96520. flags: flags
  96521. };
  96522. }
  96523. function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
  96524. // Watcher needs to be updated if the recursive flags dont match
  96525. if (existingWatcher.flags === flags) {
  96526. return;
  96527. }
  96528. existingWatcher.watcher.close();
  96529. existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
  96530. }
  96531. }
  96532. ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
  96533. function isEmittedFileOfProgram(program, file) {
  96534. if (!program) {
  96535. return false;
  96536. }
  96537. return program.isEmittedFile(file);
  96538. }
  96539. ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
  96540. var WatchLogLevel;
  96541. (function (WatchLogLevel) {
  96542. WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
  96543. WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
  96544. WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
  96545. })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
  96546. function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
  96547. return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
  96548. }
  96549. ts.getWatchFactory = getWatchFactory;
  96550. function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
  96551. var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
  96552. var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
  96553. var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
  96554. if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
  96555. ts.setSysLog(function (s) { return log(s); });
  96556. }
  96557. return {
  96558. watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
  96559. return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
  96560. },
  96561. watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
  96562. return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
  96563. },
  96564. watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
  96565. return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
  96566. }
  96567. };
  96568. }
  96569. function watchFile(host, file, callback, pollingInterval, options) {
  96570. return host.watchFile(file, callback, pollingInterval, options);
  96571. }
  96572. function watchFilePath(host, file, callback, pollingInterval, options, path) {
  96573. return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
  96574. }
  96575. function watchDirectory(host, directory, callback, flags, options) {
  96576. return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
  96577. }
  96578. function getCreateFileWatcher(watchLogLevel, addWatch) {
  96579. switch (watchLogLevel) {
  96580. case WatchLogLevel.None:
  96581. return addWatch;
  96582. case WatchLogLevel.TriggerOnly:
  96583. return createFileWatcherWithTriggerLogging;
  96584. case WatchLogLevel.Verbose:
  96585. return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
  96586. }
  96587. }
  96588. function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
  96589. log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
  96590. var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
  96591. return {
  96592. close: function () {
  96593. log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
  96594. watcher.close();
  96595. }
  96596. };
  96597. }
  96598. function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
  96599. var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
  96600. log(watchInfo);
  96601. var start = ts.timestamp();
  96602. var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
  96603. var elapsed = ts.timestamp() - start;
  96604. log("Elapsed:: " + elapsed + "ms " + watchInfo);
  96605. return {
  96606. close: function () {
  96607. var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
  96608. log(watchInfo);
  96609. var start = ts.timestamp();
  96610. watcher.close();
  96611. var elapsed = ts.timestamp() - start;
  96612. log("Elapsed:: " + elapsed + "ms " + watchInfo);
  96613. }
  96614. };
  96615. }
  96616. function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
  96617. return addWatch(host, file, function (fileName, cbOptional) {
  96618. var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
  96619. log(triggerredInfo);
  96620. var start = ts.timestamp();
  96621. cb(fileName, cbOptional, passThrough);
  96622. var elapsed = ts.timestamp() - start;
  96623. log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
  96624. }, flags, options);
  96625. }
  96626. function getFallbackOptions(options) {
  96627. var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
  96628. return {
  96629. watchFile: fallbackPolling !== undefined ?
  96630. fallbackPolling :
  96631. ts.WatchFileKind.PriorityPollingInterval
  96632. };
  96633. }
  96634. ts.getFallbackOptions = getFallbackOptions;
  96635. function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
  96636. return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
  96637. }
  96638. function closeFileWatcherOf(objWithWatcher) {
  96639. objWithWatcher.watcher.close();
  96640. }
  96641. ts.closeFileWatcherOf = closeFileWatcherOf;
  96642. })(ts || (ts = {}));
  96643. var ts;
  96644. (function (ts) {
  96645. var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
  96646. function findConfigFile(searchPath, fileExists, configName) {
  96647. if (configName === void 0) { configName = "tsconfig.json"; }
  96648. return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
  96649. var fileName = ts.combinePaths(ancestor, configName);
  96650. return fileExists(fileName) ? fileName : undefined;
  96651. });
  96652. }
  96653. ts.findConfigFile = findConfigFile;
  96654. function resolveTripleslashReference(moduleName, containingFile) {
  96655. var basePath = ts.getDirectoryPath(containingFile);
  96656. var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
  96657. return ts.normalizePath(referencedFileName);
  96658. }
  96659. ts.resolveTripleslashReference = resolveTripleslashReference;
  96660. /* @internal */
  96661. function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
  96662. var commonPathComponents;
  96663. var failed = ts.forEach(fileNames, function (sourceFile) {
  96664. // Each file contributes into common source file path
  96665. var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
  96666. sourcePathComponents.pop(); // The base file name is not part of the common directory path
  96667. if (!commonPathComponents) {
  96668. // first file
  96669. commonPathComponents = sourcePathComponents;
  96670. return;
  96671. }
  96672. var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
  96673. for (var i = 0; i < n; i++) {
  96674. if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
  96675. if (i === 0) {
  96676. // Failed to find any common path component
  96677. return true;
  96678. }
  96679. // New common path found that is 0 -> i-1
  96680. commonPathComponents.length = i;
  96681. break;
  96682. }
  96683. }
  96684. // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
  96685. if (sourcePathComponents.length < commonPathComponents.length) {
  96686. commonPathComponents.length = sourcePathComponents.length;
  96687. }
  96688. });
  96689. // A common path can not be found when paths span multiple drives on windows, for example
  96690. if (failed) {
  96691. return "";
  96692. }
  96693. if (!commonPathComponents) { // Can happen when all input files are .d.ts files
  96694. return currentDirectory;
  96695. }
  96696. return ts.getPathFromPathComponents(commonPathComponents);
  96697. }
  96698. ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
  96699. function createCompilerHost(options, setParentNodes) {
  96700. return createCompilerHostWorker(options, setParentNodes);
  96701. }
  96702. ts.createCompilerHost = createCompilerHost;
  96703. /*@internal*/
  96704. // TODO(shkamat): update this after reworking ts build API
  96705. function createCompilerHostWorker(options, setParentNodes, system) {
  96706. if (system === void 0) { system = ts.sys; }
  96707. var existingDirectories = ts.createMap();
  96708. var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
  96709. function getSourceFile(fileName, languageVersion, onError) {
  96710. var text;
  96711. try {
  96712. ts.performance.mark("beforeIORead");
  96713. text = compilerHost.readFile(fileName);
  96714. ts.performance.mark("afterIORead");
  96715. ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
  96716. }
  96717. catch (e) {
  96718. if (onError) {
  96719. onError(e.message);
  96720. }
  96721. text = "";
  96722. }
  96723. return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
  96724. }
  96725. function directoryExists(directoryPath) {
  96726. if (existingDirectories.has(directoryPath)) {
  96727. return true;
  96728. }
  96729. if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
  96730. existingDirectories.set(directoryPath, true);
  96731. return true;
  96732. }
  96733. return false;
  96734. }
  96735. function writeFile(fileName, data, writeByteOrderMark, onError) {
  96736. try {
  96737. ts.performance.mark("beforeIOWrite");
  96738. // NOTE: If patchWriteFileEnsuringDirectory has been called,
  96739. // the system.writeFile will do its own directory creation and
  96740. // the ensureDirectoriesExist call will always be redundant.
  96741. ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); });
  96742. ts.performance.mark("afterIOWrite");
  96743. ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
  96744. }
  96745. catch (e) {
  96746. if (onError) {
  96747. onError(e.message);
  96748. }
  96749. }
  96750. }
  96751. var outputFingerprints;
  96752. function writeFileWorker(fileName, data, writeByteOrderMark) {
  96753. if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
  96754. system.writeFile(fileName, data, writeByteOrderMark);
  96755. return;
  96756. }
  96757. if (!outputFingerprints) {
  96758. outputFingerprints = ts.createMap();
  96759. }
  96760. var hash = system.createHash(data);
  96761. var mtimeBefore = system.getModifiedTime(fileName);
  96762. if (mtimeBefore) {
  96763. var fingerprint = outputFingerprints.get(fileName);
  96764. // If output has not been changed, and the file has no external modification
  96765. if (fingerprint &&
  96766. fingerprint.byteOrderMark === writeByteOrderMark &&
  96767. fingerprint.hash === hash &&
  96768. fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
  96769. return;
  96770. }
  96771. }
  96772. system.writeFile(fileName, data, writeByteOrderMark);
  96773. var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
  96774. outputFingerprints.set(fileName, {
  96775. hash: hash,
  96776. byteOrderMark: writeByteOrderMark,
  96777. mtime: mtimeAfter
  96778. });
  96779. }
  96780. function getDefaultLibLocation() {
  96781. return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
  96782. }
  96783. var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
  96784. var realpath = system.realpath && (function (path) { return system.realpath(path); });
  96785. var compilerHost = {
  96786. getSourceFile: getSourceFile,
  96787. getDefaultLibLocation: getDefaultLibLocation,
  96788. getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
  96789. writeFile: writeFile,
  96790. getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
  96791. useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
  96792. getCanonicalFileName: getCanonicalFileName,
  96793. getNewLine: function () { return newLine; },
  96794. fileExists: function (fileName) { return system.fileExists(fileName); },
  96795. readFile: function (fileName) { return system.readFile(fileName); },
  96796. trace: function (s) { return system.write(s + newLine); },
  96797. directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
  96798. getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
  96799. getDirectories: function (path) { return system.getDirectories(path); },
  96800. realpath: realpath,
  96801. readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
  96802. createDirectory: function (d) { return system.createDirectory(d); },
  96803. createHash: ts.maybeBind(system, system.createHash)
  96804. };
  96805. return compilerHost;
  96806. }
  96807. ts.createCompilerHostWorker = createCompilerHostWorker;
  96808. /*@internal*/
  96809. function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
  96810. var originalReadFile = host.readFile;
  96811. var originalFileExists = host.fileExists;
  96812. var originalDirectoryExists = host.directoryExists;
  96813. var originalCreateDirectory = host.createDirectory;
  96814. var originalWriteFile = host.writeFile;
  96815. var readFileCache = ts.createMap();
  96816. var fileExistsCache = ts.createMap();
  96817. var directoryExistsCache = ts.createMap();
  96818. var sourceFileCache = ts.createMap();
  96819. var readFileWithCache = function (fileName) {
  96820. var key = toPath(fileName);
  96821. var value = readFileCache.get(key);
  96822. if (value !== undefined)
  96823. return value !== false ? value : undefined;
  96824. return setReadFileCache(key, fileName);
  96825. };
  96826. var setReadFileCache = function (key, fileName) {
  96827. var newValue = originalReadFile.call(host, fileName);
  96828. readFileCache.set(key, newValue !== undefined ? newValue : false);
  96829. return newValue;
  96830. };
  96831. host.readFile = function (fileName) {
  96832. var key = toPath(fileName);
  96833. var value = readFileCache.get(key);
  96834. if (value !== undefined)
  96835. return value !== false ? value : undefined; // could be .d.ts from output
  96836. // Cache json or buildInfo
  96837. if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
  96838. return originalReadFile.call(host, fileName);
  96839. }
  96840. return setReadFileCache(key, fileName);
  96841. };
  96842. var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
  96843. var key = toPath(fileName);
  96844. var value = sourceFileCache.get(key);
  96845. if (value)
  96846. return value;
  96847. var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
  96848. if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
  96849. sourceFileCache.set(key, sourceFile);
  96850. }
  96851. return sourceFile;
  96852. } : undefined;
  96853. // fileExists for any kind of extension
  96854. host.fileExists = function (fileName) {
  96855. var key = toPath(fileName);
  96856. var value = fileExistsCache.get(key);
  96857. if (value !== undefined)
  96858. return value;
  96859. var newValue = originalFileExists.call(host, fileName);
  96860. fileExistsCache.set(key, !!newValue);
  96861. return newValue;
  96862. };
  96863. if (originalWriteFile) {
  96864. host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
  96865. var key = toPath(fileName);
  96866. fileExistsCache.delete(key);
  96867. var value = readFileCache.get(key);
  96868. if (value !== undefined && value !== data) {
  96869. readFileCache.delete(key);
  96870. sourceFileCache.delete(key);
  96871. }
  96872. else if (getSourceFileWithCache) {
  96873. var sourceFile = sourceFileCache.get(key);
  96874. if (sourceFile && sourceFile.text !== data) {
  96875. sourceFileCache.delete(key);
  96876. }
  96877. }
  96878. originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
  96879. };
  96880. }
  96881. // directoryExists
  96882. if (originalDirectoryExists && originalCreateDirectory) {
  96883. host.directoryExists = function (directory) {
  96884. var key = toPath(directory);
  96885. var value = directoryExistsCache.get(key);
  96886. if (value !== undefined)
  96887. return value;
  96888. var newValue = originalDirectoryExists.call(host, directory);
  96889. directoryExistsCache.set(key, !!newValue);
  96890. return newValue;
  96891. };
  96892. host.createDirectory = function (directory) {
  96893. var key = toPath(directory);
  96894. directoryExistsCache.delete(key);
  96895. originalCreateDirectory.call(host, directory);
  96896. };
  96897. }
  96898. return {
  96899. originalReadFile: originalReadFile,
  96900. originalFileExists: originalFileExists,
  96901. originalDirectoryExists: originalDirectoryExists,
  96902. originalCreateDirectory: originalCreateDirectory,
  96903. originalWriteFile: originalWriteFile,
  96904. getSourceFileWithCache: getSourceFileWithCache,
  96905. readFileWithCache: readFileWithCache
  96906. };
  96907. }
  96908. ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
  96909. function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
  96910. var diagnostics;
  96911. diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
  96912. diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
  96913. diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
  96914. diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
  96915. diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
  96916. if (ts.getEmitDeclarations(program.getCompilerOptions())) {
  96917. diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
  96918. }
  96919. return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
  96920. }
  96921. ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
  96922. function formatDiagnostics(diagnostics, host) {
  96923. var output = "";
  96924. for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
  96925. var diagnostic = diagnostics_2[_i];
  96926. output += formatDiagnostic(diagnostic, host);
  96927. }
  96928. return output;
  96929. }
  96930. ts.formatDiagnostics = formatDiagnostics;
  96931. function formatDiagnostic(diagnostic, host) {
  96932. var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
  96933. if (diagnostic.file) {
  96934. var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
  96935. var fileName = diagnostic.file.fileName;
  96936. var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
  96937. return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
  96938. }
  96939. return errorMessage;
  96940. }
  96941. ts.formatDiagnostic = formatDiagnostic;
  96942. /** @internal */
  96943. var ForegroundColorEscapeSequences;
  96944. (function (ForegroundColorEscapeSequences) {
  96945. ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
  96946. ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
  96947. ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
  96948. ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
  96949. ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
  96950. })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
  96951. var gutterStyleSequence = "\u001b[7m";
  96952. var gutterSeparator = " ";
  96953. var resetEscapeSequence = "\u001b[0m";
  96954. var ellipsis = "...";
  96955. var halfIndent = " ";
  96956. var indent = " ";
  96957. function getCategoryFormat(category) {
  96958. switch (category) {
  96959. case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
  96960. case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
  96961. case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
  96962. case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
  96963. }
  96964. }
  96965. /** @internal */
  96966. function formatColorAndReset(text, formatStyle) {
  96967. return formatStyle + text + resetEscapeSequence;
  96968. }
  96969. ts.formatColorAndReset = formatColorAndReset;
  96970. function padLeft(s, length) {
  96971. while (s.length < length) {
  96972. s = " " + s;
  96973. }
  96974. return s;
  96975. }
  96976. function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
  96977. var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
  96978. var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
  96979. var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
  96980. var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
  96981. var gutterWidth = (lastLine + 1 + "").length;
  96982. if (hasMoreThanFiveLines) {
  96983. gutterWidth = Math.max(ellipsis.length, gutterWidth);
  96984. }
  96985. var context = "";
  96986. for (var i = firstLine; i <= lastLine; i++) {
  96987. context += host.getNewLine();
  96988. // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
  96989. // so we'll skip ahead to the second-to-last line.
  96990. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
  96991. context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
  96992. i = lastLine - 1;
  96993. }
  96994. var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
  96995. var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
  96996. var lineContent = file.text.slice(lineStart, lineEnd);
  96997. lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
  96998. lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
  96999. // Output the gutter and the actual contents of the line.
  97000. context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
  97001. context += lineContent + host.getNewLine();
  97002. // Output the gutter and the error span for the line using tildes.
  97003. context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
  97004. context += squiggleColor;
  97005. if (i === firstLine) {
  97006. // If we're on the last line, then limit it to the last character of the last line.
  97007. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
  97008. var lastCharForLine = i === lastLine ? lastLineChar : undefined;
  97009. context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
  97010. context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
  97011. }
  97012. else if (i === lastLine) {
  97013. context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
  97014. }
  97015. else {
  97016. // Squiggle the entire line.
  97017. context += lineContent.replace(/./g, "~");
  97018. }
  97019. context += resetEscapeSequence;
  97020. }
  97021. return context;
  97022. }
  97023. /* @internal */
  97024. function formatLocation(file, start, host, color) {
  97025. if (color === void 0) { color = formatColorAndReset; }
  97026. var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
  97027. var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
  97028. var output = "";
  97029. output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
  97030. output += ":";
  97031. output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
  97032. output += ":";
  97033. output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
  97034. return output;
  97035. }
  97036. ts.formatLocation = formatLocation;
  97037. function formatDiagnosticsWithColorAndContext(diagnostics, host) {
  97038. var output = "";
  97039. for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
  97040. var diagnostic = diagnostics_3[_i];
  97041. if (diagnostic.file) {
  97042. var file = diagnostic.file, start = diagnostic.start;
  97043. output += formatLocation(file, start, host); // TODO: GH#18217
  97044. output += " - ";
  97045. }
  97046. output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
  97047. output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
  97048. output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
  97049. if (diagnostic.file) {
  97050. output += host.getNewLine();
  97051. output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
  97052. if (diagnostic.relatedInformation) {
  97053. output += host.getNewLine();
  97054. for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
  97055. var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText;
  97056. if (file) {
  97057. output += host.getNewLine();
  97058. output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
  97059. output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
  97060. }
  97061. output += host.getNewLine();
  97062. output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
  97063. }
  97064. }
  97065. }
  97066. output += host.getNewLine();
  97067. }
  97068. return output;
  97069. }
  97070. ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
  97071. function flattenDiagnosticMessageText(diag, newLine, indent) {
  97072. if (indent === void 0) { indent = 0; }
  97073. if (ts.isString(diag)) {
  97074. return diag;
  97075. }
  97076. else if (diag === undefined) {
  97077. return "";
  97078. }
  97079. var result = "";
  97080. if (indent) {
  97081. result += newLine;
  97082. for (var i = 0; i < indent; i++) {
  97083. result += " ";
  97084. }
  97085. }
  97086. result += diag.messageText;
  97087. indent++;
  97088. if (diag.next) {
  97089. for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
  97090. var kid = _a[_i];
  97091. result += flattenDiagnosticMessageText(kid, newLine, indent);
  97092. }
  97093. }
  97094. return result;
  97095. }
  97096. ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
  97097. /* @internal */
  97098. function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
  97099. if (names.length === 0) {
  97100. return [];
  97101. }
  97102. var resolutions = [];
  97103. var cache = ts.createMap();
  97104. for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
  97105. var name = names_2[_i];
  97106. var result = void 0;
  97107. if (cache.has(name)) {
  97108. result = cache.get(name);
  97109. }
  97110. else {
  97111. cache.set(name, result = loader(name, containingFile, redirectedReference));
  97112. }
  97113. resolutions.push(result);
  97114. }
  97115. return resolutions;
  97116. }
  97117. ts.loadWithLocalCache = loadWithLocalCache;
  97118. /* @internal */
  97119. ts.inferredTypesContainingFile = "__inferred type names__.ts";
  97120. /**
  97121. * Determines if program structure is upto date or needs to be recreated
  97122. */
  97123. /* @internal */
  97124. function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
  97125. // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
  97126. if (!program || hasChangedAutomaticTypeDirectiveNames) {
  97127. return false;
  97128. }
  97129. // If root file names don't match
  97130. if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
  97131. return false;
  97132. }
  97133. var seenResolvedRefs;
  97134. // If project references don't match
  97135. if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
  97136. return false;
  97137. }
  97138. // If any file is not up-to-date, then the whole program is not up-to-date
  97139. if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
  97140. return false;
  97141. }
  97142. // If any of the missing file paths are now created
  97143. if (program.getMissingFilePaths().some(fileExists)) {
  97144. return false;
  97145. }
  97146. var currentOptions = program.getCompilerOptions();
  97147. // If the compilation settings do no match, then the program is not up-to-date
  97148. if (!ts.compareDataObjects(currentOptions, newOptions)) {
  97149. return false;
  97150. }
  97151. // If everything matches but the text of config file is changed,
  97152. // error locations can change for program options, so update the program
  97153. if (currentOptions.configFile && newOptions.configFile) {
  97154. return currentOptions.configFile.text === newOptions.configFile.text;
  97155. }
  97156. return true;
  97157. function sourceFileNotUptoDate(sourceFile) {
  97158. return !sourceFileVersionUptoDate(sourceFile) ||
  97159. hasInvalidatedResolution(sourceFile.path);
  97160. }
  97161. function sourceFileVersionUptoDate(sourceFile) {
  97162. return sourceFile.version === getSourceVersion(sourceFile.resolvedPath);
  97163. }
  97164. function projectReferenceUptoDate(oldRef, newRef, index) {
  97165. if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
  97166. return false;
  97167. }
  97168. return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
  97169. }
  97170. function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
  97171. if (oldResolvedRef) {
  97172. if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
  97173. // Assume true
  97174. return true;
  97175. }
  97176. // If sourceFile for the oldResolvedRef existed, check the version for uptodate
  97177. if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
  97178. return false;
  97179. }
  97180. // Add to seen before checking the referenced paths of this config file
  97181. (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
  97182. // If child project references are upto date, this project reference is uptodate
  97183. return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
  97184. return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
  97185. });
  97186. }
  97187. // In old program, not able to resolve project reference path,
  97188. // so if config file doesnt exist, it is uptodate.
  97189. return !fileExists(resolveProjectReferencePath(oldRef));
  97190. }
  97191. }
  97192. ts.isProgramUptoDate = isProgramUptoDate;
  97193. function getConfigFileParsingDiagnostics(configFileParseResult) {
  97194. return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
  97195. configFileParseResult.errors;
  97196. }
  97197. ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
  97198. /**
  97199. * Determine if source file needs to be re-created even if its text hasn't changed
  97200. */
  97201. function shouldProgramCreateNewSourceFiles(program, newOptions) {
  97202. if (!program)
  97203. return false;
  97204. // If any compiler options change, we can't reuse old source file even if version match
  97205. // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
  97206. var oldOptions = program.getCompilerOptions();
  97207. return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
  97208. return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
  97209. });
  97210. }
  97211. function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
  97212. return {
  97213. rootNames: rootNames,
  97214. options: options,
  97215. host: host,
  97216. oldProgram: oldProgram,
  97217. configFileParsingDiagnostics: configFileParsingDiagnostics
  97218. };
  97219. }
  97220. function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
  97221. var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
  97222. var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
  97223. var oldProgram = createProgramOptions.oldProgram;
  97224. var processingDefaultLibFiles;
  97225. var processingOtherFiles;
  97226. var files;
  97227. var symlinks;
  97228. var commonSourceDirectory;
  97229. var diagnosticsProducingTypeChecker;
  97230. var noDiagnosticsTypeChecker;
  97231. var classifiableNames;
  97232. var ambientModuleNameToUnmodifiedFileName = ts.createMap();
  97233. // Todo:: Use this to report why file was included in --extendedDiagnostics
  97234. var refFileMap;
  97235. var cachedBindAndCheckDiagnosticsForFile = {};
  97236. var cachedDeclarationDiagnosticsForFile = {};
  97237. var resolvedTypeReferenceDirectives = ts.createMap();
  97238. var fileProcessingDiagnostics = ts.createDiagnosticCollection();
  97239. // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
  97240. // This works as imported modules are discovered recursively in a depth first manner, specifically:
  97241. // - For each root file, findSourceFile is called.
  97242. // - This calls processImportedModules for each module imported in the source file.
  97243. // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
  97244. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
  97245. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
  97246. var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
  97247. var currentNodeModulesDepth = 0;
  97248. // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
  97249. // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
  97250. var modulesWithElidedImports = ts.createMap();
  97251. // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
  97252. var sourceFilesFoundSearchingNodeModules = ts.createMap();
  97253. ts.performance.mark("beforeProgram");
  97254. var host = createProgramOptions.host || createCompilerHost(options);
  97255. var configParsingHost = parseConfigHostFromCompilerHostLike(host);
  97256. var skipDefaultLib = options.noLib;
  97257. var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
  97258. var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
  97259. var programDiagnostics = ts.createDiagnosticCollection();
  97260. var currentDirectory = host.getCurrentDirectory();
  97261. var supportedExtensions = ts.getSupportedExtensions(options);
  97262. var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
  97263. // Map storing if there is emit blocking diagnostics for given input
  97264. var hasEmitBlockingDiagnostics = ts.createMap();
  97265. var _compilerOptionsObjectLiteralSyntax;
  97266. var moduleResolutionCache;
  97267. var resolveModuleNamesWorker;
  97268. var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
  97269. if (host.resolveModuleNames) {
  97270. resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
  97271. // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
  97272. if (!resolved || resolved.extension !== undefined) {
  97273. return resolved;
  97274. }
  97275. var withExtension = ts.clone(resolved);
  97276. withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
  97277. return withExtension;
  97278. }); };
  97279. }
  97280. else {
  97281. moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
  97282. var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
  97283. resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
  97284. }
  97285. var resolveTypeReferenceDirectiveNamesWorker;
  97286. if (host.resolveTypeReferenceDirectives) {
  97287. resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
  97288. }
  97289. else {
  97290. var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
  97291. resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
  97292. }
  97293. // Map from a stringified PackageId to the source file with that id.
  97294. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
  97295. // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
  97296. var packageIdToSourceFile = ts.createMap();
  97297. // Maps from a SourceFile's `.path` to the name of the package it was imported with.
  97298. var sourceFileToPackageName = ts.createMap();
  97299. // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
  97300. var redirectTargetsMap = ts.createMultiMap();
  97301. /**
  97302. * map with
  97303. * - SourceFile if present
  97304. * - false if sourceFile missing for source of project reference redirect
  97305. * - undefined otherwise
  97306. */
  97307. var filesByName = ts.createMap();
  97308. var missingFilePaths;
  97309. // stores 'filename -> file association' ignoring case
  97310. // used to track cases when two file names differ only in casing
  97311. var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
  97312. // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
  97313. var resolvedProjectReferences;
  97314. var projectReferenceRedirects;
  97315. var mapFromFileToProjectReferenceRedirects;
  97316. var mapFromToProjectReferenceRedirectSource;
  97317. var useSourceOfProjectReferenceRedirect = !!host.useSourceOfProjectReferenceRedirect && host.useSourceOfProjectReferenceRedirect();
  97318. var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
  97319. // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
  97320. // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
  97321. var structuralIsReused;
  97322. structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
  97323. if (structuralIsReused !== 2 /* Completely */) {
  97324. processingDefaultLibFiles = [];
  97325. processingOtherFiles = [];
  97326. if (projectReferences) {
  97327. if (!resolvedProjectReferences) {
  97328. resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
  97329. }
  97330. if (host.setResolvedProjectReferenceCallbacks) {
  97331. host.setResolvedProjectReferenceCallbacks({
  97332. getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
  97333. forEachResolvedProjectReference: forEachResolvedProjectReference
  97334. });
  97335. }
  97336. if (rootNames.length) {
  97337. for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
  97338. var parsedRef = resolvedProjectReferences_1[_i];
  97339. if (!parsedRef)
  97340. continue;
  97341. var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
  97342. if (useSourceOfProjectReferenceRedirect) {
  97343. if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
  97344. for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
  97345. var fileName = _b[_a];
  97346. processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
  97347. }
  97348. }
  97349. }
  97350. else {
  97351. if (out) {
  97352. processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
  97353. }
  97354. else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
  97355. for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
  97356. var fileName = _d[_c];
  97357. if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
  97358. processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
  97359. }
  97360. }
  97361. }
  97362. }
  97363. }
  97364. }
  97365. }
  97366. ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
  97367. // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
  97368. var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
  97369. if (typeReferences.length) {
  97370. // This containingFilename needs to match with the one used in managed-side
  97371. var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
  97372. var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
  97373. var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
  97374. for (var i = 0; i < typeReferences.length; i++) {
  97375. processTypeReferenceDirective(typeReferences[i], resolutions[i]);
  97376. }
  97377. }
  97378. // Do not process the default library if:
  97379. // - The '--noLib' flag is used.
  97380. // - A 'no-default-lib' reference comment is encountered in
  97381. // processing the root files.
  97382. if (rootNames.length && !skipDefaultLib) {
  97383. // If '--lib' is not specified, include default library file according to '--target'
  97384. // otherwise, using options specified in '--lib' instead of '--target' default library file
  97385. var defaultLibraryFileName = getDefaultLibraryFileName();
  97386. if (!options.lib && defaultLibraryFileName) {
  97387. processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
  97388. }
  97389. else {
  97390. ts.forEach(options.lib, function (libFileName) {
  97391. processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
  97392. });
  97393. }
  97394. }
  97395. missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
  97396. var path = _a[0], file = _a[1];
  97397. return file === undefined ? path : undefined;
  97398. }));
  97399. files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
  97400. processingDefaultLibFiles = undefined;
  97401. processingOtherFiles = undefined;
  97402. }
  97403. ts.Debug.assert(!!missingFilePaths);
  97404. // Release any files we have acquired in the old program but are
  97405. // not part of the new program.
  97406. if (oldProgram && host.onReleaseOldSourceFile) {
  97407. var oldSourceFiles = oldProgram.getSourceFiles();
  97408. for (var _e = 0, oldSourceFiles_1 = oldSourceFiles; _e < oldSourceFiles_1.length; _e++) {
  97409. var oldSourceFile = oldSourceFiles_1[_e];
  97410. var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
  97411. if (shouldCreateNewSourceFile || !newFile ||
  97412. // old file wasnt redirect but new file is
  97413. (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
  97414. host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
  97415. }
  97416. }
  97417. oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
  97418. if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
  97419. host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
  97420. }
  97421. });
  97422. }
  97423. // unconditionally set oldProgram to undefined to prevent it from being captured in closure
  97424. oldProgram = undefined;
  97425. var program = {
  97426. getRootFileNames: function () { return rootNames; },
  97427. getSourceFile: getSourceFile,
  97428. getSourceFileByPath: getSourceFileByPath,
  97429. getSourceFiles: function () { return files; },
  97430. getMissingFilePaths: function () { return missingFilePaths; },
  97431. getRefFileMap: function () { return refFileMap; },
  97432. getFilesByNameMap: function () { return filesByName; },
  97433. getCompilerOptions: function () { return options; },
  97434. getSyntacticDiagnostics: getSyntacticDiagnostics,
  97435. getOptionsDiagnostics: getOptionsDiagnostics,
  97436. getGlobalDiagnostics: getGlobalDiagnostics,
  97437. getSemanticDiagnostics: getSemanticDiagnostics,
  97438. getSuggestionDiagnostics: getSuggestionDiagnostics,
  97439. getDeclarationDiagnostics: getDeclarationDiagnostics,
  97440. getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
  97441. getProgramDiagnostics: getProgramDiagnostics,
  97442. getTypeChecker: getTypeChecker,
  97443. getClassifiableNames: getClassifiableNames,
  97444. getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
  97445. getCommonSourceDirectory: getCommonSourceDirectory,
  97446. emit: emit,
  97447. getCurrentDirectory: function () { return currentDirectory; },
  97448. getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
  97449. getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
  97450. getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
  97451. getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
  97452. getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
  97453. getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
  97454. getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
  97455. isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
  97456. isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
  97457. dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
  97458. getSourceFileFromReference: getSourceFileFromReference,
  97459. getLibFileFromReference: getLibFileFromReference,
  97460. sourceFileToPackageName: sourceFileToPackageName,
  97461. redirectTargetsMap: redirectTargetsMap,
  97462. isEmittedFile: isEmittedFile,
  97463. getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
  97464. getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
  97465. getProjectReferences: getProjectReferences,
  97466. getResolvedProjectReferences: getResolvedProjectReferences,
  97467. getProjectReferenceRedirect: getProjectReferenceRedirect,
  97468. getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
  97469. getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
  97470. forEachResolvedProjectReference: forEachResolvedProjectReference,
  97471. isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
  97472. emitBuildInfo: emitBuildInfo,
  97473. getProbableSymlinks: getProbableSymlinks
  97474. };
  97475. verifyCompilerOptions();
  97476. ts.performance.mark("afterProgram");
  97477. ts.performance.measure("Program", "beforeProgram", "afterProgram");
  97478. return program;
  97479. function compareDefaultLibFiles(a, b) {
  97480. return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
  97481. }
  97482. function getDefaultLibFilePriority(a) {
  97483. if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
  97484. var basename = ts.getBaseFileName(a.fileName);
  97485. if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
  97486. return 0;
  97487. var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
  97488. var index = ts.libs.indexOf(name);
  97489. if (index !== -1)
  97490. return index + 1;
  97491. }
  97492. return ts.libs.length + 2;
  97493. }
  97494. function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
  97495. return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
  97496. }
  97497. function toPath(fileName) {
  97498. return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  97499. }
  97500. function getCommonSourceDirectory() {
  97501. if (commonSourceDirectory === undefined) {
  97502. var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
  97503. if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
  97504. // If a rootDir is specified use it as the commonSourceDirectory
  97505. commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
  97506. }
  97507. else if (options.composite && options.configFilePath) {
  97508. // Project compilations never infer their root from the input source paths
  97509. commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
  97510. checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
  97511. }
  97512. else {
  97513. commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
  97514. }
  97515. if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
  97516. // Make sure directory path ends with directory separator so this string can directly
  97517. // used to replace with "" to get the relative path of the source file and the relative path doesn't
  97518. // start with / making it rooted path
  97519. commonSourceDirectory += ts.directorySeparator;
  97520. }
  97521. }
  97522. return commonSourceDirectory;
  97523. }
  97524. function getClassifiableNames() {
  97525. if (!classifiableNames) {
  97526. // Initialize a checker so that all our files are bound.
  97527. getTypeChecker();
  97528. classifiableNames = ts.createUnderscoreEscapedMap();
  97529. for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
  97530. var sourceFile = files_2[_i];
  97531. ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
  97532. }
  97533. }
  97534. return classifiableNames;
  97535. }
  97536. function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
  97537. if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
  97538. // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
  97539. // the best we can do is fallback to the default logic.
  97540. return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
  97541. }
  97542. var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
  97543. if (oldSourceFile !== file && file.resolvedModules) {
  97544. // `file` was created for the new program.
  97545. //
  97546. // We only set `file.resolvedModules` via work from the current function,
  97547. // so it is defined iff we already called the current function on `file`.
  97548. // That call happened no later than the creation of the `file` object,
  97549. // which per above occurred during the current program creation.
  97550. // Since we assume the filesystem does not change during program creation,
  97551. // it is safe to reuse resolutions from the earlier call.
  97552. var result_8 = [];
  97553. for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
  97554. var moduleName = moduleNames_1[_i];
  97555. var resolvedModule = file.resolvedModules.get(moduleName);
  97556. result_8.push(resolvedModule);
  97557. }
  97558. return result_8;
  97559. }
  97560. // At this point, we know at least one of the following hold:
  97561. // - file has local declarations for ambient modules
  97562. // - old program state is available
  97563. // With this information, we can infer some module resolutions without performing resolution.
  97564. /** An ordered list of module names for which we cannot recover the resolution. */
  97565. var unknownModuleNames;
  97566. /**
  97567. * The indexing of elements in this list matches that of `moduleNames`.
  97568. *
  97569. * Before combining results, result[i] is in one of the following states:
  97570. * * undefined: needs to be recomputed,
  97571. * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
  97572. * Needs to be reset to undefined before returning,
  97573. * * ResolvedModuleFull instance: can be reused.
  97574. */
  97575. var result;
  97576. var reusedNames;
  97577. /** A transient placeholder used to mark predicted resolution in the result list. */
  97578. var predictedToResolveToAmbientModuleMarker = {};
  97579. for (var i = 0; i < moduleNames.length; i++) {
  97580. var moduleName = moduleNames[i];
  97581. // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
  97582. if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
  97583. var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
  97584. if (oldResolvedModule) {
  97585. if (ts.isTraceEnabled(options, host)) {
  97586. ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
  97587. }
  97588. (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
  97589. (reusedNames || (reusedNames = [])).push(moduleName);
  97590. continue;
  97591. }
  97592. }
  97593. // We know moduleName resolves to an ambient module provided that moduleName:
  97594. // - is in the list of ambient modules locally declared in the current source file.
  97595. // - resolved to an ambient module in the old program whose declaration is in an unmodified file
  97596. // (so the same module declaration will land in the new program)
  97597. var resolvesToAmbientModuleInNonModifiedFile = false;
  97598. if (ts.contains(file.ambientModuleNames, moduleName)) {
  97599. resolvesToAmbientModuleInNonModifiedFile = true;
  97600. if (ts.isTraceEnabled(options, host)) {
  97601. ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
  97602. }
  97603. }
  97604. else {
  97605. resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
  97606. }
  97607. if (resolvesToAmbientModuleInNonModifiedFile) {
  97608. (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
  97609. }
  97610. else {
  97611. // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
  97612. (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
  97613. }
  97614. }
  97615. var resolutions = unknownModuleNames && unknownModuleNames.length
  97616. ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
  97617. : ts.emptyArray;
  97618. // Combine results of resolutions and predicted results
  97619. if (!result) {
  97620. // There were no unresolved/ambient resolutions.
  97621. ts.Debug.assert(resolutions.length === moduleNames.length);
  97622. return resolutions;
  97623. }
  97624. var j = 0;
  97625. for (var i = 0; i < result.length; i++) {
  97626. if (result[i]) {
  97627. // `result[i]` is either a `ResolvedModuleFull` or a marker.
  97628. // If it is the former, we can leave it as is.
  97629. if (result[i] === predictedToResolveToAmbientModuleMarker) {
  97630. result[i] = undefined; // TODO: GH#18217
  97631. }
  97632. }
  97633. else {
  97634. result[i] = resolutions[j];
  97635. j++;
  97636. }
  97637. }
  97638. ts.Debug.assert(j === resolutions.length);
  97639. return result;
  97640. // If we change our policy of rechecking failed lookups on each program create,
  97641. // we should adjust the value returned here.
  97642. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
  97643. var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
  97644. var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
  97645. if (resolutionToFile && resolvedFile) {
  97646. // In the old program, we resolved to an ambient module that was in the same
  97647. // place as we expected to find an actual module file.
  97648. // We actually need to return 'false' here even though this seems like a 'true' case
  97649. // because the normal module resolution algorithm will find this anyway.
  97650. return false;
  97651. }
  97652. // at least one of declarations should come from non-modified source file
  97653. var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
  97654. if (!unmodifiedFile) {
  97655. return false;
  97656. }
  97657. if (ts.isTraceEnabled(options, host)) {
  97658. ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
  97659. }
  97660. return true;
  97661. }
  97662. }
  97663. function canReuseProjectReferences() {
  97664. return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
  97665. var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
  97666. var newResolvedRef = parseProjectReferenceConfigFile(newRef);
  97667. if (oldResolvedRef) {
  97668. // Resolved project reference has gone missing or changed
  97669. return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
  97670. }
  97671. else {
  97672. // A previously-unresolved reference may be resolved now
  97673. return newResolvedRef !== undefined;
  97674. }
  97675. }, function (oldProjectReferences, parent) {
  97676. // If array of references is changed, we cant resue old program
  97677. var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
  97678. return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
  97679. });
  97680. }
  97681. function tryReuseStructureFromOldProgram() {
  97682. if (!oldProgram) {
  97683. return 0 /* Not */;
  97684. }
  97685. // check properties that can affect structure of the program or module resolution strategy
  97686. // if any of these properties has changed - structure cannot be reused
  97687. var oldOptions = oldProgram.getCompilerOptions();
  97688. if (ts.changesAffectModuleResolution(oldOptions, options)) {
  97689. return oldProgram.structureIsReused = 0 /* Not */;
  97690. }
  97691. ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
  97692. // there is an old program, check if we can reuse its structure
  97693. var oldRootNames = oldProgram.getRootFileNames();
  97694. if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
  97695. return oldProgram.structureIsReused = 0 /* Not */;
  97696. }
  97697. if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
  97698. return oldProgram.structureIsReused = 0 /* Not */;
  97699. }
  97700. // Check if any referenced project tsconfig files are different
  97701. if (!canReuseProjectReferences()) {
  97702. return oldProgram.structureIsReused = 0 /* Not */;
  97703. }
  97704. if (projectReferences) {
  97705. resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
  97706. if (host.setResolvedProjectReferenceCallbacks) {
  97707. host.setResolvedProjectReferenceCallbacks({
  97708. getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
  97709. forEachResolvedProjectReference: forEachResolvedProjectReference
  97710. });
  97711. }
  97712. }
  97713. // check if program source files has changed in the way that can affect structure of the program
  97714. var newSourceFiles = [];
  97715. var modifiedSourceFiles = [];
  97716. oldProgram.structureIsReused = 2 /* Completely */;
  97717. // If the missing file paths are now present, it can change the progam structure,
  97718. // and hence cant reuse the structure.
  97719. // This is same as how we dont reuse the structure if one of the file from old program is now missing
  97720. if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
  97721. return oldProgram.structureIsReused = 0 /* Not */;
  97722. }
  97723. var oldSourceFiles = oldProgram.getSourceFiles();
  97724. var SeenPackageName;
  97725. (function (SeenPackageName) {
  97726. SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
  97727. SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
  97728. })(SeenPackageName || (SeenPackageName = {}));
  97729. var seenPackageNames = ts.createMap();
  97730. for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
  97731. var oldSourceFile = oldSourceFiles_2[_i];
  97732. var newSourceFile = host.getSourceFileByPath
  97733. ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
  97734. : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
  97735. if (!newSourceFile) {
  97736. return oldProgram.structureIsReused = 0 /* Not */;
  97737. }
  97738. ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
  97739. var fileChanged = void 0;
  97740. if (oldSourceFile.redirectInfo) {
  97741. // We got `newSourceFile` by path, so it is actually for the unredirected file.
  97742. // This lets us know if the unredirected file has changed. If it has we should break the redirect.
  97743. if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
  97744. // Underlying file has changed. Might not redirect anymore. Must rebuild program.
  97745. return oldProgram.structureIsReused = 0 /* Not */;
  97746. }
  97747. fileChanged = false;
  97748. newSourceFile = oldSourceFile; // Use the redirect.
  97749. }
  97750. else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
  97751. // If a redirected-to source file changes, the redirect may be broken.
  97752. if (newSourceFile !== oldSourceFile) {
  97753. return oldProgram.structureIsReused = 0 /* Not */;
  97754. }
  97755. fileChanged = false;
  97756. }
  97757. else {
  97758. fileChanged = newSourceFile !== oldSourceFile;
  97759. }
  97760. // Since the project references havent changed, its right to set originalFileName and resolvedPath here
  97761. newSourceFile.path = oldSourceFile.path;
  97762. newSourceFile.originalFileName = oldSourceFile.originalFileName;
  97763. newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
  97764. newSourceFile.fileName = oldSourceFile.fileName;
  97765. var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
  97766. if (packageName !== undefined) {
  97767. // If there are 2 different source files for the same package name and at least one of them changes,
  97768. // they might become redirects. So we must rebuild the program.
  97769. var prevKind = seenPackageNames.get(packageName);
  97770. var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
  97771. if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
  97772. return oldProgram.structureIsReused = 0 /* Not */;
  97773. }
  97774. seenPackageNames.set(packageName, newKind);
  97775. }
  97776. if (fileChanged) {
  97777. // The `newSourceFile` object was created for the new program.
  97778. if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
  97779. // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
  97780. return oldProgram.structureIsReused = 0 /* Not */;
  97781. }
  97782. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
  97783. // value of no-default-lib has changed
  97784. // this will affect if default library is injected into the list of files
  97785. oldProgram.structureIsReused = 1 /* SafeModules */;
  97786. }
  97787. // check tripleslash references
  97788. if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
  97789. // tripleslash references has changed
  97790. oldProgram.structureIsReused = 1 /* SafeModules */;
  97791. }
  97792. // check imports and module augmentations
  97793. collectExternalModuleReferences(newSourceFile);
  97794. if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
  97795. // imports has changed
  97796. oldProgram.structureIsReused = 1 /* SafeModules */;
  97797. }
  97798. if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
  97799. // moduleAugmentations has changed
  97800. oldProgram.structureIsReused = 1 /* SafeModules */;
  97801. }
  97802. if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
  97803. // dynamicImport has changed
  97804. oldProgram.structureIsReused = 1 /* SafeModules */;
  97805. }
  97806. if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
  97807. // 'types' references has changed
  97808. oldProgram.structureIsReused = 1 /* SafeModules */;
  97809. }
  97810. // tentatively approve the file
  97811. modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
  97812. }
  97813. else if (hasInvalidatedResolution(oldSourceFile.path)) {
  97814. // 'module/types' references could have changed
  97815. oldProgram.structureIsReused = 1 /* SafeModules */;
  97816. // add file to the modified list so that we will resolve it later
  97817. modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
  97818. }
  97819. // if file has passed all checks it should be safe to reuse it
  97820. newSourceFiles.push(newSourceFile);
  97821. }
  97822. if (oldProgram.structureIsReused !== 2 /* Completely */) {
  97823. return oldProgram.structureIsReused;
  97824. }
  97825. var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
  97826. for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
  97827. var oldFile = oldSourceFiles_3[_a];
  97828. if (!ts.contains(modifiedFiles, oldFile)) {
  97829. for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
  97830. var moduleName = _c[_b];
  97831. ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
  97832. }
  97833. }
  97834. }
  97835. // try to verify results of module resolution
  97836. for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
  97837. var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
  97838. var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
  97839. var moduleNames = getModuleNames(newSourceFile);
  97840. var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
  97841. // ensure that module resolution results are still correct
  97842. var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
  97843. if (resolutionsChanged) {
  97844. oldProgram.structureIsReused = 1 /* SafeModules */;
  97845. newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
  97846. }
  97847. else {
  97848. newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
  97849. }
  97850. if (resolveTypeReferenceDirectiveNamesWorker) {
  97851. // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
  97852. var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
  97853. var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
  97854. // ensure that types resolutions are still correct
  97855. var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
  97856. if (resolutionsChanged_1) {
  97857. oldProgram.structureIsReused = 1 /* SafeModules */;
  97858. newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
  97859. }
  97860. else {
  97861. newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
  97862. }
  97863. }
  97864. }
  97865. if (oldProgram.structureIsReused !== 2 /* Completely */) {
  97866. return oldProgram.structureIsReused;
  97867. }
  97868. if (host.hasChangedAutomaticTypeDirectiveNames) {
  97869. return oldProgram.structureIsReused = 1 /* SafeModules */;
  97870. }
  97871. missingFilePaths = oldProgram.getMissingFilePaths();
  97872. refFileMap = oldProgram.getRefFileMap();
  97873. // update fileName -> file mapping
  97874. ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
  97875. for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
  97876. var newSourceFile = newSourceFiles_1[_f];
  97877. filesByName.set(newSourceFile.path, newSourceFile);
  97878. }
  97879. var oldFilesByNameMap = oldProgram.getFilesByNameMap();
  97880. oldFilesByNameMap.forEach(function (oldFile, path) {
  97881. if (!oldFile) {
  97882. filesByName.set(path, oldFile);
  97883. return;
  97884. }
  97885. if (oldFile.path === path) {
  97886. // Set the file as found during node modules search if it was found that way in old progra,
  97887. if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
  97888. sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
  97889. }
  97890. return;
  97891. }
  97892. filesByName.set(path, filesByName.get(oldFile.path));
  97893. });
  97894. files = newSourceFiles;
  97895. fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
  97896. for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
  97897. var modifiedFile = modifiedSourceFiles_2[_g];
  97898. fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
  97899. }
  97900. resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
  97901. sourceFileToPackageName = oldProgram.sourceFileToPackageName;
  97902. redirectTargetsMap = oldProgram.redirectTargetsMap;
  97903. return oldProgram.structureIsReused = 2 /* Completely */;
  97904. }
  97905. function getEmitHost(writeFileCallback) {
  97906. return __assign(__assign({ getPrependNodes: getPrependNodes,
  97907. getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
  97908. getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
  97909. isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
  97910. getProbableSymlinks: getProbableSymlinks, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
  97911. // Use local caches
  97912. var path = toPath(f);
  97913. if (getSourceFileByPath(path))
  97914. return true;
  97915. if (ts.contains(missingFilePaths, path))
  97916. return false;
  97917. // Before falling back to the host
  97918. return host.fileExists(f);
  97919. } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {})), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); }, getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap });
  97920. }
  97921. function emitBuildInfo(writeFileCallback) {
  97922. ts.Debug.assert(!options.out && !options.outFile);
  97923. ts.performance.mark("beforeEmit");
  97924. var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
  97925. /*targetSourceFile*/ undefined,
  97926. /*transformers*/ ts.noTransformers,
  97927. /*emitOnlyDtsFiles*/ false,
  97928. /*onlyBuildInfo*/ true);
  97929. ts.performance.mark("afterEmit");
  97930. ts.performance.measure("Emit", "beforeEmit", "afterEmit");
  97931. return emitResult;
  97932. }
  97933. function getResolvedProjectReferences() {
  97934. return resolvedProjectReferences;
  97935. }
  97936. function getProjectReferences() {
  97937. return projectReferences;
  97938. }
  97939. function getPrependNodes() {
  97940. return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
  97941. var path = toPath(fileName);
  97942. var sourceFile = getSourceFileByPath(path);
  97943. return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
  97944. });
  97945. }
  97946. function isSourceFileFromExternalLibrary(file) {
  97947. return !!sourceFilesFoundSearchingNodeModules.get(file.path);
  97948. }
  97949. function isSourceFileDefaultLibrary(file) {
  97950. if (file.hasNoDefaultLib) {
  97951. return true;
  97952. }
  97953. if (!options.noLib) {
  97954. return false;
  97955. }
  97956. // If '--lib' is not specified, include default library file according to '--target'
  97957. // otherwise, using options specified in '--lib' instead of '--target' default library file
  97958. var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
  97959. if (!options.lib) {
  97960. return equalityComparer(file.fileName, getDefaultLibraryFileName());
  97961. }
  97962. else {
  97963. return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
  97964. }
  97965. }
  97966. function getDiagnosticsProducingTypeChecker() {
  97967. return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
  97968. }
  97969. function dropDiagnosticsProducingTypeChecker() {
  97970. diagnosticsProducingTypeChecker = undefined;
  97971. }
  97972. function getTypeChecker() {
  97973. return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
  97974. }
  97975. function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
  97976. return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
  97977. }
  97978. function isEmitBlocked(emitFileName) {
  97979. return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
  97980. }
  97981. function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
  97982. if (!forceDtsEmit) {
  97983. var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
  97984. if (result)
  97985. return result;
  97986. }
  97987. // Create the emit resolver outside of the "emitTime" tracking code below. That way
  97988. // any cost associated with it (like type checking) are appropriate associated with
  97989. // the type-checking counter.
  97990. //
  97991. // If the -out option is specified, we should not pass the source file to getEmitResolver.
  97992. // This is because in the -out scenario all files need to be emitted, and therefore all
  97993. // files need to be type checked. And the way to specify that all files need to be type
  97994. // checked is to not pass the file to getEmitResolver.
  97995. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
  97996. ts.performance.mark("beforeEmit");
  97997. var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles,
  97998. /*onlyBuildInfo*/ false, forceDtsEmit);
  97999. ts.performance.mark("afterEmit");
  98000. ts.performance.measure("Emit", "beforeEmit", "afterEmit");
  98001. return emitResult;
  98002. }
  98003. function getSourceFile(fileName) {
  98004. return getSourceFileByPath(toPath(fileName));
  98005. }
  98006. function getSourceFileByPath(path) {
  98007. return filesByName.get(path) || undefined;
  98008. }
  98009. function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
  98010. if (sourceFile) {
  98011. return getDiagnostics(sourceFile, cancellationToken);
  98012. }
  98013. return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
  98014. if (cancellationToken) {
  98015. cancellationToken.throwIfCancellationRequested();
  98016. }
  98017. return getDiagnostics(sourceFile, cancellationToken);
  98018. }));
  98019. }
  98020. function getSyntacticDiagnostics(sourceFile, cancellationToken) {
  98021. return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
  98022. }
  98023. function getSemanticDiagnostics(sourceFile, cancellationToken) {
  98024. return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
  98025. }
  98026. function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
  98027. return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
  98028. }
  98029. function getProgramDiagnostics(sourceFile) {
  98030. if (ts.skipTypeChecking(sourceFile, options, program)) {
  98031. return ts.emptyArray;
  98032. }
  98033. var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
  98034. var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
  98035. var diagnostics;
  98036. for (var _i = 0, _a = [fileProcessingDiagnosticsInFile, programDiagnosticsInFile]; _i < _a.length; _i++) {
  98037. var diags = _a[_i];
  98038. if (diags) {
  98039. for (var _b = 0, diags_4 = diags; _b < diags_4.length; _b++) {
  98040. var diag = diags_4[_b];
  98041. if (shouldReportDiagnostic(diag)) {
  98042. diagnostics = ts.append(diagnostics, diag);
  98043. }
  98044. }
  98045. }
  98046. }
  98047. return diagnostics || ts.emptyArray;
  98048. }
  98049. function getDeclarationDiagnostics(sourceFile, cancellationToken) {
  98050. var options = program.getCompilerOptions();
  98051. // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
  98052. if (!sourceFile || options.out || options.outFile) {
  98053. return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
  98054. }
  98055. else {
  98056. return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
  98057. }
  98058. }
  98059. function getSyntacticDiagnosticsForFile(sourceFile) {
  98060. // For JavaScript files, we report semantic errors for using TypeScript-only
  98061. // constructs from within a JavaScript file as syntactic errors.
  98062. if (ts.isSourceFileJS(sourceFile)) {
  98063. if (!sourceFile.additionalSyntacticDiagnostics) {
  98064. sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
  98065. }
  98066. return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
  98067. }
  98068. return sourceFile.parseDiagnostics;
  98069. }
  98070. function runWithCancellationToken(func) {
  98071. try {
  98072. return func();
  98073. }
  98074. catch (e) {
  98075. if (e instanceof ts.OperationCanceledException) {
  98076. // We were canceled while performing the operation. Because our type checker
  98077. // might be a bad state, we need to throw it away.
  98078. //
  98079. // Note: we are overly aggressive here. We do not actually *have* to throw away
  98080. // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
  98081. // the lifetimes of these two TypeCheckers the same. Also, we generally only
  98082. // cancel when the user has made a change anyways. And, in that case, we (the
  98083. // program instance) will get thrown away anyways. So trying to keep one of
  98084. // these type checkers alive doesn't serve much purpose.
  98085. noDiagnosticsTypeChecker = undefined;
  98086. diagnosticsProducingTypeChecker = undefined;
  98087. }
  98088. throw e;
  98089. }
  98090. }
  98091. function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
  98092. return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
  98093. }
  98094. function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
  98095. return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
  98096. }
  98097. function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
  98098. return runWithCancellationToken(function () {
  98099. if (ts.skipTypeChecking(sourceFile, options, program)) {
  98100. return ts.emptyArray;
  98101. }
  98102. var typeChecker = getDiagnosticsProducingTypeChecker();
  98103. ts.Debug.assert(!!sourceFile.bindDiagnostics);
  98104. var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
  98105. var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
  98106. // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
  98107. var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
  98108. sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
  98109. var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
  98110. var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
  98111. var diagnostics;
  98112. for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) {
  98113. var diags = _a[_i];
  98114. if (diags) {
  98115. for (var _b = 0, diags_5 = diags; _b < diags_5.length; _b++) {
  98116. var diag = diags_5[_b];
  98117. if (shouldReportDiagnostic(diag)) {
  98118. diagnostics = ts.append(diagnostics, diag);
  98119. }
  98120. }
  98121. }
  98122. }
  98123. return diagnostics || ts.emptyArray;
  98124. });
  98125. }
  98126. function getSuggestionDiagnostics(sourceFile, cancellationToken) {
  98127. return runWithCancellationToken(function () {
  98128. return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
  98129. });
  98130. }
  98131. /**
  98132. * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines
  98133. */
  98134. function shouldReportDiagnostic(diagnostic) {
  98135. var file = diagnostic.file, start = diagnostic.start;
  98136. if (file) {
  98137. var lineStarts = ts.getLineStarts(file);
  98138. var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217
  98139. while (line > 0) {
  98140. var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
  98141. var result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
  98142. if (!result) {
  98143. // non-empty line
  98144. return true;
  98145. }
  98146. if (result[3]) {
  98147. // @ts-ignore
  98148. return false;
  98149. }
  98150. line--;
  98151. }
  98152. }
  98153. return true;
  98154. }
  98155. function getJSSyntacticDiagnosticsForFile(sourceFile) {
  98156. return runWithCancellationToken(function () {
  98157. var diagnostics = [];
  98158. var parent = sourceFile;
  98159. walk(sourceFile);
  98160. return diagnostics;
  98161. function walk(node) {
  98162. // Return directly from the case if the given node doesnt want to visit each child
  98163. // Otherwise break to visit each child
  98164. switch (parent.kind) {
  98165. case 156 /* Parameter */:
  98166. case 159 /* PropertyDeclaration */:
  98167. case 161 /* MethodDeclaration */:
  98168. if (parent.questionToken === node) {
  98169. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
  98170. return;
  98171. }
  98172. // falls through
  98173. case 160 /* MethodSignature */:
  98174. case 162 /* Constructor */:
  98175. case 163 /* GetAccessor */:
  98176. case 164 /* SetAccessor */:
  98177. case 201 /* FunctionExpression */:
  98178. case 244 /* FunctionDeclaration */:
  98179. case 202 /* ArrowFunction */:
  98180. case 242 /* VariableDeclaration */:
  98181. // type annotation
  98182. if (parent.type === node) {
  98183. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
  98184. return;
  98185. }
  98186. }
  98187. switch (node.kind) {
  98188. case 255 /* ImportClause */:
  98189. if (node.isTypeOnly) {
  98190. diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
  98191. return;
  98192. }
  98193. break;
  98194. case 260 /* ExportDeclaration */:
  98195. if (node.isTypeOnly) {
  98196. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
  98197. return;
  98198. }
  98199. break;
  98200. case 253 /* ImportEqualsDeclaration */:
  98201. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
  98202. return;
  98203. case 259 /* ExportAssignment */:
  98204. if (node.isExportEquals) {
  98205. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
  98206. return;
  98207. }
  98208. break;
  98209. case 279 /* HeritageClause */:
  98210. var heritageClause = node;
  98211. if (heritageClause.token === 113 /* ImplementsKeyword */) {
  98212. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
  98213. return;
  98214. }
  98215. break;
  98216. case 246 /* InterfaceDeclaration */:
  98217. var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
  98218. ts.Debug.assertDefined(interfaceKeyword);
  98219. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
  98220. return;
  98221. case 249 /* ModuleDeclaration */:
  98222. var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
  98223. ts.Debug.assertDefined(moduleKeyword);
  98224. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
  98225. return;
  98226. case 247 /* TypeAliasDeclaration */:
  98227. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
  98228. return;
  98229. case 248 /* EnumDeclaration */:
  98230. var enumKeyword = ts.Debug.assertDefined(ts.tokenToString(88 /* EnumKeyword */));
  98231. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
  98232. return;
  98233. case 218 /* NonNullExpression */:
  98234. diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
  98235. return;
  98236. case 217 /* AsExpression */:
  98237. diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
  98238. return;
  98239. case 199 /* TypeAssertionExpression */:
  98240. ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
  98241. }
  98242. var prevParent = parent;
  98243. parent = node;
  98244. ts.forEachChild(node, walk, walkArray);
  98245. parent = prevParent;
  98246. }
  98247. function walkArray(nodes) {
  98248. if (parent.decorators === nodes && !options.experimentalDecorators) {
  98249. diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning));
  98250. }
  98251. switch (parent.kind) {
  98252. case 245 /* ClassDeclaration */:
  98253. case 214 /* ClassExpression */:
  98254. case 161 /* MethodDeclaration */:
  98255. case 162 /* Constructor */:
  98256. case 163 /* GetAccessor */:
  98257. case 164 /* SetAccessor */:
  98258. case 201 /* FunctionExpression */:
  98259. case 244 /* FunctionDeclaration */:
  98260. case 202 /* ArrowFunction */:
  98261. // Check type parameters
  98262. if (nodes === parent.typeParameters) {
  98263. diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
  98264. return;
  98265. }
  98266. // falls through
  98267. case 225 /* VariableStatement */:
  98268. // Check modifiers
  98269. if (nodes === parent.modifiers) {
  98270. return checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
  98271. }
  98272. break;
  98273. case 159 /* PropertyDeclaration */:
  98274. // Check modifiers of property declaration
  98275. if (nodes === parent.modifiers) {
  98276. for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
  98277. var modifier = _a[_i];
  98278. if (modifier.kind !== 120 /* StaticKeyword */) {
  98279. diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
  98280. }
  98281. }
  98282. return;
  98283. }
  98284. break;
  98285. case 156 /* Parameter */:
  98286. // Check modifiers of parameter declaration
  98287. if (nodes === parent.modifiers) {
  98288. diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
  98289. return;
  98290. }
  98291. break;
  98292. case 196 /* CallExpression */:
  98293. case 197 /* NewExpression */:
  98294. case 216 /* ExpressionWithTypeArguments */:
  98295. case 267 /* JsxSelfClosingElement */:
  98296. case 268 /* JsxOpeningElement */:
  98297. case 198 /* TaggedTemplateExpression */:
  98298. // Check type arguments
  98299. if (nodes === parent.typeArguments) {
  98300. diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
  98301. return;
  98302. }
  98303. break;
  98304. }
  98305. for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) {
  98306. var node = nodes_6[_b];
  98307. walk(node);
  98308. }
  98309. }
  98310. function checkModifiers(modifiers, isConstValid) {
  98311. for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
  98312. var modifier = modifiers_1[_i];
  98313. switch (modifier.kind) {
  98314. case 81 /* ConstKeyword */:
  98315. if (isConstValid) {
  98316. continue;
  98317. }
  98318. // to report error,
  98319. // falls through
  98320. case 119 /* PublicKeyword */:
  98321. case 117 /* PrivateKeyword */:
  98322. case 118 /* ProtectedKeyword */:
  98323. case 138 /* ReadonlyKeyword */:
  98324. case 130 /* DeclareKeyword */:
  98325. case 122 /* AbstractKeyword */:
  98326. diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
  98327. break;
  98328. // These are all legal modifiers.
  98329. case 120 /* StaticKeyword */:
  98330. case 89 /* ExportKeyword */:
  98331. case 84 /* DefaultKeyword */:
  98332. }
  98333. }
  98334. }
  98335. function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
  98336. var start = nodes.pos;
  98337. return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
  98338. }
  98339. // Since these are syntactic diagnostics, parent might not have been set
  98340. // this means the sourceFile cannot be infered from the node
  98341. function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
  98342. return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
  98343. }
  98344. });
  98345. }
  98346. function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
  98347. return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
  98348. }
  98349. function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
  98350. return runWithCancellationToken(function () {
  98351. var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
  98352. // Don't actually write any files since we're just getting diagnostics.
  98353. return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
  98354. });
  98355. }
  98356. function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
  98357. var cachedResult = sourceFile
  98358. ? cache.perFile && cache.perFile.get(sourceFile.path)
  98359. : cache.allDiagnostics;
  98360. if (cachedResult) {
  98361. return cachedResult;
  98362. }
  98363. var result = getDiagnostics(sourceFile, cancellationToken);
  98364. if (sourceFile) {
  98365. if (!cache.perFile) {
  98366. cache.perFile = ts.createMap();
  98367. }
  98368. cache.perFile.set(sourceFile.path, result);
  98369. }
  98370. else {
  98371. cache.allDiagnostics = result;
  98372. }
  98373. return result;
  98374. }
  98375. function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
  98376. return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
  98377. }
  98378. function getOptionsDiagnostics() {
  98379. return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
  98380. }
  98381. function getOptionsDiagnosticsOfConfigFile() {
  98382. if (!options.configFile) {
  98383. return ts.emptyArray;
  98384. }
  98385. var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
  98386. forEachResolvedProjectReference(function (resolvedRef) {
  98387. if (resolvedRef) {
  98388. diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
  98389. }
  98390. });
  98391. return diagnostics;
  98392. }
  98393. function getGlobalDiagnostics() {
  98394. return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
  98395. }
  98396. function getConfigFileParsingDiagnostics() {
  98397. return configFileParsingDiagnostics || ts.emptyArray;
  98398. }
  98399. function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
  98400. processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
  98401. }
  98402. function fileReferenceIsEqualTo(a, b) {
  98403. return a.fileName === b.fileName;
  98404. }
  98405. function moduleNameIsEqualTo(a, b) {
  98406. return a.kind === 75 /* Identifier */
  98407. ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
  98408. : b.kind === 10 /* StringLiteral */ && a.text === b.text;
  98409. }
  98410. function collectExternalModuleReferences(file) {
  98411. if (file.imports) {
  98412. return;
  98413. }
  98414. var isJavaScriptFile = ts.isSourceFileJS(file);
  98415. var isExternalModuleFile = ts.isExternalModule(file);
  98416. // file.imports may not be undefined if there exists dynamic import
  98417. var imports;
  98418. var moduleAugmentations;
  98419. var ambientModules;
  98420. // If we are importing helpers, we need to add a synthetic reference to resolve the
  98421. // helpers library.
  98422. if (options.importHelpers
  98423. && (options.isolatedModules || isExternalModuleFile)
  98424. && !file.isDeclarationFile) {
  98425. // synthesize 'import "tslib"' declaration
  98426. var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
  98427. var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
  98428. ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
  98429. externalHelpersModuleReference.parent = importDecl;
  98430. importDecl.parent = file;
  98431. imports = [externalHelpersModuleReference];
  98432. }
  98433. for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
  98434. var node = _a[_i];
  98435. collectModuleReferences(node, /*inAmbientModule*/ false);
  98436. }
  98437. if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
  98438. collectDynamicImportOrRequireCalls(file);
  98439. }
  98440. file.imports = imports || ts.emptyArray;
  98441. file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
  98442. file.ambientModuleNames = ambientModules || ts.emptyArray;
  98443. return;
  98444. function collectModuleReferences(node, inAmbientModule) {
  98445. if (ts.isAnyImportOrReExport(node)) {
  98446. var moduleNameExpr = ts.getExternalModuleName(node);
  98447. // TypeScript 1.0 spec (April 2014): 12.1.6
  98448. // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
  98449. // only through top - level external module names. Relative external module names are not permitted.
  98450. if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
  98451. imports = ts.append(imports, moduleNameExpr);
  98452. }
  98453. }
  98454. else if (ts.isModuleDeclaration(node)) {
  98455. if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
  98456. var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
  98457. // Ambient module declarations can be interpreted as augmentations for some existing external modules.
  98458. // This will happen in two cases:
  98459. // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
  98460. // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
  98461. // immediately nested in top level ambient module declaration .
  98462. if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
  98463. (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
  98464. }
  98465. else if (!inAmbientModule) {
  98466. if (file.isDeclarationFile) {
  98467. // for global .d.ts files record name of ambient module
  98468. (ambientModules || (ambientModules = [])).push(nameText);
  98469. }
  98470. // An AmbientExternalModuleDeclaration declares an external module.
  98471. // This type of declaration is permitted only in the global module.
  98472. // The StringLiteral must specify a top - level external module name.
  98473. // Relative external module names are not permitted
  98474. // NOTE: body of ambient module is always a module block, if it exists
  98475. var body = node.body;
  98476. if (body) {
  98477. for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
  98478. var statement = _a[_i];
  98479. collectModuleReferences(statement, /*inAmbientModule*/ true);
  98480. }
  98481. }
  98482. }
  98483. }
  98484. }
  98485. }
  98486. function collectDynamicImportOrRequireCalls(file) {
  98487. var r = /import|require/g;
  98488. while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
  98489. var node = getNodeAtPosition(file, r.lastIndex);
  98490. if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
  98491. imports = ts.append(imports, node.arguments[0]);
  98492. }
  98493. // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
  98494. else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
  98495. imports = ts.append(imports, node.arguments[0]);
  98496. }
  98497. else if (ts.isLiteralImportTypeNode(node)) {
  98498. imports = ts.append(imports, node.argument.literal);
  98499. }
  98500. }
  98501. }
  98502. /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
  98503. function getNodeAtPosition(sourceFile, position) {
  98504. var current = sourceFile;
  98505. var getContainingChild = function (child) {
  98506. if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
  98507. return child;
  98508. }
  98509. };
  98510. while (true) {
  98511. var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
  98512. if (!child) {
  98513. return current;
  98514. }
  98515. current = child;
  98516. }
  98517. }
  98518. }
  98519. function getLibFileFromReference(ref) {
  98520. var libName = ts.toFileNameLowerCase(ref.fileName);
  98521. var libFileName = ts.libMap.get(libName);
  98522. if (libFileName) {
  98523. return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
  98524. }
  98525. }
  98526. /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
  98527. function getSourceFileFromReference(referencingFile, ref) {
  98528. return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
  98529. }
  98530. function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
  98531. if (ts.hasExtension(fileName)) {
  98532. var canonicalFileName_1 = host.getCanonicalFileName(fileName);
  98533. if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
  98534. if (fail) {
  98535. if (ts.hasJSFileExtension(canonicalFileName_1)) {
  98536. fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
  98537. }
  98538. else {
  98539. fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
  98540. }
  98541. }
  98542. return undefined;
  98543. }
  98544. var sourceFile = getSourceFile(fileName);
  98545. if (fail) {
  98546. if (!sourceFile) {
  98547. var redirect = getProjectReferenceRedirect(fileName);
  98548. if (redirect) {
  98549. fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
  98550. }
  98551. else {
  98552. fail(ts.Diagnostics.File_0_not_found, fileName);
  98553. }
  98554. }
  98555. else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
  98556. fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
  98557. }
  98558. }
  98559. return sourceFile;
  98560. }
  98561. else {
  98562. var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
  98563. if (sourceFileNoExtension)
  98564. return sourceFileNoExtension;
  98565. if (fail && options.allowNonTsExtensions) {
  98566. fail(ts.Diagnostics.File_0_not_found, fileName);
  98567. return undefined;
  98568. }
  98569. var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
  98570. if (fail && !sourceFileWithAddedExtension)
  98571. fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */);
  98572. return sourceFileWithAddedExtension;
  98573. }
  98574. }
  98575. /** This has side effects through `findSourceFile`. */
  98576. function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
  98577. getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
  98578. function (diagnostic) {
  98579. var args = [];
  98580. for (var _i = 1; _i < arguments.length; _i++) {
  98581. args[_i - 1] = arguments[_i];
  98582. }
  98583. return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
  98584. }, refFile && refFile.file);
  98585. }
  98586. function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
  98587. var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
  98588. var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
  98589. fileProcessingDiagnostics.add(refToReportErrorOn ?
  98590. createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
  98591. createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
  98592. }
  98593. function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
  98594. var redirect = Object.create(redirectTarget);
  98595. redirect.fileName = fileName;
  98596. redirect.path = path;
  98597. redirect.resolvedPath = resolvedPath;
  98598. redirect.originalFileName = originalFileName;
  98599. redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
  98600. sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
  98601. Object.defineProperties(redirect, {
  98602. id: {
  98603. get: function () { return this.redirectInfo.redirectTarget.id; },
  98604. set: function (value) { this.redirectInfo.redirectTarget.id = value; },
  98605. },
  98606. symbol: {
  98607. get: function () { return this.redirectInfo.redirectTarget.symbol; },
  98608. set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
  98609. },
  98610. });
  98611. return redirect;
  98612. }
  98613. // Get source file from normalized fileName
  98614. function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
  98615. if (useSourceOfProjectReferenceRedirect) {
  98616. var source = getSourceOfProjectReferenceRedirect(fileName);
  98617. // If preserveSymlinks is true, module resolution wont jump the symlink
  98618. // but the resolved real path may be the .d.ts from project reference
  98619. // Note:: Currently we try the real path only if the
  98620. // file is from node_modules to avoid having to run real path on all file paths
  98621. if (!source &&
  98622. host.realpath &&
  98623. options.preserveSymlinks &&
  98624. ts.isDeclarationFileName(fileName) &&
  98625. ts.stringContains(fileName, ts.nodeModulesPathPart)) {
  98626. var realPath = host.realpath(fileName);
  98627. if (realPath !== fileName)
  98628. source = getSourceOfProjectReferenceRedirect(realPath);
  98629. }
  98630. if (source) {
  98631. var file_1 = ts.isString(source) ?
  98632. findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
  98633. undefined;
  98634. if (file_1)
  98635. addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
  98636. return file_1;
  98637. }
  98638. }
  98639. var originalFileName = fileName;
  98640. if (filesByName.has(path)) {
  98641. var file_2 = filesByName.get(path);
  98642. addFileToRefFileMap(fileName, file_2 || undefined, refFile);
  98643. // try to check if we've already seen this file but with a different casing in path
  98644. // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
  98645. if (file_2 && options.forceConsistentCasingInFileNames) {
  98646. var checkedName = file_2.fileName;
  98647. var isRedirect = toPath(checkedName) !== toPath(fileName);
  98648. if (isRedirect) {
  98649. fileName = getProjectReferenceRedirect(fileName) || fileName;
  98650. }
  98651. // Check if it differs only in drive letters its ok to ignore that error:
  98652. var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
  98653. var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
  98654. if (checkedAbsolutePath !== inputAbsolutePath) {
  98655. reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
  98656. }
  98657. }
  98658. // If the file was previously found via a node_modules search, but is now being processed as a root file,
  98659. // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
  98660. if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
  98661. sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
  98662. if (!options.noResolve) {
  98663. processReferencedFiles(file_2, isDefaultLib);
  98664. processTypeReferenceDirectives(file_2);
  98665. }
  98666. if (!options.noLib) {
  98667. processLibReferenceDirectives(file_2);
  98668. }
  98669. modulesWithElidedImports.set(file_2.path, false);
  98670. processImportedModules(file_2);
  98671. }
  98672. // See if we need to reprocess the imports due to prior skipped imports
  98673. else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
  98674. if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
  98675. modulesWithElidedImports.set(file_2.path, false);
  98676. processImportedModules(file_2);
  98677. }
  98678. }
  98679. return file_2 || undefined;
  98680. }
  98681. var redirectedPath;
  98682. if (refFile && !useSourceOfProjectReferenceRedirect) {
  98683. var redirectProject = getProjectReferenceRedirectProject(fileName);
  98684. if (redirectProject) {
  98685. if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
  98686. // Shouldnt create many to 1 mapping file in --out scenario
  98687. return undefined;
  98688. }
  98689. var redirect = getProjectReferenceOutputName(redirectProject, fileName);
  98690. fileName = redirect;
  98691. // Once we start redirecting to a file, we can potentially come back to it
  98692. // via a back-reference from another file in the .d.ts folder. If that happens we'll
  98693. // end up trying to add it to the program *again* because we were tracking it via its
  98694. // original (un-redirected) name. So we have to map both the original path and the redirected path
  98695. // to the source file we're about to find/create
  98696. redirectedPath = toPath(redirect);
  98697. }
  98698. }
  98699. // We haven't looked for this file, do so now and cache result
  98700. var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { return fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); }, shouldCreateNewSourceFile);
  98701. if (packageId) {
  98702. var packageIdKey = ts.packageIdToString(packageId);
  98703. var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
  98704. if (fileFromPackageId) {
  98705. // Some other SourceFile already exists with this package name and version.
  98706. // Instead of creating a duplicate, just redirect to the existing one.
  98707. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
  98708. redirectTargetsMap.add(fileFromPackageId.path, fileName);
  98709. addFileToFilesByName(dupFile, path, redirectedPath);
  98710. sourceFileToPackageName.set(path, packageId.name);
  98711. processingOtherFiles.push(dupFile);
  98712. return dupFile;
  98713. }
  98714. else if (file) {
  98715. // This is the first source file to have this packageId.
  98716. packageIdToSourceFile.set(packageIdKey, file);
  98717. sourceFileToPackageName.set(path, packageId.name);
  98718. }
  98719. }
  98720. addFileToFilesByName(file, path, redirectedPath);
  98721. if (file) {
  98722. sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
  98723. file.fileName = fileName; // Ensure that source file has same name as what we were looking for
  98724. file.path = path;
  98725. file.resolvedPath = toPath(fileName);
  98726. file.originalFileName = originalFileName;
  98727. addFileToRefFileMap(fileName, file, refFile);
  98728. if (host.useCaseSensitiveFileNames()) {
  98729. var pathLowerCase = ts.toFileNameLowerCase(path);
  98730. // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
  98731. var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
  98732. if (existingFile) {
  98733. reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
  98734. }
  98735. else {
  98736. filesByNameIgnoreCase.set(pathLowerCase, file);
  98737. }
  98738. }
  98739. skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
  98740. if (!options.noResolve) {
  98741. processReferencedFiles(file, isDefaultLib);
  98742. processTypeReferenceDirectives(file);
  98743. }
  98744. if (!options.noLib) {
  98745. processLibReferenceDirectives(file);
  98746. }
  98747. // always process imported modules to record module name resolutions
  98748. processImportedModules(file);
  98749. if (isDefaultLib) {
  98750. processingDefaultLibFiles.push(file);
  98751. }
  98752. else {
  98753. processingOtherFiles.push(file);
  98754. }
  98755. }
  98756. return file;
  98757. }
  98758. function addFileToRefFileMap(referencedFileName, file, refFile) {
  98759. if (refFile && file) {
  98760. (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
  98761. referencedFileName: referencedFileName,
  98762. kind: refFile.kind,
  98763. index: refFile.index,
  98764. file: refFile.file.path
  98765. });
  98766. }
  98767. }
  98768. function addFileToFilesByName(file, path, redirectedPath) {
  98769. if (redirectedPath) {
  98770. filesByName.set(redirectedPath, file);
  98771. filesByName.set(path, file || false);
  98772. }
  98773. else {
  98774. filesByName.set(path, file);
  98775. }
  98776. }
  98777. function getProjectReferenceRedirect(fileName) {
  98778. var referencedProject = getProjectReferenceRedirectProject(fileName);
  98779. return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
  98780. }
  98781. function getProjectReferenceRedirectProject(fileName) {
  98782. // Ignore dts or any json files
  98783. if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
  98784. return undefined;
  98785. }
  98786. // If this file is produced by a referenced project, we need to rewrite it to
  98787. // look in the output folder of the referenced project rather than the input
  98788. return getResolvedProjectReferenceToRedirect(fileName);
  98789. }
  98790. function getProjectReferenceOutputName(referencedProject, fileName) {
  98791. var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
  98792. return out ?
  98793. ts.changeExtension(out, ".d.ts" /* Dts */) :
  98794. ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
  98795. }
  98796. /**
  98797. * Get the referenced project if the file is input file from that reference project
  98798. */
  98799. function getResolvedProjectReferenceToRedirect(fileName) {
  98800. if (mapFromFileToProjectReferenceRedirects === undefined) {
  98801. mapFromFileToProjectReferenceRedirects = ts.createMap();
  98802. forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
  98803. // not input file from the referenced project, ignore
  98804. if (referencedProject &&
  98805. toPath(options.configFilePath) !== referenceProjectPath) {
  98806. referencedProject.commandLine.fileNames.forEach(function (f) {
  98807. return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
  98808. });
  98809. }
  98810. });
  98811. }
  98812. var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
  98813. return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
  98814. }
  98815. function forEachResolvedProjectReference(cb) {
  98816. return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
  98817. var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
  98818. var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
  98819. return cb(resolvedRef, resolvedRefPath);
  98820. });
  98821. }
  98822. function getSourceOfProjectReferenceRedirect(file) {
  98823. if (!ts.isDeclarationFileName(file))
  98824. return undefined;
  98825. if (mapFromToProjectReferenceRedirectSource === undefined) {
  98826. mapFromToProjectReferenceRedirectSource = ts.createMap();
  98827. forEachResolvedProjectReference(function (resolvedRef) {
  98828. if (resolvedRef) {
  98829. var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
  98830. if (out) {
  98831. // Dont know which source file it means so return true?
  98832. var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
  98833. mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
  98834. }
  98835. else {
  98836. ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
  98837. if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
  98838. var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
  98839. mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
  98840. }
  98841. });
  98842. }
  98843. }
  98844. });
  98845. }
  98846. return mapFromToProjectReferenceRedirectSource.get(toPath(file));
  98847. }
  98848. function isSourceOfProjectReferenceRedirect(fileName) {
  98849. return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
  98850. }
  98851. function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
  98852. var seenResolvedRefs;
  98853. return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
  98854. function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
  98855. // Visit project references first
  98856. if (cbRef) {
  98857. var result = cbRef(projectReferences, parent);
  98858. if (result) {
  98859. return result;
  98860. }
  98861. }
  98862. return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
  98863. if (ts.contains(seenResolvedRefs, resolvedRef)) {
  98864. // ignore recursives
  98865. return undefined;
  98866. }
  98867. var result = cbResolvedRef(resolvedRef, index, parent);
  98868. if (result) {
  98869. return result;
  98870. }
  98871. if (!resolvedRef)
  98872. return undefined;
  98873. (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
  98874. return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
  98875. });
  98876. }
  98877. }
  98878. function getResolvedProjectReferenceByPath(projectReferencePath) {
  98879. if (!projectReferenceRedirects) {
  98880. return undefined;
  98881. }
  98882. return projectReferenceRedirects.get(projectReferencePath) || undefined;
  98883. }
  98884. function processReferencedFiles(file, isDefaultLib) {
  98885. ts.forEach(file.referencedFiles, function (ref, index) {
  98886. var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
  98887. processSourceFile(referencedFileName, isDefaultLib,
  98888. /*ignoreNoDefaultLib*/ false,
  98889. /*packageId*/ undefined, {
  98890. kind: ts.RefFileKind.ReferenceFile,
  98891. index: index,
  98892. file: file,
  98893. pos: ref.pos,
  98894. end: ref.end
  98895. });
  98896. });
  98897. }
  98898. function processTypeReferenceDirectives(file) {
  98899. // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
  98900. var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
  98901. if (!typeDirectives) {
  98902. return;
  98903. }
  98904. var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
  98905. for (var i = 0; i < typeDirectives.length; i++) {
  98906. var ref = file.typeReferenceDirectives[i];
  98907. var resolvedTypeReferenceDirective = resolutions[i];
  98908. // store resolved type directive on the file
  98909. var fileName = ts.toFileNameLowerCase(ref.fileName);
  98910. ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
  98911. processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
  98912. kind: ts.RefFileKind.TypeReferenceDirective,
  98913. index: i,
  98914. file: file,
  98915. pos: ref.pos,
  98916. end: ref.end
  98917. });
  98918. }
  98919. }
  98920. function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
  98921. // If we already found this library as a primary reference - nothing to do
  98922. var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
  98923. if (previousResolution && previousResolution.primary) {
  98924. return;
  98925. }
  98926. var saveResolution = true;
  98927. if (resolvedTypeReferenceDirective) {
  98928. if (resolvedTypeReferenceDirective.isExternalLibraryImport)
  98929. currentNodeModulesDepth++;
  98930. if (resolvedTypeReferenceDirective.primary) {
  98931. // resolved from the primary path
  98932. processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
  98933. }
  98934. else {
  98935. // If we already resolved to this file, it must have been a secondary reference. Check file contents
  98936. // for sameness and possibly issue an error
  98937. if (previousResolution) {
  98938. // Don't bother reading the file again if it's the same file.
  98939. if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
  98940. var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
  98941. var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
  98942. if (otherFileText !== existingFile_1.text) {
  98943. // Try looking up ref for original file
  98944. var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
  98945. var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
  98946. fileProcessingDiagnostics.add(refToReportErrorOn ?
  98947. createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName) :
  98948. createRefFileDiagnostic(refFile, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName));
  98949. }
  98950. }
  98951. // don't overwrite previous resolution result
  98952. saveResolution = false;
  98953. }
  98954. else {
  98955. // First resolution of this library
  98956. processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
  98957. }
  98958. }
  98959. if (resolvedTypeReferenceDirective.isExternalLibraryImport)
  98960. currentNodeModulesDepth--;
  98961. }
  98962. else {
  98963. fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
  98964. }
  98965. if (saveResolution) {
  98966. resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
  98967. }
  98968. }
  98969. function processLibReferenceDirectives(file) {
  98970. ts.forEach(file.libReferenceDirectives, function (libReference) {
  98971. var libName = ts.toFileNameLowerCase(libReference.fileName);
  98972. var libFileName = ts.libMap.get(libName);
  98973. if (libFileName) {
  98974. // we ignore any 'no-default-lib' reference set on this file.
  98975. processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
  98976. }
  98977. else {
  98978. var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
  98979. var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
  98980. var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
  98981. fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
  98982. }
  98983. });
  98984. }
  98985. function createRefFileDiagnostic(refFile, message) {
  98986. var args = [];
  98987. for (var _i = 2; _i < arguments.length; _i++) {
  98988. args[_i - 2] = arguments[_i];
  98989. }
  98990. if (!refFile) {
  98991. return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
  98992. }
  98993. else {
  98994. return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
  98995. }
  98996. }
  98997. function getCanonicalFileName(fileName) {
  98998. return host.getCanonicalFileName(fileName);
  98999. }
  99000. function processImportedModules(file) {
  99001. collectExternalModuleReferences(file);
  99002. if (file.imports.length || file.moduleAugmentations.length) {
  99003. // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
  99004. var moduleNames = getModuleNames(file);
  99005. var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
  99006. ts.Debug.assert(resolutions.length === moduleNames.length);
  99007. for (var i = 0; i < moduleNames.length; i++) {
  99008. var resolution = resolutions[i];
  99009. ts.setResolvedModule(file, moduleNames[i], resolution);
  99010. if (!resolution) {
  99011. continue;
  99012. }
  99013. var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
  99014. var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
  99015. var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
  99016. var resolvedFileName = resolution.resolvedFileName;
  99017. if (isFromNodeModulesSearch) {
  99018. currentNodeModulesDepth++;
  99019. }
  99020. // add file to program only if:
  99021. // - resolution was successful
  99022. // - noResolve is falsy
  99023. // - module name comes from the list of imports
  99024. // - it's not a top level JavaScript module that exceeded the search max
  99025. var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
  99026. // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
  99027. // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
  99028. var shouldAddFile = resolvedFileName
  99029. && !getResolutionDiagnostic(options, resolution)
  99030. && !options.noResolve
  99031. && i < file.imports.length
  99032. && !elideImport
  99033. && !(isJsFile && !options.allowJs)
  99034. && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
  99035. if (elideImport) {
  99036. modulesWithElidedImports.set(file.path, true);
  99037. }
  99038. else if (shouldAddFile) {
  99039. var path = toPath(resolvedFileName);
  99040. var pos = ts.skipTrivia(file.text, file.imports[i].pos);
  99041. findSourceFile(resolvedFileName, path,
  99042. /*isDefaultLib*/ false,
  99043. /*ignoreNoDefaultLib*/ false, {
  99044. kind: ts.RefFileKind.Import,
  99045. index: i,
  99046. file: file,
  99047. pos: pos,
  99048. end: file.imports[i].end
  99049. }, resolution.packageId);
  99050. }
  99051. if (isFromNodeModulesSearch) {
  99052. currentNodeModulesDepth--;
  99053. }
  99054. }
  99055. }
  99056. else {
  99057. // no imports - drop cached module resolutions
  99058. file.resolvedModules = undefined;
  99059. }
  99060. }
  99061. function computeCommonSourceDirectory(sourceFiles) {
  99062. var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
  99063. return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
  99064. }
  99065. function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
  99066. var allFilesBelongToPath = true;
  99067. var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
  99068. var rootPaths;
  99069. for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
  99070. var sourceFile = sourceFiles_2[_i];
  99071. if (!sourceFile.isDeclarationFile) {
  99072. var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
  99073. if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
  99074. if (!rootPaths)
  99075. rootPaths = ts.arrayToSet(rootNames, toPath);
  99076. addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
  99077. allFilesBelongToPath = false;
  99078. }
  99079. }
  99080. }
  99081. return allFilesBelongToPath;
  99082. }
  99083. function parseProjectReferenceConfigFile(ref) {
  99084. if (!projectReferenceRedirects) {
  99085. projectReferenceRedirects = ts.createMap();
  99086. }
  99087. // The actual filename (i.e. add "/tsconfig.json" if necessary)
  99088. var refPath = resolveProjectReferencePath(ref);
  99089. var sourceFilePath = toPath(refPath);
  99090. var fromCache = projectReferenceRedirects.get(sourceFilePath);
  99091. if (fromCache !== undefined) {
  99092. return fromCache || undefined;
  99093. }
  99094. var commandLine;
  99095. var sourceFile;
  99096. if (host.getParsedCommandLine) {
  99097. commandLine = host.getParsedCommandLine(refPath);
  99098. if (!commandLine) {
  99099. addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
  99100. projectReferenceRedirects.set(sourceFilePath, false);
  99101. return undefined;
  99102. }
  99103. sourceFile = ts.Debug.assertDefined(commandLine.options.configFile);
  99104. ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
  99105. addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
  99106. }
  99107. else {
  99108. // An absolute path pointing to the containing directory of the config file
  99109. var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
  99110. sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
  99111. addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
  99112. if (sourceFile === undefined) {
  99113. projectReferenceRedirects.set(sourceFilePath, false);
  99114. return undefined;
  99115. }
  99116. commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
  99117. }
  99118. sourceFile.fileName = refPath;
  99119. sourceFile.path = sourceFilePath;
  99120. sourceFile.resolvedPath = sourceFilePath;
  99121. sourceFile.originalFileName = refPath;
  99122. var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
  99123. projectReferenceRedirects.set(sourceFilePath, resolvedRef);
  99124. if (commandLine.projectReferences) {
  99125. resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
  99126. }
  99127. return resolvedRef;
  99128. }
  99129. function verifyCompilerOptions() {
  99130. if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
  99131. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
  99132. }
  99133. if (options.isolatedModules) {
  99134. if (options.out) {
  99135. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
  99136. }
  99137. if (options.outFile) {
  99138. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
  99139. }
  99140. }
  99141. if (options.inlineSourceMap) {
  99142. if (options.sourceMap) {
  99143. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
  99144. }
  99145. if (options.mapRoot) {
  99146. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
  99147. }
  99148. }
  99149. if (options.paths && options.baseUrl === undefined) {
  99150. createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
  99151. }
  99152. if (options.composite) {
  99153. if (options.declaration === false) {
  99154. createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
  99155. }
  99156. if (options.incremental === false) {
  99157. createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
  99158. }
  99159. }
  99160. if (options.tsBuildInfoFile) {
  99161. if (!ts.isIncrementalCompilation(options)) {
  99162. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
  99163. }
  99164. }
  99165. else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
  99166. programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
  99167. }
  99168. if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
  99169. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
  99170. }
  99171. verifyProjectReferences();
  99172. // List of collected files is complete; validate exhautiveness if this is a project with a file list
  99173. if (options.composite) {
  99174. var rootPaths = ts.arrayToSet(rootNames, toPath);
  99175. for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
  99176. var file = files_3[_i];
  99177. // Ignore file that is not emitted
  99178. if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
  99179. addProgramDiagnosticAtRefPath(file, rootPaths, ts.Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, file.fileName, options.configFilePath || "");
  99180. }
  99181. }
  99182. }
  99183. if (options.paths) {
  99184. for (var key in options.paths) {
  99185. if (!ts.hasProperty(options.paths, key)) {
  99186. continue;
  99187. }
  99188. if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
  99189. createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
  99190. }
  99191. if (ts.isArray(options.paths[key])) {
  99192. var len = options.paths[key].length;
  99193. if (len === 0) {
  99194. createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
  99195. }
  99196. for (var i = 0; i < len; i++) {
  99197. var subst = options.paths[key][i];
  99198. var typeOfSubst = typeof subst;
  99199. if (typeOfSubst === "string") {
  99200. if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
  99201. createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
  99202. }
  99203. }
  99204. else {
  99205. createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
  99206. }
  99207. }
  99208. }
  99209. else {
  99210. createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
  99211. }
  99212. }
  99213. }
  99214. if (!options.sourceMap && !options.inlineSourceMap) {
  99215. if (options.inlineSources) {
  99216. createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
  99217. }
  99218. if (options.sourceRoot) {
  99219. createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
  99220. }
  99221. }
  99222. if (options.out && options.outFile) {
  99223. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
  99224. }
  99225. if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
  99226. // Error to specify --mapRoot without --sourcemap
  99227. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
  99228. }
  99229. if (options.declarationDir) {
  99230. if (!ts.getEmitDeclarations(options)) {
  99231. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
  99232. }
  99233. if (options.out || options.outFile) {
  99234. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
  99235. }
  99236. }
  99237. if (options.declarationMap && !ts.getEmitDeclarations(options)) {
  99238. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
  99239. }
  99240. if (options.lib && options.noLib) {
  99241. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
  99242. }
  99243. if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
  99244. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
  99245. }
  99246. var languageVersion = options.target || 0 /* ES3 */;
  99247. var outFile = options.outFile || options.out;
  99248. var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
  99249. if (options.isolatedModules) {
  99250. if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
  99251. createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
  99252. }
  99253. var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
  99254. if (firstNonExternalModuleSourceFile) {
  99255. var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
  99256. programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
  99257. }
  99258. }
  99259. else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
  99260. // We cannot use createDiagnosticFromNode because nodes do not have parents yet
  99261. var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
  99262. programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
  99263. }
  99264. // Cannot specify module gen that isn't amd or system with --out
  99265. if (outFile && !options.emitDeclarationOnly) {
  99266. if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
  99267. createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
  99268. }
  99269. else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
  99270. var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
  99271. programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
  99272. }
  99273. }
  99274. if (options.resolveJsonModule) {
  99275. if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
  99276. createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
  99277. }
  99278. // Any emit other than common js, amd, es2015 or esnext is error
  99279. else if (!ts.hasJsonModuleEmitEnabled(options)) {
  99280. createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
  99281. }
  99282. }
  99283. // there has to be common source directory if user specified --outdir || --sourceRoot
  99284. // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
  99285. if (options.outDir || // there is --outDir specified
  99286. options.sourceRoot || // there is --sourceRoot specified
  99287. options.mapRoot) { // there is --mapRoot specified
  99288. // Precalculate and cache the common source directory
  99289. var dir = getCommonSourceDirectory();
  99290. // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
  99291. if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
  99292. createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
  99293. }
  99294. }
  99295. if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
  99296. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
  99297. }
  99298. if (options.checkJs && !options.allowJs) {
  99299. programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
  99300. }
  99301. if (options.emitDeclarationOnly) {
  99302. if (!ts.getEmitDeclarations(options)) {
  99303. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
  99304. }
  99305. if (options.noEmit) {
  99306. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
  99307. }
  99308. }
  99309. if (options.emitDecoratorMetadata &&
  99310. !options.experimentalDecorators) {
  99311. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
  99312. }
  99313. if (options.jsxFactory) {
  99314. if (options.reactNamespace) {
  99315. createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
  99316. }
  99317. if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
  99318. createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
  99319. }
  99320. }
  99321. else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
  99322. createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
  99323. }
  99324. // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
  99325. if (!options.noEmit && !options.suppressOutputPathCheck) {
  99326. var emitHost = getEmitHost();
  99327. var emitFilesSeen_1 = ts.createMap();
  99328. ts.forEachEmittedFile(emitHost, function (emitFileNames) {
  99329. if (!options.emitDeclarationOnly) {
  99330. verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
  99331. }
  99332. verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
  99333. });
  99334. }
  99335. // Verify that all the emit files are unique and don't overwrite input files
  99336. function verifyEmitFilePath(emitFileName, emitFilesSeen) {
  99337. if (emitFileName) {
  99338. var emitFilePath = toPath(emitFileName);
  99339. // Report error if the output overwrites input file
  99340. if (filesByName.has(emitFilePath)) {
  99341. var chain = void 0;
  99342. if (!options.configFilePath) {
  99343. // The program is from either an inferred project or an external project
  99344. chain = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig);
  99345. }
  99346. chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
  99347. blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
  99348. }
  99349. var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
  99350. // Report error if multiple files write into same file
  99351. if (emitFilesSeen.has(emitFileKey)) {
  99352. // Already seen the same emit file - report error
  99353. blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
  99354. }
  99355. else {
  99356. emitFilesSeen.set(emitFileKey, true);
  99357. }
  99358. }
  99359. }
  99360. }
  99361. function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
  99362. var _a, _b;
  99363. var args = [];
  99364. for (var _i = 2; _i < arguments.length; _i++) {
  99365. args[_i - 2] = arguments[_i];
  99366. }
  99367. var refFile = ts.Debug.assertDefined(getSourceFileByPath(refPathToReportErrorOn.file));
  99368. var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
  99369. var pos, end;
  99370. switch (kind) {
  99371. case ts.RefFileKind.Import:
  99372. pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
  99373. end = refFile.imports[index].end;
  99374. break;
  99375. case ts.RefFileKind.ReferenceFile:
  99376. (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
  99377. break;
  99378. case ts.RefFileKind.TypeReferenceDirective:
  99379. (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
  99380. break;
  99381. default:
  99382. return ts.Debug.assertNever(kind);
  99383. }
  99384. return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
  99385. }
  99386. function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
  99387. var args = [];
  99388. for (var _i = 3; _i < arguments.length; _i++) {
  99389. args[_i - 3] = arguments[_i];
  99390. }
  99391. var refPaths = refFileMap && refFileMap.get(file.path);
  99392. var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
  99393. ts.elementAt(refPaths, 0);
  99394. programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
  99395. }
  99396. function verifyProjectReferences() {
  99397. var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
  99398. forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
  99399. var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
  99400. var parentFile = parent && parent.sourceFile;
  99401. if (!resolvedRef) {
  99402. createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
  99403. return;
  99404. }
  99405. var options = resolvedRef.commandLine.options;
  99406. if (!options.composite) {
  99407. // ok to not have composite if the current program is container only
  99408. var inputs = parent ? parent.commandLine.fileNames : rootNames;
  99409. if (inputs.length) {
  99410. createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
  99411. }
  99412. }
  99413. if (ref.prepend) {
  99414. var out = options.outFile || options.out;
  99415. if (out) {
  99416. if (!host.fileExists(out)) {
  99417. createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
  99418. }
  99419. }
  99420. else {
  99421. createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
  99422. }
  99423. }
  99424. if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
  99425. createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
  99426. hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
  99427. }
  99428. });
  99429. }
  99430. function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
  99431. var needCompilerDiagnostic = true;
  99432. var pathsSyntax = getOptionPathsSyntax();
  99433. for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
  99434. var pathProp = pathsSyntax_1[_i];
  99435. if (ts.isObjectLiteralExpression(pathProp.initializer)) {
  99436. for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
  99437. var keyProps = _b[_a];
  99438. var initializer = keyProps.initializer;
  99439. if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
  99440. programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
  99441. needCompilerDiagnostic = false;
  99442. }
  99443. }
  99444. }
  99445. }
  99446. if (needCompilerDiagnostic) {
  99447. programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
  99448. }
  99449. }
  99450. function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
  99451. var needCompilerDiagnostic = true;
  99452. var pathsSyntax = getOptionPathsSyntax();
  99453. for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
  99454. var pathProp = pathsSyntax_2[_i];
  99455. if (ts.isObjectLiteralExpression(pathProp.initializer) &&
  99456. createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
  99457. needCompilerDiagnostic = false;
  99458. }
  99459. }
  99460. if (needCompilerDiagnostic) {
  99461. programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
  99462. }
  99463. }
  99464. function getOptionsSyntaxByName(name) {
  99465. var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
  99466. if (compilerOptionsObjectLiteralSyntax) {
  99467. return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
  99468. }
  99469. return undefined;
  99470. }
  99471. function getOptionPathsSyntax() {
  99472. return getOptionsSyntaxByName("paths") || ts.emptyArray;
  99473. }
  99474. function createDiagnosticForOptionName(message, option1, option2, option3) {
  99475. createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
  99476. }
  99477. function createOptionValueDiagnostic(option1, message, arg0) {
  99478. createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
  99479. }
  99480. function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
  99481. var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
  99482. if (referencesSyntax && referencesSyntax.elements.length > index) {
  99483. programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
  99484. }
  99485. else {
  99486. programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
  99487. }
  99488. }
  99489. function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
  99490. var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
  99491. var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
  99492. !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
  99493. if (needCompilerDiagnostic) {
  99494. programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
  99495. }
  99496. }
  99497. function getCompilerOptionsObjectLiteralSyntax() {
  99498. if (_compilerOptionsObjectLiteralSyntax === undefined) {
  99499. _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
  99500. var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
  99501. if (jsonObjectLiteral) {
  99502. for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
  99503. var prop = _a[_i];
  99504. if (ts.isObjectLiteralExpression(prop.initializer)) {
  99505. _compilerOptionsObjectLiteralSyntax = prop.initializer;
  99506. break;
  99507. }
  99508. }
  99509. }
  99510. }
  99511. return _compilerOptionsObjectLiteralSyntax;
  99512. }
  99513. function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
  99514. var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
  99515. for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
  99516. var prop = props_3[_i];
  99517. programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
  99518. }
  99519. return !!props.length;
  99520. }
  99521. function blockEmittingOfFile(emitFileName, diag) {
  99522. hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
  99523. programDiagnostics.add(diag);
  99524. }
  99525. function isEmittedFile(file) {
  99526. if (options.noEmit) {
  99527. return false;
  99528. }
  99529. // If this is source file, its not emitted file
  99530. var filePath = toPath(file);
  99531. if (getSourceFileByPath(filePath)) {
  99532. return false;
  99533. }
  99534. // If options have --outFile or --out just check that
  99535. var out = options.outFile || options.out;
  99536. if (out) {
  99537. return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
  99538. }
  99539. // If declarationDir is specified, return if its a file in that directory
  99540. if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
  99541. return true;
  99542. }
  99543. // If --outDir, check if file is in that directory
  99544. if (options.outDir) {
  99545. return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
  99546. }
  99547. if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
  99548. // Otherwise just check if sourceFile with the name exists
  99549. var filePathWithoutExtension = ts.removeFileExtension(filePath);
  99550. return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
  99551. !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
  99552. }
  99553. return false;
  99554. }
  99555. function isSameFile(file1, file2) {
  99556. return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
  99557. }
  99558. function getProbableSymlinks() {
  99559. if (host.getSymlinks) {
  99560. return host.getSymlinks();
  99561. }
  99562. return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
  99563. }
  99564. }
  99565. ts.createProgram = createProgram;
  99566. /*@internal*/
  99567. function handleNoEmitOptions(program, sourceFile, cancellationToken) {
  99568. var options = program.getCompilerOptions();
  99569. if (options.noEmit) {
  99570. return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
  99571. }
  99572. // If the noEmitOnError flag is set, then check if we have any errors so far. If so,
  99573. // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
  99574. // get any preEmit diagnostics, not just the ones
  99575. if (!options.noEmitOnError)
  99576. return undefined;
  99577. var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
  99578. if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
  99579. diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
  99580. }
  99581. return diagnostics.length > 0 ?
  99582. { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
  99583. undefined;
  99584. }
  99585. ts.handleNoEmitOptions = handleNoEmitOptions;
  99586. /* @internal */
  99587. function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
  99588. if (directoryStructureHost === void 0) { directoryStructureHost = host; }
  99589. return {
  99590. fileExists: function (f) { return directoryStructureHost.fileExists(f); },
  99591. readDirectory: function (root, extensions, excludes, includes, depth) {
  99592. ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
  99593. return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
  99594. },
  99595. readFile: function (f) { return directoryStructureHost.readFile(f); },
  99596. useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
  99597. getCurrentDirectory: function () { return host.getCurrentDirectory(); },
  99598. onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
  99599. trace: host.trace ? function (s) { return host.trace(s); } : undefined
  99600. };
  99601. }
  99602. ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
  99603. /* @internal */
  99604. function createPrependNodes(projectReferences, getCommandLine, readFile) {
  99605. if (!projectReferences)
  99606. return ts.emptyArray;
  99607. var nodes;
  99608. for (var i = 0; i < projectReferences.length; i++) {
  99609. var ref = projectReferences[i];
  99610. var resolvedRefOpts = getCommandLine(ref, i);
  99611. if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
  99612. var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
  99613. // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
  99614. if (!out)
  99615. continue;
  99616. var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
  99617. var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
  99618. (nodes || (nodes = [])).push(node);
  99619. }
  99620. }
  99621. return nodes || ts.emptyArray;
  99622. }
  99623. ts.createPrependNodes = createPrependNodes;
  99624. function resolveProjectReferencePath(hostOrRef, ref) {
  99625. var passedInRef = ref ? ref : hostOrRef;
  99626. return ts.resolveConfigFileProjectName(passedInRef.path);
  99627. }
  99628. ts.resolveProjectReferencePath = resolveProjectReferencePath;
  99629. /* @internal */
  99630. /**
  99631. * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
  99632. * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
  99633. * This returns a diagnostic even if the module will be an untyped module.
  99634. */
  99635. function getResolutionDiagnostic(options, _a) {
  99636. var extension = _a.extension;
  99637. switch (extension) {
  99638. case ".ts" /* Ts */:
  99639. case ".d.ts" /* Dts */:
  99640. // These are always allowed.
  99641. return undefined;
  99642. case ".tsx" /* Tsx */:
  99643. return needJsx();
  99644. case ".jsx" /* Jsx */:
  99645. return needJsx() || needAllowJs();
  99646. case ".js" /* Js */:
  99647. return needAllowJs();
  99648. case ".json" /* Json */:
  99649. return needResolveJsonModule();
  99650. }
  99651. function needJsx() {
  99652. return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
  99653. }
  99654. function needAllowJs() {
  99655. return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
  99656. }
  99657. function needResolveJsonModule() {
  99658. return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
  99659. }
  99660. }
  99661. ts.getResolutionDiagnostic = getResolutionDiagnostic;
  99662. function getModuleNames(_a) {
  99663. var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
  99664. var res = imports.map(function (i) { return i.text; });
  99665. for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
  99666. var aug = moduleAugmentations_1[_i];
  99667. if (aug.kind === 10 /* StringLiteral */) {
  99668. res.push(aug.text);
  99669. }
  99670. // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
  99671. }
  99672. return res;
  99673. }
  99674. })(ts || (ts = {}));
  99675. /*@internal*/
  99676. var ts;
  99677. (function (ts) {
  99678. function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
  99679. var outputFiles = [];
  99680. var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit);
  99681. return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit };
  99682. function writeFile(fileName, text, writeByteOrderMark) {
  99683. outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
  99684. }
  99685. }
  99686. ts.getFileEmitOutput = getFileEmitOutput;
  99687. var BuilderState;
  99688. (function (BuilderState) {
  99689. /**
  99690. * Get the referencedFile from the imported module symbol
  99691. */
  99692. function getReferencedFileFromImportedModuleSymbol(symbol) {
  99693. if (symbol.declarations && symbol.declarations[0]) {
  99694. var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
  99695. return declarationSourceFile && declarationSourceFile.resolvedPath;
  99696. }
  99697. }
  99698. /**
  99699. * Get the referencedFile from the import name node from file
  99700. */
  99701. function getReferencedFileFromImportLiteral(checker, importName) {
  99702. var symbol = checker.getSymbolAtLocation(importName);
  99703. return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
  99704. }
  99705. /**
  99706. * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
  99707. */
  99708. function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
  99709. return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
  99710. }
  99711. /**
  99712. * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
  99713. */
  99714. function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
  99715. var referencedFiles;
  99716. // We need to use a set here since the code can contain the same import twice,
  99717. // but that will only be one dependency.
  99718. // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
  99719. if (sourceFile.imports && sourceFile.imports.length > 0) {
  99720. var checker = program.getTypeChecker();
  99721. for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
  99722. var importName = _a[_i];
  99723. var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
  99724. if (declarationSourceFilePath) {
  99725. addReferencedFile(declarationSourceFilePath);
  99726. }
  99727. }
  99728. }
  99729. var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
  99730. // Handle triple slash references
  99731. if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
  99732. for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
  99733. var referencedFile = _c[_b];
  99734. var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
  99735. addReferencedFile(referencedPath);
  99736. }
  99737. }
  99738. // Handle type reference directives
  99739. if (sourceFile.resolvedTypeReferenceDirectiveNames) {
  99740. sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
  99741. if (!resolvedTypeReferenceDirective) {
  99742. return;
  99743. }
  99744. var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
  99745. var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
  99746. addReferencedFile(typeFilePath);
  99747. });
  99748. }
  99749. // Add module augmentation as references
  99750. if (sourceFile.moduleAugmentations.length) {
  99751. var checker = program.getTypeChecker();
  99752. for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
  99753. var moduleName = _e[_d];
  99754. if (!ts.isStringLiteral(moduleName)) {
  99755. continue;
  99756. }
  99757. var symbol = checker.getSymbolAtLocation(moduleName);
  99758. if (!symbol) {
  99759. continue;
  99760. }
  99761. // Add any file other than our own as reference
  99762. addReferenceFromAmbientModule(symbol);
  99763. }
  99764. }
  99765. // From ambient modules
  99766. for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
  99767. var ambientModule = _g[_f];
  99768. if (ambientModule.declarations.length > 1) {
  99769. addReferenceFromAmbientModule(ambientModule);
  99770. }
  99771. }
  99772. return referencedFiles;
  99773. function addReferenceFromAmbientModule(symbol) {
  99774. // Add any file other than our own as reference
  99775. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  99776. var declaration = _a[_i];
  99777. var declarationSourceFile = ts.getSourceFileOfNode(declaration);
  99778. if (declarationSourceFile &&
  99779. declarationSourceFile !== sourceFile) {
  99780. addReferencedFile(declarationSourceFile.resolvedPath);
  99781. }
  99782. }
  99783. }
  99784. function addReferencedFile(referencedPath) {
  99785. if (!referencedFiles) {
  99786. referencedFiles = ts.createMap();
  99787. }
  99788. referencedFiles.set(referencedPath, true);
  99789. }
  99790. }
  99791. /**
  99792. * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
  99793. */
  99794. function canReuseOldState(newReferencedMap, oldState) {
  99795. return oldState && !oldState.referencedMap === !newReferencedMap;
  99796. }
  99797. BuilderState.canReuseOldState = canReuseOldState;
  99798. /**
  99799. * Creates the state of file references and signature for the new program from oldState if it is safe
  99800. */
  99801. function create(newProgram, getCanonicalFileName, oldState) {
  99802. var fileInfos = ts.createMap();
  99803. var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
  99804. var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
  99805. var hasCalledUpdateShapeSignature = ts.createMap();
  99806. var useOldState = canReuseOldState(referencedMap, oldState);
  99807. // Create the reference map, and set the file infos
  99808. for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
  99809. var sourceFile = _a[_i];
  99810. var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
  99811. var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
  99812. if (referencedMap) {
  99813. var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
  99814. if (newReferences) {
  99815. referencedMap.set(sourceFile.resolvedPath, newReferences);
  99816. }
  99817. // Copy old visible to outside files map
  99818. if (useOldState) {
  99819. var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
  99820. if (exportedModules) {
  99821. exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
  99822. }
  99823. }
  99824. }
  99825. fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature });
  99826. }
  99827. return {
  99828. fileInfos: fileInfos,
  99829. referencedMap: referencedMap,
  99830. exportedModulesMap: exportedModulesMap,
  99831. hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
  99832. };
  99833. }
  99834. BuilderState.create = create;
  99835. /**
  99836. * Releases needed properties
  99837. */
  99838. function releaseCache(state) {
  99839. state.allFilesExcludingDefaultLibraryFile = undefined;
  99840. state.allFileNames = undefined;
  99841. }
  99842. BuilderState.releaseCache = releaseCache;
  99843. /**
  99844. * Creates a clone of the state
  99845. */
  99846. function clone(state) {
  99847. var fileInfos = ts.createMap();
  99848. state.fileInfos.forEach(function (value, key) {
  99849. fileInfos.set(key, __assign({}, value));
  99850. });
  99851. // Dont need to backup allFiles info since its cache anyway
  99852. return {
  99853. fileInfos: fileInfos,
  99854. referencedMap: cloneMapOrUndefined(state.referencedMap),
  99855. exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
  99856. hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
  99857. };
  99858. }
  99859. BuilderState.clone = clone;
  99860. /**
  99861. * Gets the files affected by the path from the program
  99862. */
  99863. function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
  99864. // Since the operation could be cancelled, the signatures are always stored in the cache
  99865. // They will be committed once it is safe to use them
  99866. // eg when calling this api from tsserver, if there is no cancellation of the operation
  99867. // In the other cases the affected files signatures are committed only after the iteration through the result is complete
  99868. var signatureCache = cacheToUpdateSignature || ts.createMap();
  99869. var sourceFile = programOfThisState.getSourceFileByPath(path);
  99870. if (!sourceFile) {
  99871. return ts.emptyArray;
  99872. }
  99873. if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
  99874. return [sourceFile];
  99875. }
  99876. var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
  99877. if (!cacheToUpdateSignature) {
  99878. // Commit all the signatures in the signature cache
  99879. updateSignaturesFromCache(state, signatureCache);
  99880. }
  99881. return result;
  99882. }
  99883. BuilderState.getFilesAffectedBy = getFilesAffectedBy;
  99884. /**
  99885. * Updates the signatures from the cache into state's fileinfo signatures
  99886. * This should be called whenever it is safe to commit the state of the builder
  99887. */
  99888. function updateSignaturesFromCache(state, signatureCache) {
  99889. signatureCache.forEach(function (signature, path) {
  99890. state.fileInfos.get(path).signature = signature;
  99891. state.hasCalledUpdateShapeSignature.set(path, true);
  99892. });
  99893. }
  99894. BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
  99895. /**
  99896. * Returns if the shape of the signature has changed since last emit
  99897. */
  99898. function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
  99899. ts.Debug.assert(!!sourceFile);
  99900. ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
  99901. // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
  99902. if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
  99903. return false;
  99904. }
  99905. var info = state.fileInfos.get(sourceFile.resolvedPath);
  99906. if (!info)
  99907. return ts.Debug.fail();
  99908. var prevSignature = info.signature;
  99909. var latestSignature;
  99910. if (sourceFile.isDeclarationFile) {
  99911. latestSignature = sourceFile.version;
  99912. if (exportedModulesMapCache && latestSignature !== prevSignature) {
  99913. // All the references in this file are exported
  99914. var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
  99915. exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
  99916. }
  99917. }
  99918. else {
  99919. var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile,
  99920. /*emitOnlyDtsFiles*/ true, cancellationToken,
  99921. /*customTransformers*/ undefined,
  99922. /*forceDtsEmit*/ true);
  99923. var firstDts_1 = emitOutput_1.outputFiles &&
  99924. programOfThisState.getCompilerOptions().declarationMap ?
  99925. emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
  99926. emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
  99927. if (firstDts_1) {
  99928. ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); });
  99929. latestSignature = computeHash(firstDts_1.text);
  99930. if (exportedModulesMapCache && latestSignature !== prevSignature) {
  99931. updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
  99932. }
  99933. }
  99934. else {
  99935. latestSignature = prevSignature; // TODO: GH#18217
  99936. }
  99937. }
  99938. cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
  99939. return !prevSignature || latestSignature !== prevSignature;
  99940. }
  99941. BuilderState.updateShapeSignature = updateShapeSignature;
  99942. /**
  99943. * Coverts the declaration emit result into exported modules map
  99944. */
  99945. function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
  99946. if (!exportedModulesFromDeclarationEmit) {
  99947. exportedModulesMapCache.set(sourceFile.resolvedPath, false);
  99948. return;
  99949. }
  99950. var exportedModules;
  99951. exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
  99952. exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
  99953. function addExportedModule(exportedModulePath) {
  99954. if (exportedModulePath) {
  99955. if (!exportedModules) {
  99956. exportedModules = ts.createMap();
  99957. }
  99958. exportedModules.set(exportedModulePath, true);
  99959. }
  99960. }
  99961. }
  99962. /**
  99963. * Updates the exported modules from cache into state's exported modules map
  99964. * This should be called whenever it is safe to commit the state of the builder
  99965. */
  99966. function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
  99967. if (exportedModulesMapCache) {
  99968. ts.Debug.assert(!!state.exportedModulesMap);
  99969. exportedModulesMapCache.forEach(function (exportedModules, path) {
  99970. if (exportedModules) {
  99971. state.exportedModulesMap.set(path, exportedModules);
  99972. }
  99973. else {
  99974. state.exportedModulesMap.delete(path);
  99975. }
  99976. });
  99977. }
  99978. }
  99979. BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
  99980. /**
  99981. * Get all the dependencies of the sourceFile
  99982. */
  99983. function getAllDependencies(state, programOfThisState, sourceFile) {
  99984. var compilerOptions = programOfThisState.getCompilerOptions();
  99985. // With --out or --outFile all outputs go into single file, all files depend on each other
  99986. if (compilerOptions.outFile || compilerOptions.out) {
  99987. return getAllFileNames(state, programOfThisState);
  99988. }
  99989. // If this is non module emit, or its a global file, it depends on all the source files
  99990. if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
  99991. return getAllFileNames(state, programOfThisState);
  99992. }
  99993. // Get the references, traversing deep from the referenceMap
  99994. var seenMap = ts.createMap();
  99995. var queue = [sourceFile.resolvedPath];
  99996. while (queue.length) {
  99997. var path = queue.pop();
  99998. if (!seenMap.has(path)) {
  99999. seenMap.set(path, true);
  100000. var references = state.referencedMap.get(path);
  100001. if (references) {
  100002. var iterator = references.keys();
  100003. for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
  100004. queue.push(iterResult.value);
  100005. }
  100006. }
  100007. }
  100008. }
  100009. return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
  100010. var file = programOfThisState.getSourceFileByPath(path);
  100011. return file ? file.fileName : path;
  100012. }));
  100013. }
  100014. BuilderState.getAllDependencies = getAllDependencies;
  100015. /**
  100016. * Gets the names of all files from the program
  100017. */
  100018. function getAllFileNames(state, programOfThisState) {
  100019. if (!state.allFileNames) {
  100020. var sourceFiles = programOfThisState.getSourceFiles();
  100021. state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
  100022. }
  100023. return state.allFileNames;
  100024. }
  100025. /**
  100026. * Gets the files referenced by the the file path
  100027. */
  100028. function getReferencedByPaths(state, referencedFilePath) {
  100029. return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
  100030. var filePath = _a[0], referencesInFile = _a[1];
  100031. return referencesInFile.has(referencedFilePath) ? filePath : undefined;
  100032. }));
  100033. }
  100034. BuilderState.getReferencedByPaths = getReferencedByPaths;
  100035. /**
  100036. * For script files that contains only ambient external modules, although they are not actually external module files,
  100037. * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
  100038. * there are no point to rebuild all script files if these special files have changed. However, if any statement
  100039. * in the file is not ambient external module, we treat it as a regular script file.
  100040. */
  100041. function containsOnlyAmbientModules(sourceFile) {
  100042. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  100043. var statement = _a[_i];
  100044. if (!ts.isModuleWithStringLiteralName(statement)) {
  100045. return false;
  100046. }
  100047. }
  100048. return true;
  100049. }
  100050. /**
  100051. * Return true if file contains anything that augments to global scope we need to build them as if
  100052. * they are global files as well as module
  100053. */
  100054. function containsGlobalScopeAugmentation(sourceFile) {
  100055. return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
  100056. }
  100057. /**
  100058. * Return true if the file will invalidate all files because it affectes global scope
  100059. */
  100060. function isFileAffectingGlobalScope(sourceFile) {
  100061. return containsGlobalScopeAugmentation(sourceFile) ||
  100062. !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
  100063. }
  100064. /**
  100065. * Gets all files of the program excluding the default library file
  100066. */
  100067. function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
  100068. // Use cached result
  100069. if (state.allFilesExcludingDefaultLibraryFile) {
  100070. return state.allFilesExcludingDefaultLibraryFile;
  100071. }
  100072. var result;
  100073. addSourceFile(firstSourceFile);
  100074. for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
  100075. var sourceFile = _a[_i];
  100076. if (sourceFile !== firstSourceFile) {
  100077. addSourceFile(sourceFile);
  100078. }
  100079. }
  100080. state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
  100081. return state.allFilesExcludingDefaultLibraryFile;
  100082. function addSourceFile(sourceFile) {
  100083. if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
  100084. (result || (result = [])).push(sourceFile);
  100085. }
  100086. }
  100087. }
  100088. /**
  100089. * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
  100090. */
  100091. function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
  100092. var compilerOptions = programOfThisState.getCompilerOptions();
  100093. // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
  100094. // so returning the file itself is good enough.
  100095. if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
  100096. return [sourceFileWithUpdatedShape];
  100097. }
  100098. return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
  100099. }
  100100. /**
  100101. * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
  100102. */
  100103. function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
  100104. if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
  100105. return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
  100106. }
  100107. var compilerOptions = programOfThisState.getCompilerOptions();
  100108. if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
  100109. return [sourceFileWithUpdatedShape];
  100110. }
  100111. // Now we need to if each file in the referencedBy list has a shape change as well.
  100112. // Because if so, its own referencedBy files need to be saved as well to make the
  100113. // emitting result consistent with files on disk.
  100114. var seenFileNamesMap = ts.createMap();
  100115. // Start with the paths this file was referenced by
  100116. seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
  100117. var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
  100118. while (queue.length > 0) {
  100119. var currentPath = queue.pop();
  100120. if (!seenFileNamesMap.has(currentPath)) {
  100121. var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
  100122. seenFileNamesMap.set(currentPath, currentSourceFile);
  100123. if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
  100124. queue.push.apply(// TODO: GH#18217
  100125. queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
  100126. }
  100127. }
  100128. }
  100129. // Return array of values that needs emit
  100130. // Return array of values that needs emit
  100131. return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
  100132. }
  100133. })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
  100134. function cloneMapOrUndefined(map) {
  100135. return map ? ts.cloneMap(map) : undefined;
  100136. }
  100137. ts.cloneMapOrUndefined = cloneMapOrUndefined;
  100138. })(ts || (ts = {}));
  100139. /*@internal*/
  100140. var ts;
  100141. (function (ts) {
  100142. var BuilderFileEmit;
  100143. (function (BuilderFileEmit) {
  100144. BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
  100145. BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
  100146. })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
  100147. function hasSameKeys(map1, map2) {
  100148. // Has same size and every key is present in both maps
  100149. return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
  100150. }
  100151. /**
  100152. * Create the state so that we can iterate on changedFiles/affected files
  100153. */
  100154. function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
  100155. var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
  100156. state.program = newProgram;
  100157. var compilerOptions = newProgram.getCompilerOptions();
  100158. state.compilerOptions = compilerOptions;
  100159. // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
  100160. if (!compilerOptions.outFile && !compilerOptions.out) {
  100161. state.semanticDiagnosticsPerFile = ts.createMap();
  100162. }
  100163. state.changedFilesSet = ts.createMap();
  100164. var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
  100165. var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
  100166. var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
  100167. !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
  100168. if (useOldState) {
  100169. // Verify the sanity of old state
  100170. if (!oldState.currentChangedFilePath) {
  100171. var affectedSignatures = oldState.currentAffectedFilesSignatures;
  100172. ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
  100173. }
  100174. var changedFilesSet = oldState.changedFilesSet;
  100175. if (canCopySemanticDiagnostics) {
  100176. ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
  100177. }
  100178. // Copy old state's changed files set
  100179. if (changedFilesSet) {
  100180. ts.copyEntries(changedFilesSet, state.changedFilesSet);
  100181. }
  100182. if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
  100183. state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
  100184. state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
  100185. state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
  100186. }
  100187. }
  100188. // Update changed files and copy semantic diagnostics if we can
  100189. var referencedMap = state.referencedMap;
  100190. var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
  100191. var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
  100192. var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
  100193. state.fileInfos.forEach(function (info, sourceFilePath) {
  100194. var oldInfo;
  100195. var newReferences;
  100196. // if not using old state, every file is changed
  100197. if (!useOldState ||
  100198. // File wasnt present in old state
  100199. !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
  100200. // versions dont match
  100201. oldInfo.version !== info.version ||
  100202. // Referenced files changed
  100203. !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
  100204. // Referenced file was deleted in the new program
  100205. newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
  100206. // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
  100207. state.changedFilesSet.set(sourceFilePath, true);
  100208. }
  100209. else if (canCopySemanticDiagnostics) {
  100210. var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
  100211. if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
  100212. return;
  100213. }
  100214. if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
  100215. return;
  100216. }
  100217. // Unchanged file copy diagnostics
  100218. var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
  100219. if (diagnostics) {
  100220. state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
  100221. if (!state.semanticDiagnosticsFromOldState) {
  100222. state.semanticDiagnosticsFromOldState = ts.createMap();
  100223. }
  100224. state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
  100225. }
  100226. }
  100227. });
  100228. if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
  100229. // Add all files to affectedFilesPendingEmit since emit changed
  100230. newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
  100231. ts.Debug.assert(state.seenAffectedFiles === undefined);
  100232. state.seenAffectedFiles = ts.createMap();
  100233. }
  100234. state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
  100235. return state;
  100236. }
  100237. function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
  100238. if (!diagnostics.length)
  100239. return ts.emptyArray;
  100240. var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
  100241. return diagnostics.map(function (diagnostic) {
  100242. var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
  100243. result.reportsUnnecessary = diagnostic.reportsUnnecessary;
  100244. result.source = diagnostic.source;
  100245. var relatedInformation = diagnostic.relatedInformation;
  100246. result.relatedInformation = relatedInformation ?
  100247. relatedInformation.length ?
  100248. relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
  100249. ts.emptyArray :
  100250. undefined;
  100251. return result;
  100252. });
  100253. function toPath(path) {
  100254. return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
  100255. }
  100256. }
  100257. function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
  100258. var file = diagnostic.file;
  100259. return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
  100260. }
  100261. /**
  100262. * Releases program and other related not needed properties
  100263. */
  100264. function releaseCache(state) {
  100265. ts.BuilderState.releaseCache(state);
  100266. state.program = undefined;
  100267. }
  100268. /**
  100269. * Creates a clone of the state
  100270. */
  100271. function cloneBuilderProgramState(state) {
  100272. var newState = ts.BuilderState.clone(state);
  100273. newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
  100274. newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
  100275. newState.affectedFiles = state.affectedFiles;
  100276. newState.affectedFilesIndex = state.affectedFilesIndex;
  100277. newState.currentChangedFilePath = state.currentChangedFilePath;
  100278. newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
  100279. newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
  100280. newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
  100281. newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
  100282. newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
  100283. newState.program = state.program;
  100284. newState.compilerOptions = state.compilerOptions;
  100285. newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
  100286. newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
  100287. newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
  100288. newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
  100289. newState.programEmitComplete = state.programEmitComplete;
  100290. return newState;
  100291. }
  100292. /**
  100293. * Verifies that source file is ok to be used in calls that arent handled by next
  100294. */
  100295. function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
  100296. ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
  100297. }
  100298. /**
  100299. * This function returns the next affected file to be processed.
  100300. * Note that until doneAffected is called it would keep reporting same result
  100301. * This is to allow the callers to be able to actually remove affected file only when the operation is complete
  100302. * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
  100303. */
  100304. function getNextAffectedFile(state, cancellationToken, computeHash) {
  100305. while (true) {
  100306. var affectedFiles = state.affectedFiles;
  100307. if (affectedFiles) {
  100308. var seenAffectedFiles = state.seenAffectedFiles;
  100309. var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
  100310. while (affectedFilesIndex < affectedFiles.length) {
  100311. var affectedFile = affectedFiles[affectedFilesIndex];
  100312. if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
  100313. // Set the next affected file as seen and remove the cached semantic diagnostics
  100314. state.affectedFilesIndex = affectedFilesIndex;
  100315. handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
  100316. return affectedFile;
  100317. }
  100318. affectedFilesIndex++;
  100319. }
  100320. // Remove the changed file from the change set
  100321. state.changedFilesSet.delete(state.currentChangedFilePath);
  100322. state.currentChangedFilePath = undefined;
  100323. // Commit the changes in file signature
  100324. ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
  100325. state.currentAffectedFilesSignatures.clear();
  100326. ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
  100327. state.affectedFiles = undefined;
  100328. }
  100329. // Get next changed file
  100330. var nextKey = state.changedFilesSet.keys().next();
  100331. if (nextKey.done) {
  100332. // Done
  100333. return undefined;
  100334. }
  100335. // With --out or --outFile all outputs go into single file
  100336. // so operations are performed directly on program, return program
  100337. var program = ts.Debug.assertDefined(state.program);
  100338. var compilerOptions = program.getCompilerOptions();
  100339. if (compilerOptions.outFile || compilerOptions.out) {
  100340. ts.Debug.assert(!state.semanticDiagnosticsPerFile);
  100341. return program;
  100342. }
  100343. // Get next batch of affected files
  100344. state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
  100345. if (state.exportedModulesMap) {
  100346. state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
  100347. }
  100348. state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
  100349. state.currentChangedFilePath = nextKey.value;
  100350. state.affectedFilesIndex = 0;
  100351. state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
  100352. }
  100353. }
  100354. /**
  100355. * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
  100356. */
  100357. function getNextAffectedFilePendingEmit(state) {
  100358. var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
  100359. if (affectedFilesPendingEmit) {
  100360. var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
  100361. for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
  100362. var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
  100363. if (affectedFile) {
  100364. var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
  100365. var emitKind = ts.Debug.assertDefined(ts.Debug.assertDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
  100366. if (seenKind === undefined || seenKind < emitKind) {
  100367. // emit this file
  100368. state.affectedFilesPendingEmitIndex = i;
  100369. return { affectedFile: affectedFile, emitKind: emitKind };
  100370. }
  100371. }
  100372. }
  100373. state.affectedFilesPendingEmit = undefined;
  100374. state.affectedFilesPendingEmitKind = undefined;
  100375. state.affectedFilesPendingEmitIndex = undefined;
  100376. }
  100377. return undefined;
  100378. }
  100379. /**
  100380. * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
  100381. * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
  100382. */
  100383. function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
  100384. removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
  100385. // If affected files is everything except default library, then nothing more to do
  100386. if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
  100387. if (!state.cleanedDiagnosticsOfLibFiles) {
  100388. state.cleanedDiagnosticsOfLibFiles = true;
  100389. var program_1 = ts.Debug.assertDefined(state.program);
  100390. var options_2 = program_1.getCompilerOptions();
  100391. ts.forEach(program_1.getSourceFiles(), function (f) {
  100392. return program_1.isSourceFileDefaultLibrary(f) &&
  100393. !ts.skipTypeChecking(f, options_2, program_1) &&
  100394. removeSemanticDiagnosticsOf(state, f.resolvedPath);
  100395. });
  100396. }
  100397. return;
  100398. }
  100399. if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
  100400. forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
  100401. }
  100402. }
  100403. /**
  100404. * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
  100405. * Also we need to make sure signature is updated for these files
  100406. */
  100407. function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
  100408. removeSemanticDiagnosticsOf(state, path);
  100409. if (!state.changedFilesSet.has(path)) {
  100410. var program = ts.Debug.assertDefined(state.program);
  100411. var sourceFile = program.getSourceFileByPath(path);
  100412. if (sourceFile) {
  100413. // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
  100414. // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
  100415. // This ensures that we dont later during incremental builds considering wrong signature.
  100416. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
  100417. ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.assertDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
  100418. // If not dts emit, nothing more to do
  100419. if (ts.getEmitDeclarations(state.compilerOptions)) {
  100420. addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
  100421. }
  100422. }
  100423. }
  100424. return false;
  100425. }
  100426. /**
  100427. * Removes semantic diagnostics for path and
  100428. * returns true if there are no more semantic diagnostics from the old state
  100429. */
  100430. function removeSemanticDiagnosticsOf(state, path) {
  100431. if (!state.semanticDiagnosticsFromOldState) {
  100432. return true;
  100433. }
  100434. state.semanticDiagnosticsFromOldState.delete(path);
  100435. state.semanticDiagnosticsPerFile.delete(path);
  100436. return !state.semanticDiagnosticsFromOldState.size;
  100437. }
  100438. function isChangedSignagure(state, path) {
  100439. var newSignature = ts.Debug.assertDefined(state.currentAffectedFilesSignatures).get(path);
  100440. var oldSignagure = ts.Debug.assertDefined(state.fileInfos.get(path)).signature;
  100441. return newSignature !== oldSignagure;
  100442. }
  100443. /**
  100444. * Iterate on referencing modules that export entities from affected file
  100445. */
  100446. function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
  100447. // If there was change in signature (dts output) for the changed file,
  100448. // then only we need to handle pending file emit
  100449. if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
  100450. return;
  100451. }
  100452. if (!isChangedSignagure(state, affectedFile.resolvedPath))
  100453. return;
  100454. // Since isolated modules dont change js files, files affected by change in signature is itself
  100455. // But we need to cleanup semantic diagnostics and queue dts emit for affected files
  100456. if (state.compilerOptions.isolatedModules) {
  100457. var seenFileNamesMap = ts.createMap();
  100458. seenFileNamesMap.set(affectedFile.resolvedPath, true);
  100459. var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
  100460. while (queue.length > 0) {
  100461. var currentPath = queue.pop();
  100462. if (!seenFileNamesMap.has(currentPath)) {
  100463. seenFileNamesMap.set(currentPath, true);
  100464. var result = fn(state, currentPath);
  100465. if (result && isChangedSignagure(state, currentPath)) {
  100466. var currentSourceFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(currentPath);
  100467. queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
  100468. }
  100469. }
  100470. }
  100471. }
  100472. ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
  100473. var seenFileAndExportsOfFile = ts.createMap();
  100474. // Go through exported modules from cache first
  100475. // If exported modules has path, all files referencing file exported from are affected
  100476. if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
  100477. return exportedModules &&
  100478. exportedModules.has(affectedFile.resolvedPath) &&
  100479. forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
  100480. })) {
  100481. return;
  100482. }
  100483. // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
  100484. ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
  100485. return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
  100486. exportedModules.has(affectedFile.resolvedPath) &&
  100487. forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
  100488. });
  100489. }
  100490. /**
  100491. * Iterate on files referencing referencedPath
  100492. */
  100493. function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
  100494. return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
  100495. return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
  100496. });
  100497. }
  100498. /**
  100499. * fn on file and iterate on anything that exports this file
  100500. */
  100501. function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
  100502. if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
  100503. return false;
  100504. }
  100505. if (fn(state, filePath)) {
  100506. // If there are no more diagnostics from old cache, done
  100507. return true;
  100508. }
  100509. ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
  100510. // Go through exported modules from cache first
  100511. // If exported modules has path, all files referencing file exported from are affected
  100512. if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
  100513. return exportedModules &&
  100514. exportedModules.has(filePath) &&
  100515. forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
  100516. })) {
  100517. return true;
  100518. }
  100519. // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
  100520. if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
  100521. return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
  100522. exportedModules.has(filePath) &&
  100523. forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
  100524. })) {
  100525. return true;
  100526. }
  100527. // Remove diagnostics of files that import this file (without going to exports of referencing files)
  100528. return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
  100529. return referencesInFile.has(filePath) &&
  100530. !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
  100531. fn(state, referencingFilePath);
  100532. } // Dont add to seen since this is not yet done with the export removal
  100533. );
  100534. }
  100535. /**
  100536. * This is called after completing operation on the next affected file.
  100537. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
  100538. */
  100539. function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
  100540. if (isBuildInfoEmit) {
  100541. state.emittedBuildInfo = true;
  100542. }
  100543. else if (affected === state.program) {
  100544. state.changedFilesSet.clear();
  100545. state.programEmitComplete = true;
  100546. }
  100547. else {
  100548. state.seenAffectedFiles.set(affected.resolvedPath, true);
  100549. if (emitKind !== undefined) {
  100550. (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
  100551. }
  100552. if (isPendingEmit) {
  100553. state.affectedFilesPendingEmitIndex++;
  100554. }
  100555. else {
  100556. state.affectedFilesIndex++;
  100557. }
  100558. }
  100559. }
  100560. /**
  100561. * Returns the result with affected file
  100562. */
  100563. function toAffectedFileResult(state, result, affected) {
  100564. doneWithAffectedFile(state, affected);
  100565. return { result: result, affected: affected };
  100566. }
  100567. /**
  100568. * Returns the result with affected file
  100569. */
  100570. function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
  100571. doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
  100572. return { result: result, affected: affected };
  100573. }
  100574. /**
  100575. * Gets semantic diagnostics for the file which are
  100576. * bindAndCheckDiagnostics (from cache) and program diagnostics
  100577. */
  100578. function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
  100579. return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.assertDefined(state.program).getProgramDiagnostics(sourceFile));
  100580. }
  100581. /**
  100582. * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
  100583. * Note that it is assumed that when asked about binder and checker diagnostics, the file has been taken out of affected files/changed file set
  100584. */
  100585. function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
  100586. var path = sourceFile.resolvedPath;
  100587. if (state.semanticDiagnosticsPerFile) {
  100588. var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
  100589. // Report the bind and check diagnostics from the cache if we already have those diagnostics present
  100590. if (cachedDiagnostics) {
  100591. return cachedDiagnostics;
  100592. }
  100593. }
  100594. // Diagnostics werent cached, get them from program, and cache the result
  100595. var diagnostics = ts.Debug.assertDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
  100596. if (state.semanticDiagnosticsPerFile) {
  100597. state.semanticDiagnosticsPerFile.set(path, diagnostics);
  100598. }
  100599. return diagnostics;
  100600. }
  100601. /**
  100602. * Gets the program information to be emitted in buildInfo so that we can use it to create new program
  100603. */
  100604. function getProgramBuildInfo(state, getCanonicalFileName) {
  100605. if (state.compilerOptions.outFile || state.compilerOptions.out)
  100606. return undefined;
  100607. var currentDirectory = ts.Debug.assertDefined(state.program).getCurrentDirectory();
  100608. var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
  100609. var fileInfos = {};
  100610. state.fileInfos.forEach(function (value, key) {
  100611. var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
  100612. fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature };
  100613. });
  100614. var result = {
  100615. fileInfos: fileInfos,
  100616. options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
  100617. };
  100618. if (state.referencedMap) {
  100619. var referencedMap_1 = {};
  100620. state.referencedMap.forEach(function (value, key) {
  100621. referencedMap_1[relativeToBuildInfo(key)] = ts.arrayFrom(value.keys(), relativeToBuildInfo);
  100622. });
  100623. result.referencedMap = referencedMap_1;
  100624. }
  100625. if (state.exportedModulesMap) {
  100626. var exportedModulesMap_1 = {};
  100627. state.exportedModulesMap.forEach(function (value, key) {
  100628. var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
  100629. // Not in temporary cache, use existing value
  100630. if (newValue === undefined)
  100631. exportedModulesMap_1[relativeToBuildInfo(key)] = ts.arrayFrom(value.keys(), relativeToBuildInfo);
  100632. // Value in cache and has updated value map, use that
  100633. else if (newValue)
  100634. exportedModulesMap_1[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo);
  100635. });
  100636. result.exportedModulesMap = exportedModulesMap_1;
  100637. }
  100638. if (state.semanticDiagnosticsPerFile) {
  100639. var semanticDiagnosticsPerFile_1 = [];
  100640. // Currently not recording actual errors since those mean no emit for tsc --build
  100641. state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
  100642. [
  100643. relativeToBuildInfo(key),
  100644. state.hasReusableDiagnostic ?
  100645. value :
  100646. convertToReusableDiagnostics(value, relativeToBuildInfo)
  100647. ] :
  100648. relativeToBuildInfo(key)); });
  100649. result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
  100650. }
  100651. return result;
  100652. function relativeToBuildInfoEnsuringAbsolutePath(path) {
  100653. return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
  100654. }
  100655. function relativeToBuildInfo(path) {
  100656. return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
  100657. }
  100658. }
  100659. function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
  100660. var result = {};
  100661. var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
  100662. for (var name in options) {
  100663. if (ts.hasProperty(options, name)) {
  100664. result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
  100665. }
  100666. }
  100667. if (result.configFilePath) {
  100668. result.configFilePath = relativeToBuildInfo(result.configFilePath);
  100669. }
  100670. return result;
  100671. }
  100672. function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
  100673. if (option) {
  100674. if (option.type === "list") {
  100675. var values = value;
  100676. if (option.element.isFilePath && values.length) {
  100677. return values.map(relativeToBuildInfo);
  100678. }
  100679. }
  100680. else if (option.isFilePath) {
  100681. return relativeToBuildInfo(value);
  100682. }
  100683. }
  100684. return value;
  100685. }
  100686. function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
  100687. ts.Debug.assert(!!diagnostics.length);
  100688. return diagnostics.map(function (diagnostic) {
  100689. var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
  100690. result.reportsUnnecessary = diagnostic.reportsUnnecessary;
  100691. result.source = diagnostic.source;
  100692. var relatedInformation = diagnostic.relatedInformation;
  100693. result.relatedInformation = relatedInformation ?
  100694. relatedInformation.length ?
  100695. relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
  100696. ts.emptyArray :
  100697. undefined;
  100698. return result;
  100699. });
  100700. }
  100701. function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
  100702. var file = diagnostic.file;
  100703. return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
  100704. }
  100705. var BuilderProgramKind;
  100706. (function (BuilderProgramKind) {
  100707. BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
  100708. BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
  100709. })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
  100710. function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  100711. var host;
  100712. var newProgram;
  100713. var oldProgram;
  100714. if (newProgramOrRootNames === undefined) {
  100715. ts.Debug.assert(hostOrOptions === undefined);
  100716. host = oldProgramOrHost;
  100717. oldProgram = configFileParsingDiagnosticsOrOldProgram;
  100718. ts.Debug.assert(!!oldProgram);
  100719. newProgram = oldProgram.getProgram();
  100720. }
  100721. else if (ts.isArray(newProgramOrRootNames)) {
  100722. oldProgram = configFileParsingDiagnosticsOrOldProgram;
  100723. newProgram = ts.createProgram({
  100724. rootNames: newProgramOrRootNames,
  100725. options: hostOrOptions,
  100726. host: oldProgramOrHost,
  100727. oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
  100728. configFileParsingDiagnostics: configFileParsingDiagnostics,
  100729. projectReferences: projectReferences
  100730. });
  100731. host = oldProgramOrHost;
  100732. }
  100733. else {
  100734. newProgram = newProgramOrRootNames;
  100735. host = hostOrOptions;
  100736. oldProgram = oldProgramOrHost;
  100737. configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
  100738. }
  100739. return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
  100740. }
  100741. ts.getBuilderCreationParameters = getBuilderCreationParameters;
  100742. function createBuilderProgram(kind, _a) {
  100743. var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
  100744. // Return same program if underlying program doesnt change
  100745. var oldState = oldProgram && oldProgram.getState();
  100746. if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
  100747. newProgram = undefined; // TODO: GH#18217
  100748. oldState = undefined;
  100749. return oldProgram;
  100750. }
  100751. /**
  100752. * Create the canonical file name for identity
  100753. */
  100754. var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  100755. /**
  100756. * Computing hash to for signature verification
  100757. */
  100758. var computeHash = host.createHash || ts.generateDjb2Hash;
  100759. var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
  100760. var backupState;
  100761. newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
  100762. // To ensure that we arent storing any references to old program or new program without state
  100763. newProgram = undefined; // TODO: GH#18217
  100764. oldProgram = undefined;
  100765. oldState = undefined;
  100766. var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
  100767. builderProgram.getState = function () { return state; };
  100768. builderProgram.backupState = function () {
  100769. ts.Debug.assert(backupState === undefined);
  100770. backupState = cloneBuilderProgramState(state);
  100771. };
  100772. builderProgram.restoreState = function () {
  100773. state = ts.Debug.assertDefined(backupState);
  100774. backupState = undefined;
  100775. };
  100776. builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); };
  100777. builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
  100778. builderProgram.emit = emit;
  100779. builderProgram.releaseProgram = function () {
  100780. releaseCache(state);
  100781. backupState = undefined;
  100782. };
  100783. if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
  100784. builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
  100785. }
  100786. else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
  100787. builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
  100788. builderProgram.emitNextAffectedFile = emitNextAffectedFile;
  100789. }
  100790. else {
  100791. ts.notImplemented();
  100792. }
  100793. return builderProgram;
  100794. /**
  100795. * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
  100796. * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
  100797. * in that order would be used to write the files
  100798. */
  100799. function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  100800. var affected = getNextAffectedFile(state, cancellationToken, computeHash);
  100801. var emitKind = 1 /* Full */;
  100802. var isPendingEmitFile = false;
  100803. if (!affected) {
  100804. if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
  100805. var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
  100806. if (!pendingAffectedFile) {
  100807. if (state.emittedBuildInfo) {
  100808. return undefined;
  100809. }
  100810. var affected_1 = ts.Debug.assertDefined(state.program);
  100811. return toAffectedFileEmitResult(state,
  100812. // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
  100813. // Otherwise just affected file
  100814. affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */,
  100815. /*isPendingEmitFile*/ false,
  100816. /*isBuildInfoEmit*/ true);
  100817. }
  100818. (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
  100819. isPendingEmitFile = true;
  100820. }
  100821. else {
  100822. var program = ts.Debug.assertDefined(state.program);
  100823. if (state.programEmitComplete)
  100824. return undefined;
  100825. affected = program;
  100826. }
  100827. }
  100828. return toAffectedFileEmitResult(state,
  100829. // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
  100830. // Otherwise just affected file
  100831. ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile);
  100832. }
  100833. /**
  100834. * Emits the JavaScript and declaration files.
  100835. * When targetSource file is specified, emits the files corresponding to that source file,
  100836. * otherwise for the whole program.
  100837. * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
  100838. * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
  100839. * it will only emit all the affected files instead of whole program
  100840. *
  100841. * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
  100842. * in that order would be used to write the files
  100843. */
  100844. function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  100845. if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
  100846. assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
  100847. var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
  100848. if (result)
  100849. return result;
  100850. if (!targetSourceFile) {
  100851. // Emit and report any errors we ran into.
  100852. var sourceMaps = [];
  100853. var emitSkipped = false;
  100854. var diagnostics = void 0;
  100855. var emittedFiles = [];
  100856. var affectedEmitResult = void 0;
  100857. while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
  100858. emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
  100859. diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
  100860. emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
  100861. sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
  100862. }
  100863. return {
  100864. emitSkipped: emitSkipped,
  100865. diagnostics: diagnostics || ts.emptyArray,
  100866. emittedFiles: emittedFiles,
  100867. sourceMaps: sourceMaps
  100868. };
  100869. }
  100870. }
  100871. return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
  100872. }
  100873. /**
  100874. * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
  100875. * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
  100876. */
  100877. function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
  100878. while (true) {
  100879. var affected = getNextAffectedFile(state, cancellationToken, computeHash);
  100880. if (!affected) {
  100881. // Done
  100882. return undefined;
  100883. }
  100884. else if (affected === state.program) {
  100885. // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
  100886. return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
  100887. }
  100888. // Add file to affected file pending emit to handle for later emit time
  100889. if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
  100890. addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
  100891. }
  100892. // Get diagnostics for the affected file if its not ignored
  100893. if (ignoreSourceFile && ignoreSourceFile(affected)) {
  100894. // Get next affected file
  100895. doneWithAffectedFile(state, affected);
  100896. continue;
  100897. }
  100898. return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
  100899. }
  100900. }
  100901. /**
  100902. * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
  100903. * The semantic diagnostics are cached and managed here
  100904. * Note that it is assumed that when asked about semantic diagnostics through this API,
  100905. * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
  100906. * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
  100907. * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
  100908. */
  100909. function getSemanticDiagnostics(sourceFile, cancellationToken) {
  100910. assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
  100911. var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions();
  100912. if (compilerOptions.outFile || compilerOptions.out) {
  100913. ts.Debug.assert(!state.semanticDiagnosticsPerFile);
  100914. // We dont need to cache the diagnostics just return them from program
  100915. return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
  100916. }
  100917. if (sourceFile) {
  100918. return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
  100919. }
  100920. // When semantic builder asks for diagnostics of the whole program,
  100921. // ensure that all the affected files are handled
  100922. // eslint-disable-next-line no-empty
  100923. while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
  100924. }
  100925. var diagnostics;
  100926. for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
  100927. var sourceFile_1 = _a[_i];
  100928. diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
  100929. }
  100930. return diagnostics || ts.emptyArray;
  100931. }
  100932. }
  100933. ts.createBuilderProgram = createBuilderProgram;
  100934. function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
  100935. if (!state.affectedFilesPendingEmit)
  100936. state.affectedFilesPendingEmit = [];
  100937. if (!state.affectedFilesPendingEmitKind)
  100938. state.affectedFilesPendingEmitKind = ts.createMap();
  100939. var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
  100940. state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
  100941. state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
  100942. // affectedFilesPendingEmitIndex === undefined
  100943. // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
  100944. // so start from 0 as array would be affectedFilesPendingEmit
  100945. // else, continue to iterate from existing index, the current set is appended to existing files
  100946. if (state.affectedFilesPendingEmitIndex === undefined) {
  100947. state.affectedFilesPendingEmitIndex = 0;
  100948. }
  100949. }
  100950. function getMapOfReferencedSet(mapLike, toPath) {
  100951. if (!mapLike)
  100952. return undefined;
  100953. var map = ts.createMap();
  100954. // Copies keys/values from template. Note that for..in will not throw if
  100955. // template is undefined, and instead will just exit the loop.
  100956. for (var key in mapLike) {
  100957. if (ts.hasProperty(mapLike, key)) {
  100958. map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
  100959. }
  100960. }
  100961. return map;
  100962. }
  100963. function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
  100964. var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
  100965. var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  100966. var fileInfos = ts.createMap();
  100967. for (var key in program.fileInfos) {
  100968. if (ts.hasProperty(program.fileInfos, key)) {
  100969. fileInfos.set(toPath(key), program.fileInfos[key]);
  100970. }
  100971. }
  100972. var state = {
  100973. fileInfos: fileInfos,
  100974. compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
  100975. referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
  100976. exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
  100977. semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
  100978. hasReusableDiagnostic: true
  100979. };
  100980. return {
  100981. getState: function () { return state; },
  100982. backupState: ts.noop,
  100983. restoreState: ts.noop,
  100984. getProgram: ts.notImplemented,
  100985. getProgramOrUndefined: ts.returnUndefined,
  100986. releaseProgram: ts.noop,
  100987. getCompilerOptions: function () { return state.compilerOptions; },
  100988. getSourceFile: ts.notImplemented,
  100989. getSourceFiles: ts.notImplemented,
  100990. getOptionsDiagnostics: ts.notImplemented,
  100991. getGlobalDiagnostics: ts.notImplemented,
  100992. getConfigFileParsingDiagnostics: ts.notImplemented,
  100993. getSyntacticDiagnostics: ts.notImplemented,
  100994. getDeclarationDiagnostics: ts.notImplemented,
  100995. getSemanticDiagnostics: ts.notImplemented,
  100996. emit: ts.notImplemented,
  100997. getAllDependencies: ts.notImplemented,
  100998. getCurrentDirectory: ts.notImplemented,
  100999. emitNextAffectedFile: ts.notImplemented,
  101000. getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
  101001. close: ts.noop,
  101002. };
  101003. function toPath(path) {
  101004. return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
  101005. }
  101006. function toAbsolutePath(path) {
  101007. return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
  101008. }
  101009. }
  101010. ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
  101011. function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
  101012. return {
  101013. getState: ts.notImplemented,
  101014. backupState: ts.noop,
  101015. restoreState: ts.noop,
  101016. getProgram: getProgram,
  101017. getProgramOrUndefined: function () { return state.program; },
  101018. releaseProgram: function () { return state.program = undefined; },
  101019. getCompilerOptions: function () { return state.compilerOptions; },
  101020. getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
  101021. getSourceFiles: function () { return getProgram().getSourceFiles(); },
  101022. getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
  101023. getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
  101024. getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
  101025. getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
  101026. getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
  101027. getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
  101028. emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
  101029. getAllDependencies: ts.notImplemented,
  101030. getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
  101031. close: ts.noop,
  101032. };
  101033. function getProgram() {
  101034. return ts.Debug.assertDefined(state.program);
  101035. }
  101036. }
  101037. ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
  101038. })(ts || (ts = {}));
  101039. var ts;
  101040. (function (ts) {
  101041. function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  101042. return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
  101043. }
  101044. ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
  101045. function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  101046. return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
  101047. }
  101048. ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
  101049. function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  101050. var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
  101051. return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
  101052. }
  101053. ts.createAbstractBuilder = createAbstractBuilder;
  101054. })(ts || (ts = {}));
  101055. /*@internal*/
  101056. var ts;
  101057. (function (ts) {
  101058. function removeIgnoredPath(path) {
  101059. // Consider whole staging folder as if node_modules changed.
  101060. if (ts.endsWith(path, "/node_modules/.staging")) {
  101061. return ts.removeSuffix(path, "/.staging");
  101062. }
  101063. return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
  101064. undefined :
  101065. path;
  101066. }
  101067. ts.removeIgnoredPath = removeIgnoredPath;
  101068. /**
  101069. * Filter out paths like
  101070. * "/", "/user", "/user/username", "/user/username/folderAtRoot",
  101071. * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
  101072. * @param dirPath
  101073. */
  101074. function canWatchDirectory(dirPath) {
  101075. var rootLength = ts.getRootLength(dirPath);
  101076. if (dirPath.length === rootLength) {
  101077. // Ignore "/", "c:/"
  101078. return false;
  101079. }
  101080. var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
  101081. if (nextDirectorySeparator === -1) {
  101082. // ignore "/user", "c:/users" or "c:/folderAtRoot"
  101083. return false;
  101084. }
  101085. var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
  101086. var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
  101087. if (isNonDirectorySeparatorRoot &&
  101088. dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
  101089. pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
  101090. nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
  101091. if (nextDirectorySeparator === -1) {
  101092. // ignore "//vda1cs4850/c$/folderAtRoot"
  101093. return false;
  101094. }
  101095. pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
  101096. }
  101097. if (isNonDirectorySeparatorRoot &&
  101098. pathPartForUserCheck.search(/users\//i) !== 0) {
  101099. // Paths like c:/folderAtRoot/subFolder are allowed
  101100. return true;
  101101. }
  101102. for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
  101103. searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
  101104. if (searchIndex === 0) {
  101105. // Folder isnt at expected minimum levels
  101106. return false;
  101107. }
  101108. }
  101109. return true;
  101110. }
  101111. ts.canWatchDirectory = canWatchDirectory;
  101112. ts.maxNumberOfFilesToIterateForInvalidation = 256;
  101113. function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
  101114. var filesWithChangedSetOfUnresolvedImports;
  101115. var filesWithInvalidatedResolutions;
  101116. var filesWithInvalidatedNonRelativeUnresolvedImports;
  101117. var allFilesHaveInvalidatedResolution = false;
  101118. var nonRelativeExternalModuleResolutions = ts.createMultiMap();
  101119. var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
  101120. var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
  101121. // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
  101122. // The key in the map is source file's path.
  101123. // The values are Map of resolutions with key being name lookedup.
  101124. var resolvedModuleNames = ts.createMap();
  101125. var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
  101126. var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
  101127. var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
  101128. var resolvedTypeReferenceDirectives = ts.createMap();
  101129. var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
  101130. /**
  101131. * These are the extensions that failed lookup files will have by default,
  101132. * any other extension of failed lookup will be store that path in custom failed lookup path
  101133. * This helps in not having to comb through all resolutions when files are added/removed
  101134. * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
  101135. */
  101136. var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
  101137. var customFailedLookupPaths = ts.createMap();
  101138. var directoryWatchesOfFailedLookups = ts.createMap();
  101139. var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
  101140. var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
  101141. var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
  101142. // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
  101143. var typeRootsWatches = ts.createMap();
  101144. return {
  101145. startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
  101146. finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
  101147. // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
  101148. // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
  101149. startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
  101150. finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
  101151. resolveModuleNames: resolveModuleNames,
  101152. getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
  101153. resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
  101154. removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
  101155. removeResolutionsOfFile: removeResolutionsOfFile,
  101156. invalidateResolutionOfFile: invalidateResolutionOfFile,
  101157. setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
  101158. createHasInvalidatedResolution: createHasInvalidatedResolution,
  101159. updateTypeRootsWatch: updateTypeRootsWatch,
  101160. closeTypeRootsWatch: closeTypeRootsWatch,
  101161. clear: clear
  101162. };
  101163. function getResolvedModule(resolution) {
  101164. return resolution.resolvedModule;
  101165. }
  101166. function getResolvedTypeReferenceDirective(resolution) {
  101167. return resolution.resolvedTypeReferenceDirective;
  101168. }
  101169. function isInDirectoryPath(dir, file) {
  101170. if (dir === undefined || file.length <= dir.length) {
  101171. return false;
  101172. }
  101173. return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
  101174. }
  101175. function clear() {
  101176. ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
  101177. customFailedLookupPaths.clear();
  101178. nonRelativeExternalModuleResolutions.clear();
  101179. closeTypeRootsWatch();
  101180. resolvedModuleNames.clear();
  101181. resolvedTypeReferenceDirectives.clear();
  101182. allFilesHaveInvalidatedResolution = false;
  101183. // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
  101184. // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
  101185. clearPerDirectoryResolutions();
  101186. }
  101187. function startRecordingFilesWithChangedResolutions() {
  101188. filesWithChangedSetOfUnresolvedImports = [];
  101189. }
  101190. function finishRecordingFilesWithChangedResolutions() {
  101191. var collected = filesWithChangedSetOfUnresolvedImports;
  101192. filesWithChangedSetOfUnresolvedImports = undefined;
  101193. return collected;
  101194. }
  101195. function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
  101196. if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
  101197. return false;
  101198. }
  101199. // Invalidated if file has unresolved imports
  101200. var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
  101201. return !!value && !!value.length;
  101202. }
  101203. function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
  101204. if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) {
  101205. // Any file asked would have invalidated resolution
  101206. filesWithInvalidatedResolutions = undefined;
  101207. return ts.returnTrue;
  101208. }
  101209. var collected = filesWithInvalidatedResolutions;
  101210. filesWithInvalidatedResolutions = undefined;
  101211. return function (path) { return (!!collected && collected.has(path)) ||
  101212. isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
  101213. }
  101214. function clearPerDirectoryResolutions() {
  101215. perDirectoryResolvedModuleNames.clear();
  101216. nonRelativeModuleNameCache.clear();
  101217. perDirectoryResolvedTypeReferenceDirectives.clear();
  101218. nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
  101219. nonRelativeExternalModuleResolutions.clear();
  101220. }
  101221. function finishCachingPerDirectoryResolution() {
  101222. allFilesHaveInvalidatedResolution = false;
  101223. filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
  101224. clearPerDirectoryResolutions();
  101225. directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
  101226. if (watcher.refCount === 0) {
  101227. directoryWatchesOfFailedLookups.delete(path);
  101228. watcher.watcher.close();
  101229. }
  101230. });
  101231. }
  101232. function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
  101233. var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
  101234. // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
  101235. if (!resolutionHost.getGlobalCache) {
  101236. return primaryResult;
  101237. }
  101238. // otherwise try to load typings from @types
  101239. var globalCache = resolutionHost.getGlobalCache();
  101240. if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
  101241. // create different collection of failed lookup locations for second pass
  101242. // if it will fail and we've already found something during the first pass - we don't want to pollute its results
  101243. var _a = ts.loadModuleFromGlobalCache(ts.Debug.assertDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
  101244. if (resolvedModule) {
  101245. return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) };
  101246. }
  101247. }
  101248. // Default return the result from the first pass
  101249. return primaryResult;
  101250. }
  101251. function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) {
  101252. var path = resolutionHost.toPath(containingFile);
  101253. var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
  101254. var dirPath = ts.getDirectoryPath(path);
  101255. var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
  101256. var perDirectoryResolution = perDirectoryCache.get(dirPath);
  101257. if (!perDirectoryResolution) {
  101258. perDirectoryResolution = ts.createMap();
  101259. perDirectoryCache.set(dirPath, perDirectoryResolution);
  101260. }
  101261. var resolvedModules = [];
  101262. var compilerOptions = resolutionHost.getCompilationSettings();
  101263. var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
  101264. // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
  101265. var program = resolutionHost.getCurrentProgram();
  101266. var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
  101267. var unmatchedRedirects = oldRedirect ?
  101268. !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
  101269. !!redirectedReference;
  101270. var seenNamesInFile = ts.createMap();
  101271. for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
  101272. var name = names_3[_i];
  101273. var resolution = resolutionsInFile.get(name);
  101274. // Resolution is valid if it is present and not invalidated
  101275. if (!seenNamesInFile.has(name) &&
  101276. allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated ||
  101277. // If the name is unresolved import that was invalidated, recalculate
  101278. (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
  101279. var existingResolution = resolution;
  101280. var resolutionInDirectory = perDirectoryResolution.get(name);
  101281. if (resolutionInDirectory) {
  101282. resolution = resolutionInDirectory;
  101283. }
  101284. else {
  101285. resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference);
  101286. perDirectoryResolution.set(name, resolution);
  101287. }
  101288. resolutionsInFile.set(name, resolution);
  101289. watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution);
  101290. if (existingResolution) {
  101291. stopWatchFailedLookupLocationOfResolution(existingResolution);
  101292. }
  101293. if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
  101294. filesWithChangedSetOfUnresolvedImports.push(path);
  101295. // reset log changes to avoid recording the same file multiple times
  101296. logChanges = false;
  101297. }
  101298. }
  101299. ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
  101300. seenNamesInFile.set(name, true);
  101301. resolvedModules.push(getResolutionWithResolvedFileName(resolution));
  101302. }
  101303. // Stop watching and remove the unused name
  101304. resolutionsInFile.forEach(function (resolution, name) {
  101305. if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
  101306. stopWatchFailedLookupLocationOfResolution(resolution);
  101307. resolutionsInFile.delete(name);
  101308. }
  101309. });
  101310. return resolvedModules;
  101311. function resolutionIsEqualTo(oldResolution, newResolution) {
  101312. if (oldResolution === newResolution) {
  101313. return true;
  101314. }
  101315. if (!oldResolution || !newResolution) {
  101316. return false;
  101317. }
  101318. var oldResult = getResolutionWithResolvedFileName(oldResolution);
  101319. var newResult = getResolutionWithResolvedFileName(newResolution);
  101320. if (oldResult === newResult) {
  101321. return true;
  101322. }
  101323. if (!oldResult || !newResult) {
  101324. return false;
  101325. }
  101326. return oldResult.resolvedFileName === newResult.resolvedFileName;
  101327. }
  101328. }
  101329. function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
  101330. return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective,
  101331. /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
  101332. /*reusedNames*/ undefined, /*logChanges*/ false);
  101333. }
  101334. function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
  101335. return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule,
  101336. /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule);
  101337. }
  101338. function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
  101339. var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
  101340. return cache && cache.get(moduleName);
  101341. }
  101342. function isNodeModulesDirectory(dirPath) {
  101343. return ts.endsWith(dirPath, "/node_modules");
  101344. }
  101345. function isNodeModulesAtTypesDirectory(dirPath) {
  101346. return ts.endsWith(dirPath, "/node_modules/@types");
  101347. }
  101348. function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
  101349. if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
  101350. // Ensure failed look up is normalized path
  101351. failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
  101352. var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
  101353. var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
  101354. ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
  101355. if (failedLookupPathSplit.length > rootSplitLength + 1) {
  101356. // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
  101357. return {
  101358. dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
  101359. dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
  101360. };
  101361. }
  101362. else {
  101363. // Always watch root directory non recursively
  101364. return {
  101365. dir: rootDir,
  101366. dirPath: rootPath,
  101367. nonRecursive: false
  101368. };
  101369. }
  101370. }
  101371. return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
  101372. }
  101373. function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
  101374. // If directory path contains node module, get the most parent node_modules directory for watching
  101375. while (ts.pathContainsNodeModules(dirPath)) {
  101376. dir = ts.getDirectoryPath(dir);
  101377. dirPath = ts.getDirectoryPath(dirPath);
  101378. }
  101379. // If the directory is node_modules use it to watch, always watch it recursively
  101380. if (isNodeModulesDirectory(dirPath)) {
  101381. return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
  101382. }
  101383. var nonRecursive = true;
  101384. // Use some ancestor of the root directory
  101385. var subDirectoryPath, subDirectory;
  101386. if (rootPath !== undefined) {
  101387. while (!isInDirectoryPath(dirPath, rootPath)) {
  101388. var parentPath = ts.getDirectoryPath(dirPath);
  101389. if (parentPath === dirPath) {
  101390. break;
  101391. }
  101392. nonRecursive = false;
  101393. subDirectoryPath = dirPath;
  101394. subDirectory = dir;
  101395. dirPath = parentPath;
  101396. dir = ts.getDirectoryPath(dir);
  101397. }
  101398. }
  101399. return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
  101400. }
  101401. function isPathWithDefaultFailedLookupExtension(path) {
  101402. return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
  101403. }
  101404. function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) {
  101405. // No need to set the resolution refCount
  101406. if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) {
  101407. if (resolution.refCount) {
  101408. resolution.refCount++;
  101409. }
  101410. else {
  101411. resolution.refCount = 1;
  101412. if (ts.isExternalModuleNameRelative(name)) {
  101413. watchFailedLookupLocationOfResolution(resolution);
  101414. }
  101415. else {
  101416. nonRelativeExternalModuleResolutions.add(name, resolution);
  101417. }
  101418. }
  101419. }
  101420. }
  101421. function watchFailedLookupLocationOfResolution(resolution) {
  101422. ts.Debug.assert(!!resolution.refCount);
  101423. var failedLookupLocations = resolution.failedLookupLocations;
  101424. var setAtRoot = false;
  101425. for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
  101426. var failedLookupLocation = failedLookupLocations_1[_i];
  101427. var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
  101428. var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
  101429. if (toWatch) {
  101430. var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
  101431. // If the failed lookup location path is not one of the supported extensions,
  101432. // store it in the custom path
  101433. if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
  101434. var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
  101435. customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
  101436. }
  101437. if (dirPath === rootPath) {
  101438. ts.Debug.assert(!nonRecursive);
  101439. setAtRoot = true;
  101440. }
  101441. else {
  101442. setDirectoryWatcher(dir, dirPath, nonRecursive);
  101443. }
  101444. }
  101445. }
  101446. if (setAtRoot) {
  101447. // This is always non recursive
  101448. setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
  101449. }
  101450. }
  101451. function setRefCountToUndefined(resolution) {
  101452. resolution.refCount = undefined;
  101453. }
  101454. function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
  101455. var program = resolutionHost.getCurrentProgram();
  101456. var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ?
  101457. setRefCountToUndefined : watchFailedLookupLocationOfResolution;
  101458. resolutions.forEach(updateResolution);
  101459. }
  101460. function setDirectoryWatcher(dir, dirPath, nonRecursive) {
  101461. var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
  101462. if (dirWatcher) {
  101463. ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
  101464. dirWatcher.refCount++;
  101465. }
  101466. else {
  101467. directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
  101468. }
  101469. }
  101470. function stopWatchFailedLookupLocationOfResolution(resolution) {
  101471. if (!resolution.refCount) {
  101472. return;
  101473. }
  101474. resolution.refCount--;
  101475. if (resolution.refCount) {
  101476. return;
  101477. }
  101478. var failedLookupLocations = resolution.failedLookupLocations;
  101479. var removeAtRoot = false;
  101480. for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
  101481. var failedLookupLocation = failedLookupLocations_2[_i];
  101482. var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
  101483. var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
  101484. if (toWatch) {
  101485. var dirPath = toWatch.dirPath;
  101486. var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
  101487. if (refCount) {
  101488. if (refCount === 1) {
  101489. customFailedLookupPaths.delete(failedLookupLocationPath);
  101490. }
  101491. else {
  101492. ts.Debug.assert(refCount > 1);
  101493. customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
  101494. }
  101495. }
  101496. if (dirPath === rootPath) {
  101497. removeAtRoot = true;
  101498. }
  101499. else {
  101500. removeDirectoryWatcher(dirPath);
  101501. }
  101502. }
  101503. }
  101504. if (removeAtRoot) {
  101505. removeDirectoryWatcher(rootPath);
  101506. }
  101507. }
  101508. function removeDirectoryWatcher(dirPath) {
  101509. var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
  101510. // Do not close the watcher yet since it might be needed by other failed lookup locations.
  101511. dirWatcher.refCount--;
  101512. }
  101513. function createDirectoryWatcher(directory, dirPath, nonRecursive) {
  101514. return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
  101515. var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
  101516. if (cachedDirectoryStructureHost) {
  101517. // Since the file existence changed, update the sourceFiles cache
  101518. cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
  101519. }
  101520. if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
  101521. resolutionHost.onInvalidatedResolution();
  101522. }
  101523. }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
  101524. }
  101525. function removeResolutionsOfFileFromCache(cache, filePath) {
  101526. // Deleted file, stop watching failed lookups for all the resolutions in the file
  101527. var resolutions = cache.get(filePath);
  101528. if (resolutions) {
  101529. resolutions.forEach(stopWatchFailedLookupLocationOfResolution);
  101530. cache.delete(filePath);
  101531. }
  101532. }
  101533. function removeResolutionsFromProjectReferenceRedirects(filePath) {
  101534. if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
  101535. return;
  101536. }
  101537. var program = resolutionHost.getCurrentProgram();
  101538. if (!program) {
  101539. return;
  101540. }
  101541. // If this file is input file for the referenced project, get it
  101542. var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
  101543. if (!resolvedProjectReference) {
  101544. return;
  101545. }
  101546. // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
  101547. resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
  101548. }
  101549. function removeResolutionsOfFile(filePath) {
  101550. removeResolutionsOfFileFromCache(resolvedModuleNames, filePath);
  101551. removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath);
  101552. }
  101553. function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) {
  101554. var seen = ts.createMap();
  101555. cache.forEach(function (resolutions, containingFilePath) {
  101556. var dirPath = ts.getDirectoryPath(containingFilePath);
  101557. var seenInDir = seen.get(dirPath);
  101558. if (!seenInDir) {
  101559. seenInDir = ts.createMap();
  101560. seen.set(dirPath, seenInDir);
  101561. }
  101562. resolutions.forEach(function (resolution, name) {
  101563. if (seenInDir.has(name)) {
  101564. return;
  101565. }
  101566. seenInDir.set(name, true);
  101567. if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) {
  101568. // Mark the file as needing re-evaluation of module resolution instead of using it blindly.
  101569. resolution.isInvalidated = true;
  101570. (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
  101571. // When its a file with inferred types resolution, invalidate type reference directive resolution
  101572. if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) {
  101573. resolutionHost.onChangedAutomaticTypeDirectiveNames();
  101574. }
  101575. }
  101576. });
  101577. });
  101578. }
  101579. function hasReachedResolutionIterationLimit() {
  101580. var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation;
  101581. return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize;
  101582. }
  101583. function invalidateResolutions(isInvalidatedResolution) {
  101584. // If more than maxNumberOfFilesToIterateForInvalidation present,
  101585. // just invalidated all files and recalculate the resolutions for files instead
  101586. if (hasReachedResolutionIterationLimit()) {
  101587. allFilesHaveInvalidatedResolution = true;
  101588. return;
  101589. }
  101590. invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule);
  101591. invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective);
  101592. }
  101593. function invalidateResolutionOfFile(filePath) {
  101594. removeResolutionsOfFile(filePath);
  101595. invalidateResolutions(
  101596. // Resolution is invalidated if the resulting file name is same as the deleted file path
  101597. function (resolution, getResolutionWithResolvedFileName) {
  101598. var result = getResolutionWithResolvedFileName(resolution);
  101599. return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217
  101600. });
  101601. }
  101602. function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
  101603. ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
  101604. filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
  101605. }
  101606. function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
  101607. var isChangedFailedLookupLocation;
  101608. if (isCreatingWatchedDirectory) {
  101609. // Watching directory is created
  101610. // Invalidate any resolution has failed lookup in this directory
  101611. isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
  101612. }
  101613. else {
  101614. // If something to do with folder/file starting with "." in node_modules folder, skip it
  101615. var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
  101616. if (!updatedPath)
  101617. return false;
  101618. fileOrDirectoryPath = updatedPath;
  101619. // prevent saving an open file from over-eagerly triggering invalidation
  101620. if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
  101621. return false;
  101622. }
  101623. // Some file or directory in the watching directory is created
  101624. // Return early if it does not have any of the watching extension or not the custom failed lookup path
  101625. var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
  101626. if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) ||
  101627. isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) {
  101628. // Invalidate any resolution from this directory
  101629. isChangedFailedLookupLocation = function (location) {
  101630. var locationPath = resolutionHost.toPath(location);
  101631. return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
  101632. };
  101633. }
  101634. else {
  101635. if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
  101636. return false;
  101637. }
  101638. // Ignore emits from the program
  101639. if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
  101640. return false;
  101641. }
  101642. // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
  101643. isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
  101644. }
  101645. }
  101646. var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); };
  101647. var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size;
  101648. invalidateResolutions(
  101649. // Resolution is invalidated if the resulting file name is same as the deleted file path
  101650. hasChangedFailedLookupLocation);
  101651. return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount;
  101652. }
  101653. function closeTypeRootsWatch() {
  101654. ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
  101655. }
  101656. function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
  101657. if (allFilesHaveInvalidatedResolution) {
  101658. return undefined;
  101659. }
  101660. if (isInDirectoryPath(rootPath, typeRootPath)) {
  101661. return rootPath;
  101662. }
  101663. var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
  101664. return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
  101665. }
  101666. function createTypeRootsWatch(typeRootPath, typeRoot) {
  101667. // Create new watch and recursive info
  101668. return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
  101669. var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
  101670. if (cachedDirectoryStructureHost) {
  101671. // Since the file existence changed, update the sourceFiles cache
  101672. cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
  101673. }
  101674. // For now just recompile
  101675. // We could potentially store more data here about whether it was/would be really be used or not
  101676. // and with that determine to trigger compilation but for now this is enough
  101677. resolutionHost.onChangedAutomaticTypeDirectiveNames();
  101678. // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
  101679. // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
  101680. var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
  101681. if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
  101682. resolutionHost.onInvalidatedResolution();
  101683. }
  101684. }, 1 /* Recursive */);
  101685. }
  101686. /**
  101687. * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
  101688. * To be called when compiler options change
  101689. */
  101690. function updateTypeRootsWatch() {
  101691. var options = resolutionHost.getCompilationSettings();
  101692. if (options.types) {
  101693. // No need to do any watch since resolution cache is going to handle the failed lookups
  101694. // for the types added by this
  101695. closeTypeRootsWatch();
  101696. return;
  101697. }
  101698. // we need to assume the directories exist to ensure that we can get all the type root directories that get included
  101699. // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
  101700. var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
  101701. if (typeRoots) {
  101702. ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
  101703. createNewValue: createTypeRootsWatch,
  101704. onDeleteValue: ts.closeFileWatcher
  101705. });
  101706. }
  101707. else {
  101708. closeTypeRootsWatch();
  101709. }
  101710. }
  101711. /**
  101712. * Use this function to return if directory exists to get type roots to watch
  101713. * If we return directory exists then only the paths will be added to type roots
  101714. * Hence return true for all directories except root directories which are filtered from watching
  101715. */
  101716. function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
  101717. var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
  101718. var dirPath = resolutionHost.toPath(dir);
  101719. return dirPath === rootPath || canWatchDirectory(dirPath);
  101720. }
  101721. }
  101722. ts.createResolutionCache = createResolutionCache;
  101723. })(ts || (ts = {}));
  101724. // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
  101725. /* @internal */
  101726. var ts;
  101727. (function (ts) {
  101728. var moduleSpecifiers;
  101729. (function (moduleSpecifiers) {
  101730. var RelativePreference;
  101731. (function (RelativePreference) {
  101732. RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
  101733. RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
  101734. RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
  101735. })(RelativePreference || (RelativePreference = {}));
  101736. // See UserPreferences#importPathEnding
  101737. var Ending;
  101738. (function (Ending) {
  101739. Ending[Ending["Minimal"] = 0] = "Minimal";
  101740. Ending[Ending["Index"] = 1] = "Index";
  101741. Ending[Ending["JsExtension"] = 2] = "JsExtension";
  101742. })(Ending || (Ending = {}));
  101743. function getPreferences(_a, compilerOptions, importingSourceFile) {
  101744. var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
  101745. return {
  101746. relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
  101747. ending: getEnding(),
  101748. };
  101749. function getEnding() {
  101750. switch (importModuleSpecifierEnding) {
  101751. case "minimal": return 0 /* Minimal */;
  101752. case "index": return 1 /* Index */;
  101753. case "js": return 2 /* JsExtension */;
  101754. default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
  101755. : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
  101756. }
  101757. }
  101758. }
  101759. function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
  101760. return {
  101761. relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
  101762. ending: ts.hasJSFileExtension(oldImportSpecifier) ?
  101763. 2 /* JsExtension */ :
  101764. ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
  101765. };
  101766. }
  101767. function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) {
  101768. var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
  101769. if (res === oldImportSpecifier)
  101770. return undefined;
  101771. return res;
  101772. }
  101773. moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
  101774. // Note: importingSourceFile is just for usesJsExtensionOnImports
  101775. function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) {
  101776. if (preferences === void 0) { preferences = {}; }
  101777. return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile));
  101778. }
  101779. moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
  101780. function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host, files, redirectTargetsMap) {
  101781. var info = getInfo(importingSourceFileName, host);
  101782. var modulePaths = getAllModulePaths(files, importingSourceFileName, nodeModulesFileName, info.getCanonicalFileName, host, redirectTargetsMap);
  101783. return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
  101784. }
  101785. moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
  101786. function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) {
  101787. var info = getInfo(importingSourceFileName, host);
  101788. var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap);
  101789. return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
  101790. getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
  101791. }
  101792. /** Returns an import for each symlink and for the realpath. */
  101793. function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) {
  101794. var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
  101795. if (ambient)
  101796. return [ambient];
  101797. var info = getInfo(importingSourceFile.path, host);
  101798. var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
  101799. var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.originalFileName, info.getCanonicalFileName, host, redirectTargetsMap);
  101800. var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
  101801. var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
  101802. return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
  101803. }
  101804. moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
  101805. // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
  101806. function getInfo(importingSourceFileName, host) {
  101807. var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
  101808. var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
  101809. return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
  101810. }
  101811. function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
  101812. var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
  101813. var ending = _b.ending, relativePreference = _b.relativePreference;
  101814. var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
  101815. var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
  101816. removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
  101817. if (!baseUrl || relativePreference === 0 /* Relative */) {
  101818. return relativePath;
  101819. }
  101820. var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
  101821. if (!relativeToBaseUrl) {
  101822. return relativePath;
  101823. }
  101824. var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
  101825. var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
  101826. var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
  101827. if (relativePreference === 1 /* NonRelative */) {
  101828. return nonRelative;
  101829. }
  101830. if (relativePreference !== 2 /* Auto */)
  101831. ts.Debug.assertNever(relativePreference);
  101832. // Prefer a relative import over a baseUrl import if it has fewer components.
  101833. return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
  101834. }
  101835. function countPathComponents(path) {
  101836. var count = 0;
  101837. for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
  101838. if (path.charCodeAt(i) === 47 /* slash */)
  101839. count++;
  101840. }
  101841. return count;
  101842. }
  101843. moduleSpecifiers.countPathComponents = countPathComponents;
  101844. function usesJsExtensionOnImports(_a) {
  101845. var imports = _a.imports;
  101846. return ts.firstDefined(imports, function (_a) {
  101847. var text = _a.text;
  101848. return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
  101849. }) || false;
  101850. }
  101851. function numberOfDirectorySeparators(str) {
  101852. var match = str.match(/\//g);
  101853. return match ? match.length : 0;
  101854. }
  101855. function comparePathsByNumberOfDirectorySeparators(a, b) {
  101856. return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
  101857. }
  101858. /**
  101859. * Looks for existing imports that use symlinks to this module.
  101860. * Symlinks will be returned first so they are preferred over the real path.
  101861. */
  101862. function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) {
  101863. var redirects = redirectTargetsMap.get(importedFileName);
  101864. var importedFileNames = redirects ? __spreadArrays(redirects, [importedFileName]) : [importedFileName];
  101865. var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : "";
  101866. var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
  101867. var links = host.getProbableSymlinks
  101868. ? host.getProbableSymlinks(files)
  101869. : ts.discoverProbableSymlinks(files, getCanonicalFileName, cwd);
  101870. var result = [];
  101871. var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
  101872. links.forEach(function (resolved, path) {
  101873. if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
  101874. return; // Don't want to a package to globally import from itself
  101875. }
  101876. var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
  101877. if (target === undefined)
  101878. return;
  101879. var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
  101880. var option = ts.resolvePath(path, relative);
  101881. if (!host.fileExists || host.fileExists(option)) {
  101882. result.push(option);
  101883. }
  101884. });
  101885. result.push.apply(result, targets);
  101886. if (result.length < 2)
  101887. return result;
  101888. // Sort by paths closest to importing file Name directory
  101889. var allFileNames = ts.arrayToMap(result, ts.identity, getCanonicalFileName);
  101890. var sortedPaths = [];
  101891. var _loop_18 = function (directory) {
  101892. var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
  101893. var pathsInDirectory;
  101894. allFileNames.forEach(function (canonicalFileName, fileName) {
  101895. if (ts.startsWith(canonicalFileName, directoryStart)) {
  101896. (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
  101897. allFileNames.delete(fileName);
  101898. }
  101899. });
  101900. if (pathsInDirectory) {
  101901. if (pathsInDirectory.length > 1) {
  101902. pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
  101903. }
  101904. sortedPaths.push.apply(sortedPaths, pathsInDirectory);
  101905. }
  101906. var newDirectory = ts.getDirectoryPath(directory);
  101907. if (newDirectory === directory)
  101908. return out_directory_1 = directory, "break";
  101909. directory = newDirectory;
  101910. out_directory_1 = directory;
  101911. };
  101912. var out_directory_1;
  101913. for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
  101914. var state_7 = _loop_18(directory);
  101915. directory = out_directory_1;
  101916. if (state_7 === "break")
  101917. break;
  101918. }
  101919. if (allFileNames.size) {
  101920. var remainingPaths = ts.arrayFrom(allFileNames.values());
  101921. if (remainingPaths.length > 1)
  101922. remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
  101923. sortedPaths.push.apply(sortedPaths, remainingPaths);
  101924. }
  101925. return sortedPaths;
  101926. }
  101927. function tryGetModuleNameFromAmbientModule(moduleSymbol) {
  101928. var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
  101929. if (decl) {
  101930. return decl.name.text;
  101931. }
  101932. }
  101933. function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
  101934. for (var key in paths) {
  101935. for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
  101936. var patternText_1 = _a[_i];
  101937. var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
  101938. var indexOfStar = pattern.indexOf("*");
  101939. if (indexOfStar !== -1) {
  101940. var prefix = pattern.substr(0, indexOfStar);
  101941. var suffix = pattern.substr(indexOfStar + 1);
  101942. if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
  101943. ts.startsWith(relativeToBaseUrl, prefix) &&
  101944. ts.endsWith(relativeToBaseUrl, suffix) ||
  101945. !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
  101946. var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
  101947. return key.replace("*", matchedStar);
  101948. }
  101949. }
  101950. else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
  101951. return key;
  101952. }
  101953. }
  101954. }
  101955. }
  101956. function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
  101957. var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
  101958. if (normalizedTargetPath === undefined) {
  101959. return undefined;
  101960. }
  101961. var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
  101962. var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
  101963. return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
  101964. ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
  101965. : ts.removeFileExtension(relativePath);
  101966. }
  101967. function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
  101968. var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
  101969. if (!host.fileExists || !host.readFile) {
  101970. return undefined;
  101971. }
  101972. var parts = getNodeModulePathParts(moduleFileName);
  101973. if (!parts) {
  101974. return undefined;
  101975. }
  101976. var packageJsonContent;
  101977. var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex);
  101978. if (!packageNameOnly) {
  101979. var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
  101980. packageJsonContent = host.fileExists(packageJsonPath)
  101981. ? JSON.parse(host.readFile(packageJsonPath))
  101982. : undefined;
  101983. var versionPaths = packageJsonContent && packageJsonContent.typesVersions
  101984. ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
  101985. : undefined;
  101986. if (versionPaths) {
  101987. var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
  101988. var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
  101989. if (fromPaths !== undefined) {
  101990. moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
  101991. }
  101992. }
  101993. }
  101994. // Simplify the full file path to something that can be resolved by Node.
  101995. // If the module could be imported by a directory name, use that directory's name
  101996. var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName);
  101997. var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
  101998. // Get a path that's relative to node_modules or the importing file's path
  101999. // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
  102000. var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
  102001. if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
  102002. return undefined;
  102003. }
  102004. // If the module was found in @types, get the actual Node package name
  102005. var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
  102006. var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
  102007. // For classic resolution, only allow importing from node_modules/@types, not other node_modules
  102008. return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
  102009. function getDirectoryOrExtensionlessFileName(path) {
  102010. // If the file is the main module, it can be imported by the package name
  102011. if (packageJsonContent) {
  102012. var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
  102013. if (ts.isString(mainFileRelative)) {
  102014. var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
  102015. if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) {
  102016. return packageRootPath;
  102017. }
  102018. }
  102019. }
  102020. // We still have a file name - remove the extension
  102021. var fullModulePathWithoutExtension = ts.removeFileExtension(path);
  102022. // If the file is /index, it can be imported by its directory name
  102023. // IFF there is not _also_ a file by the same name
  102024. if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
  102025. return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
  102026. }
  102027. return fullModulePathWithoutExtension;
  102028. }
  102029. }
  102030. function tryGetAnyFileFromPath(host, path) {
  102031. if (!host.fileExists)
  102032. return;
  102033. // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
  102034. var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
  102035. for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
  102036. var e = extensions_3[_i];
  102037. var fullPath = path + e;
  102038. if (host.fileExists(fullPath)) {
  102039. return fullPath;
  102040. }
  102041. }
  102042. }
  102043. function getNodeModulePathParts(fullPath) {
  102044. // If fullPath can't be valid module file within node_modules, returns undefined.
  102045. // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
  102046. // Returns indices: ^ ^ ^ ^
  102047. var topLevelNodeModulesIndex = 0;
  102048. var topLevelPackageNameIndex = 0;
  102049. var packageRootIndex = 0;
  102050. var fileNameIndex = 0;
  102051. var States;
  102052. (function (States) {
  102053. States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
  102054. States[States["NodeModules"] = 1] = "NodeModules";
  102055. States[States["Scope"] = 2] = "Scope";
  102056. States[States["PackageContent"] = 3] = "PackageContent";
  102057. })(States || (States = {}));
  102058. var partStart = 0;
  102059. var partEnd = 0;
  102060. var state = 0 /* BeforeNodeModules */;
  102061. while (partEnd >= 0) {
  102062. partStart = partEnd;
  102063. partEnd = fullPath.indexOf("/", partStart + 1);
  102064. switch (state) {
  102065. case 0 /* BeforeNodeModules */:
  102066. if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
  102067. topLevelNodeModulesIndex = partStart;
  102068. topLevelPackageNameIndex = partEnd;
  102069. state = 1 /* NodeModules */;
  102070. }
  102071. break;
  102072. case 1 /* NodeModules */:
  102073. case 2 /* Scope */:
  102074. if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
  102075. state = 2 /* Scope */;
  102076. }
  102077. else {
  102078. packageRootIndex = partEnd;
  102079. state = 3 /* PackageContent */;
  102080. }
  102081. break;
  102082. case 3 /* PackageContent */:
  102083. if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
  102084. state = 1 /* NodeModules */;
  102085. }
  102086. else {
  102087. state = 3 /* PackageContent */;
  102088. }
  102089. break;
  102090. }
  102091. }
  102092. fileNameIndex = partStart;
  102093. return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
  102094. }
  102095. function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
  102096. return ts.firstDefined(rootDirs, function (rootDir) {
  102097. var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
  102098. return isPathRelativeToParent(relativePath) ? undefined : relativePath;
  102099. });
  102100. }
  102101. function removeExtensionAndIndexPostFix(fileName, ending, options) {
  102102. if (ts.fileExtensionIs(fileName, ".json" /* Json */))
  102103. return fileName;
  102104. var noExtension = ts.removeFileExtension(fileName);
  102105. switch (ending) {
  102106. case 0 /* Minimal */:
  102107. return ts.removeSuffix(noExtension, "/index");
  102108. case 1 /* Index */:
  102109. return noExtension;
  102110. case 2 /* JsExtension */:
  102111. return noExtension + getJSExtensionForFile(fileName, options);
  102112. default:
  102113. return ts.Debug.assertNever(ending);
  102114. }
  102115. }
  102116. function getJSExtensionForFile(fileName, options) {
  102117. var ext = ts.extensionFromPath(fileName);
  102118. switch (ext) {
  102119. case ".ts" /* Ts */:
  102120. case ".d.ts" /* Dts */:
  102121. return ".js" /* Js */;
  102122. case ".tsx" /* Tsx */:
  102123. return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
  102124. case ".js" /* Js */:
  102125. case ".jsx" /* Jsx */:
  102126. case ".json" /* Json */:
  102127. return ext;
  102128. case ".tsbuildinfo" /* TsBuildInfo */:
  102129. return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
  102130. default:
  102131. return ts.Debug.assertNever(ext);
  102132. }
  102133. }
  102134. function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
  102135. var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
  102136. return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
  102137. }
  102138. function isPathRelativeToParent(path) {
  102139. return ts.startsWith(path, "..");
  102140. }
  102141. })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
  102142. })(ts || (ts = {}));
  102143. /*@internal*/
  102144. var ts;
  102145. (function (ts) {
  102146. var sysFormatDiagnosticsHost = ts.sys ? {
  102147. getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
  102148. getNewLine: function () { return ts.sys.newLine; },
  102149. getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
  102150. } : undefined; // TODO: GH#18217
  102151. /**
  102152. * Create a function that reports error by writing to the system and handles the formating of the diagnostic
  102153. */
  102154. function createDiagnosticReporter(system, pretty) {
  102155. var host = system === ts.sys ? sysFormatDiagnosticsHost : {
  102156. getCurrentDirectory: function () { return system.getCurrentDirectory(); },
  102157. getNewLine: function () { return system.newLine; },
  102158. getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
  102159. };
  102160. if (!pretty) {
  102161. return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
  102162. }
  102163. var diagnostics = new Array(1);
  102164. return function (diagnostic) {
  102165. diagnostics[0] = diagnostic;
  102166. system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
  102167. diagnostics[0] = undefined; // TODO: GH#18217
  102168. };
  102169. }
  102170. ts.createDiagnosticReporter = createDiagnosticReporter;
  102171. /**
  102172. * @returns Whether the screen was cleared.
  102173. */
  102174. function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
  102175. if (system.clearScreen &&
  102176. !options.preserveWatchOutput &&
  102177. !options.extendedDiagnostics &&
  102178. !options.diagnostics &&
  102179. ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
  102180. system.clearScreen();
  102181. return true;
  102182. }
  102183. return false;
  102184. }
  102185. ts.screenStartingMessageCodes = [
  102186. ts.Diagnostics.Starting_compilation_in_watch_mode.code,
  102187. ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
  102188. ];
  102189. function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
  102190. return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
  102191. ? newLine + newLine
  102192. : newLine;
  102193. }
  102194. /**
  102195. * Get locale specific time based on whether we are in test mode
  102196. */
  102197. function getLocaleTimeString(system) {
  102198. return !system.now ?
  102199. new Date().toLocaleTimeString() :
  102200. system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
  102201. }
  102202. ts.getLocaleTimeString = getLocaleTimeString;
  102203. /**
  102204. * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
  102205. */
  102206. function createWatchStatusReporter(system, pretty) {
  102207. return pretty ?
  102208. function (diagnostic, newLine, options) {
  102209. clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
  102210. var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
  102211. output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
  102212. system.write(output);
  102213. } :
  102214. function (diagnostic, newLine, options) {
  102215. var output = "";
  102216. if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
  102217. output += newLine;
  102218. }
  102219. output += getLocaleTimeString(system) + " - ";
  102220. output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
  102221. system.write(output);
  102222. };
  102223. }
  102224. ts.createWatchStatusReporter = createWatchStatusReporter;
  102225. /** Parses config file using System interface */
  102226. function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
  102227. var host = system;
  102228. host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
  102229. var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
  102230. host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
  102231. return result;
  102232. }
  102233. ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
  102234. function getErrorCountForSummary(diagnostics) {
  102235. return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
  102236. }
  102237. ts.getErrorCountForSummary = getErrorCountForSummary;
  102238. function getWatchErrorSummaryDiagnosticMessage(errorCount) {
  102239. return errorCount === 1 ?
  102240. ts.Diagnostics.Found_1_error_Watching_for_file_changes :
  102241. ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
  102242. }
  102243. ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
  102244. function getErrorSummaryText(errorCount, newLine) {
  102245. if (errorCount === 0)
  102246. return "";
  102247. var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
  102248. return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
  102249. }
  102250. ts.getErrorSummaryText = getErrorSummaryText;
  102251. function listFiles(program, writeFileName) {
  102252. if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
  102253. ts.forEach(program.getSourceFiles(), function (file) {
  102254. writeFileName(file.fileName);
  102255. });
  102256. }
  102257. }
  102258. ts.listFiles = listFiles;
  102259. /**
  102260. * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
  102261. */
  102262. function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  102263. var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
  102264. // First get and report any syntactic errors.
  102265. var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
  102266. var configFileParsingDiagnosticsLength = allDiagnostics.length;
  102267. ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
  102268. // If we didn't have any syntactic errors, then also try getting the global and
  102269. // semantic errors.
  102270. if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
  102271. ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
  102272. if (!isListFilesOnly) {
  102273. ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
  102274. if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
  102275. ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
  102276. }
  102277. }
  102278. }
  102279. // Emit and report any errors we ran into.
  102280. var emitResult = isListFilesOnly
  102281. ? { emitSkipped: true, diagnostics: ts.emptyArray }
  102282. : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
  102283. var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
  102284. ts.addRange(allDiagnostics, emitDiagnostics);
  102285. var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
  102286. diagnostics.forEach(reportDiagnostic);
  102287. if (writeFileName) {
  102288. var currentDir_1 = program.getCurrentDirectory();
  102289. ts.forEach(emittedFiles, function (file) {
  102290. var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
  102291. writeFileName("TSFILE: " + filepath);
  102292. });
  102293. listFiles(program, writeFileName);
  102294. }
  102295. if (reportSummary) {
  102296. reportSummary(getErrorCountForSummary(diagnostics));
  102297. }
  102298. return {
  102299. emitResult: emitResult,
  102300. diagnostics: diagnostics,
  102301. };
  102302. }
  102303. ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
  102304. function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  102305. var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
  102306. if (emitResult.emitSkipped && diagnostics.length > 0) {
  102307. // If the emitter didn't emit anything, then pass that value along.
  102308. return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
  102309. }
  102310. else if (diagnostics.length > 0) {
  102311. // The emitter emitted something, inform the caller if that happened in the presence
  102312. // of diagnostics or not.
  102313. return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
  102314. }
  102315. return ts.ExitStatus.Success;
  102316. }
  102317. ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
  102318. ts.noopFileWatcher = { close: ts.noop };
  102319. function createWatchHost(system, reportWatchStatus) {
  102320. if (system === void 0) { system = ts.sys; }
  102321. var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
  102322. return {
  102323. onWatchStatusChange: onWatchStatusChange,
  102324. watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
  102325. watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
  102326. setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
  102327. clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
  102328. };
  102329. }
  102330. ts.createWatchHost = createWatchHost;
  102331. ts.WatchType = {
  102332. ConfigFile: "Config file",
  102333. SourceFile: "Source file",
  102334. MissingFile: "Missing file",
  102335. WildcardDirectory: "Wild card directory",
  102336. FailedLookupLocations: "Failed Lookup Locations",
  102337. TypeRoots: "Type roots"
  102338. };
  102339. function createWatchFactory(host, options) {
  102340. var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
  102341. var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
  102342. var result = ts.getWatchFactory(watchLogLevel, writeLog);
  102343. result.writeLog = writeLog;
  102344. return result;
  102345. }
  102346. ts.createWatchFactory = createWatchFactory;
  102347. function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
  102348. if (directoryStructureHost === void 0) { directoryStructureHost = host; }
  102349. var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
  102350. var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
  102351. return {
  102352. getSourceFile: function (fileName, languageVersion, onError) {
  102353. var text;
  102354. try {
  102355. ts.performance.mark("beforeIORead");
  102356. text = host.readFile(fileName, getCompilerOptions().charset);
  102357. ts.performance.mark("afterIORead");
  102358. ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
  102359. }
  102360. catch (e) {
  102361. if (onError) {
  102362. onError(e.message);
  102363. }
  102364. text = "";
  102365. }
  102366. return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
  102367. },
  102368. getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
  102369. getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
  102370. writeFile: writeFile,
  102371. getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
  102372. useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
  102373. getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
  102374. getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
  102375. fileExists: function (f) { return host.fileExists(f); },
  102376. readFile: function (f) { return host.readFile(f); },
  102377. trace: ts.maybeBind(host, host.trace),
  102378. directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
  102379. getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
  102380. realpath: ts.maybeBind(host, host.realpath),
  102381. getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
  102382. createHash: ts.maybeBind(host, host.createHash),
  102383. readDirectory: ts.maybeBind(host, host.readDirectory),
  102384. };
  102385. function writeFile(fileName, text, writeByteOrderMark, onError) {
  102386. try {
  102387. ts.performance.mark("beforeIOWrite");
  102388. // NOTE: If patchWriteFileEnsuringDirectory has been called,
  102389. // the host.writeFile will do its own directory creation and
  102390. // the ensureDirectoriesExist call will always be redundant.
  102391. ts.writeFileEnsuringDirectories(fileName, text, writeByteOrderMark, function (path, data, writeByteOrderMark) { return host.writeFile(path, data, writeByteOrderMark); }, function (path) { return host.createDirectory(path); }, function (path) { return host.directoryExists(path); });
  102392. ts.performance.mark("afterIOWrite");
  102393. ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
  102394. }
  102395. catch (e) {
  102396. if (onError) {
  102397. onError(e.message);
  102398. }
  102399. }
  102400. }
  102401. }
  102402. ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
  102403. function setGetSourceFileAsHashVersioned(compilerHost, host) {
  102404. var originalGetSourceFile = compilerHost.getSourceFile;
  102405. var computeHash = host.createHash || ts.generateDjb2Hash;
  102406. compilerHost.getSourceFile = function () {
  102407. var args = [];
  102408. for (var _i = 0; _i < arguments.length; _i++) {
  102409. args[_i] = arguments[_i];
  102410. }
  102411. var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
  102412. if (result) {
  102413. result.version = computeHash.call(host, result.text);
  102414. }
  102415. return result;
  102416. };
  102417. }
  102418. ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
  102419. /**
  102420. * Creates the watch compiler host that can be extended with config file or root file names and options host
  102421. */
  102422. function createProgramHost(system, createProgram) {
  102423. var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
  102424. var host = system;
  102425. // TODO: `host` is unused!
  102426. // eslint-disable-next-line no-unused-expressions
  102427. host;
  102428. return {
  102429. useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
  102430. getNewLine: function () { return system.newLine; },
  102431. getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
  102432. getDefaultLibLocation: getDefaultLibLocation,
  102433. getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
  102434. fileExists: function (path) { return system.fileExists(path); },
  102435. readFile: function (path, encoding) { return system.readFile(path, encoding); },
  102436. directoryExists: function (path) { return system.directoryExists(path); },
  102437. getDirectories: function (path) { return system.getDirectories(path); },
  102438. readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
  102439. realpath: ts.maybeBind(system, system.realpath),
  102440. getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
  102441. trace: function (s) { return system.write(s + system.newLine); },
  102442. createDirectory: function (path) { return system.createDirectory(path); },
  102443. writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
  102444. onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
  102445. createHash: ts.maybeBind(system, system.createHash),
  102446. createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
  102447. };
  102448. }
  102449. ts.createProgramHost = createProgramHost;
  102450. /**
  102451. * Creates the watch compiler host that can be extended with config file or root file names and options host
  102452. */
  102453. function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
  102454. if (system === void 0) { system = ts.sys; }
  102455. var writeFileName = function (s) { return system.write(s + system.newLine); };
  102456. var result = createProgramHost(system, createProgram);
  102457. ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
  102458. result.afterProgramCreate = function (builderProgram) {
  102459. var compilerOptions = builderProgram.getCompilerOptions();
  102460. var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
  102461. emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
  102462. };
  102463. return result;
  102464. }
  102465. /**
  102466. * Report error and exit
  102467. */
  102468. function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
  102469. reportDiagnostic(diagnostic);
  102470. system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
  102471. }
  102472. /**
  102473. * Creates the watch compiler host from system for config file in watch mode
  102474. */
  102475. function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) {
  102476. var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
  102477. var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
  102478. host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
  102479. host.configFileName = configFileName;
  102480. host.optionsToExtend = optionsToExtend;
  102481. host.watchOptionsToExtend = watchOptionsToExtend;
  102482. return host;
  102483. }
  102484. ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
  102485. /**
  102486. * Creates the watch compiler host from system for compiling root files and options in watch mode
  102487. */
  102488. function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
  102489. var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
  102490. host.rootFiles = rootFiles;
  102491. host.options = options;
  102492. host.watchOptions = watchOptions;
  102493. host.projectReferences = projectReferences;
  102494. return host;
  102495. }
  102496. ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
  102497. function performIncrementalCompilation(input) {
  102498. var system = input.system || ts.sys;
  102499. var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
  102500. var builderProgram = ts.createIncrementalProgram(input);
  102501. var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
  102502. if (input.afterProgramEmitAndDiagnostics)
  102503. input.afterProgramEmitAndDiagnostics(builderProgram);
  102504. return exitStatus;
  102505. }
  102506. ts.performIncrementalCompilation = performIncrementalCompilation;
  102507. })(ts || (ts = {}));
  102508. var ts;
  102509. (function (ts) {
  102510. function readBuilderProgram(compilerOptions, host) {
  102511. if (compilerOptions.out || compilerOptions.outFile)
  102512. return undefined;
  102513. var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
  102514. if (!buildInfoPath)
  102515. return undefined;
  102516. var content = host.readFile(buildInfoPath);
  102517. if (!content)
  102518. return undefined;
  102519. var buildInfo = ts.getBuildInfo(content);
  102520. if (buildInfo.version !== ts.version)
  102521. return undefined;
  102522. if (!buildInfo.program)
  102523. return undefined;
  102524. return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
  102525. }
  102526. ts.readBuilderProgram = readBuilderProgram;
  102527. function createIncrementalCompilerHost(options, system) {
  102528. if (system === void 0) { system = ts.sys; }
  102529. var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
  102530. host.createHash = ts.maybeBind(system, system.createHash);
  102531. ts.setGetSourceFileAsHashVersioned(host, system);
  102532. ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
  102533. return host;
  102534. }
  102535. ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
  102536. function createIncrementalProgram(_a) {
  102537. var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
  102538. host = host || createIncrementalCompilerHost(options);
  102539. createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
  102540. var oldProgram = readBuilderProgram(options, host);
  102541. return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
  102542. }
  102543. ts.createIncrementalProgram = createIncrementalProgram;
  102544. function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) {
  102545. if (ts.isArray(rootFilesOrConfigFileName)) {
  102546. return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217
  102547. }
  102548. else {
  102549. return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus);
  102550. }
  102551. }
  102552. ts.createWatchCompilerHost = createWatchCompilerHost;
  102553. function createWatchProgram(host) {
  102554. var builderProgram;
  102555. var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
  102556. var missingFilesMap; // Map of file watchers for the missing files
  102557. var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
  102558. var timerToUpdateProgram; // timer callback to recompile the program
  102559. var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
  102560. var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
  102561. var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
  102562. var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
  102563. var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
  102564. var currentDirectory = host.getCurrentDirectory();
  102565. var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram;
  102566. var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
  102567. var configFileSpecs;
  102568. var configFileParsingDiagnostics;
  102569. var canConfigFileJsonReportNoInputFiles = false;
  102570. var hasChangedConfigFileParsingErrors = false;
  102571. var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
  102572. if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) {
  102573. host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost);
  102574. }
  102575. var directoryStructureHost = cachedDirectoryStructureHost || host;
  102576. var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
  102577. // From tsc we want to get already parsed result and hence check for rootFileNames
  102578. var newLine = updateNewLine();
  102579. if (configFileName && host.configFileParsingResult) {
  102580. setConfigFileParsingResult(host.configFileParsingResult);
  102581. newLine = updateNewLine();
  102582. }
  102583. reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
  102584. if (configFileName && !host.configFileParsingResult) {
  102585. newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
  102586. ts.Debug.assert(!rootFileNames);
  102587. parseConfigFile();
  102588. newLine = updateNewLine();
  102589. }
  102590. var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
  102591. var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  102592. writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
  102593. var configFileWatcher;
  102594. if (configFileName) {
  102595. configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
  102596. }
  102597. var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
  102598. ts.setGetSourceFileAsHashVersioned(compilerHost, host);
  102599. // Members for CompilerHost
  102600. var getNewSourceFile = compilerHost.getSourceFile;
  102601. compilerHost.getSourceFile = function (fileName) {
  102602. var args = [];
  102603. for (var _i = 1; _i < arguments.length; _i++) {
  102604. args[_i - 1] = arguments[_i];
  102605. }
  102606. return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
  102607. };
  102608. compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
  102609. compilerHost.getNewLine = function () { return newLine; };
  102610. compilerHost.fileExists = fileExists;
  102611. compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
  102612. // Members for ResolutionCacheHost
  102613. compilerHost.toPath = toPath;
  102614. compilerHost.getCompilationSettings = function () { return compilerOptions; };
  102615. compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
  102616. compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
  102617. compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
  102618. compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
  102619. compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
  102620. hasChangedAutomaticTypeDirectiveNames = true;
  102621. scheduleProgramUpdate();
  102622. };
  102623. compilerHost.fileIsOpen = ts.returnFalse;
  102624. compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation;
  102625. compilerHost.getCurrentProgram = getCurrentProgram;
  102626. compilerHost.writeLog = writeLog;
  102627. // Cache for the module resolution
  102628. var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
  102629. ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
  102630. currentDirectory,
  102631. /*logChangesWhenResolvingModule*/ false);
  102632. // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
  102633. compilerHost.resolveModuleNames = host.resolveModuleNames ?
  102634. (function () {
  102635. var args = [];
  102636. for (var _i = 0; _i < arguments.length; _i++) {
  102637. args[_i] = arguments[_i];
  102638. }
  102639. return host.resolveModuleNames.apply(host, args);
  102640. }) :
  102641. (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
  102642. compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
  102643. (function () {
  102644. var args = [];
  102645. for (var _i = 0; _i < arguments.length; _i++) {
  102646. args[_i] = arguments[_i];
  102647. }
  102648. return host.resolveTypeReferenceDirectives.apply(host, args);
  102649. }) :
  102650. (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
  102651. var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
  102652. builderProgram = readBuilderProgram(compilerOptions, compilerHost);
  102653. synchronizeProgram();
  102654. // Update the wild card directory watch
  102655. watchConfigFileWildCardDirectories();
  102656. return configFileName ?
  102657. { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
  102658. { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
  102659. function close() {
  102660. resolutionCache.clear();
  102661. ts.clearMap(sourceFilesCache, function (value) {
  102662. if (value && value.fileWatcher) {
  102663. value.fileWatcher.close();
  102664. value.fileWatcher = undefined;
  102665. }
  102666. });
  102667. if (configFileWatcher) {
  102668. configFileWatcher.close();
  102669. configFileWatcher = undefined;
  102670. }
  102671. if (watchedWildcardDirectories) {
  102672. ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
  102673. watchedWildcardDirectories = undefined;
  102674. }
  102675. if (missingFilesMap) {
  102676. ts.clearMap(missingFilesMap, ts.closeFileWatcher);
  102677. missingFilesMap = undefined;
  102678. }
  102679. }
  102680. function getCurrentBuilderProgram() {
  102681. return builderProgram;
  102682. }
  102683. function getCurrentProgram() {
  102684. return builderProgram && builderProgram.getProgramOrUndefined();
  102685. }
  102686. function synchronizeProgram() {
  102687. writeLog("Synchronizing program");
  102688. var program = getCurrentBuilderProgram();
  102689. if (hasChangedCompilerOptions) {
  102690. newLine = updateNewLine();
  102691. if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
  102692. resolutionCache.clear();
  102693. }
  102694. }
  102695. // All resolutions are invalid if user provided resolutions
  102696. var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
  102697. if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
  102698. if (hasChangedConfigFileParsingErrors) {
  102699. builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
  102700. hasChangedConfigFileParsingErrors = false;
  102701. }
  102702. }
  102703. else {
  102704. createNewProgram(hasInvalidatedResolution);
  102705. }
  102706. if (host.afterProgramCreate) {
  102707. host.afterProgramCreate(builderProgram);
  102708. }
  102709. return builderProgram;
  102710. }
  102711. function createNewProgram(hasInvalidatedResolution) {
  102712. // Compile the program
  102713. writeLog("CreatingProgramWith::");
  102714. writeLog(" roots: " + JSON.stringify(rootFileNames));
  102715. writeLog(" options: " + JSON.stringify(compilerOptions));
  102716. var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
  102717. hasChangedCompilerOptions = false;
  102718. hasChangedConfigFileParsingErrors = false;
  102719. resolutionCache.startCachingPerDirectoryResolution();
  102720. compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
  102721. compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
  102722. builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
  102723. resolutionCache.finishCachingPerDirectoryResolution();
  102724. // Update watches
  102725. ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
  102726. if (needsUpdateInTypeRootWatch) {
  102727. resolutionCache.updateTypeRootsWatch();
  102728. }
  102729. if (missingFilePathsRequestedForRelease) {
  102730. // These are the paths that program creater told us as not in use any more but were missing on the disk.
  102731. // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
  102732. // if there is already watcher for it (for missing files)
  102733. // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
  102734. // so that at later time we have correct result of their presence
  102735. for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
  102736. var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
  102737. if (!missingFilesMap.has(missingFilePath)) {
  102738. sourceFilesCache.delete(missingFilePath);
  102739. }
  102740. }
  102741. missingFilePathsRequestedForRelease = undefined;
  102742. }
  102743. }
  102744. function updateRootFileNames(files) {
  102745. ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
  102746. rootFileNames = files;
  102747. scheduleProgramUpdate();
  102748. }
  102749. function updateNewLine() {
  102750. return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
  102751. }
  102752. function toPath(fileName) {
  102753. return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  102754. }
  102755. function isFileMissingOnHost(hostSourceFile) {
  102756. return typeof hostSourceFile === "boolean";
  102757. }
  102758. function isFilePresenceUnknownOnHost(hostSourceFile) {
  102759. return typeof hostSourceFile.version === "boolean";
  102760. }
  102761. function fileExists(fileName) {
  102762. var path = toPath(fileName);
  102763. // If file is missing on host from cache, we can definitely say file doesnt exist
  102764. // otherwise we need to ensure from the disk
  102765. if (isFileMissingOnHost(sourceFilesCache.get(path))) {
  102766. return true;
  102767. }
  102768. return directoryStructureHost.fileExists(fileName);
  102769. }
  102770. function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
  102771. var hostSourceFile = sourceFilesCache.get(path);
  102772. // No source file on the host
  102773. if (isFileMissingOnHost(hostSourceFile)) {
  102774. return undefined;
  102775. }
  102776. // Create new source file if requested or the versions dont match
  102777. if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
  102778. var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
  102779. if (hostSourceFile) {
  102780. if (sourceFile) {
  102781. // Set the source file and create file watcher now that file was present on the disk
  102782. hostSourceFile.sourceFile = sourceFile;
  102783. hostSourceFile.version = sourceFile.version;
  102784. if (!hostSourceFile.fileWatcher) {
  102785. hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
  102786. }
  102787. }
  102788. else {
  102789. // There is no source file on host any more, close the watch, missing file paths will track it
  102790. if (hostSourceFile.fileWatcher) {
  102791. hostSourceFile.fileWatcher.close();
  102792. }
  102793. sourceFilesCache.set(path, false);
  102794. }
  102795. }
  102796. else {
  102797. if (sourceFile) {
  102798. var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
  102799. sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
  102800. }
  102801. else {
  102802. sourceFilesCache.set(path, false);
  102803. }
  102804. }
  102805. return sourceFile;
  102806. }
  102807. return hostSourceFile.sourceFile;
  102808. }
  102809. function nextSourceFileVersion(path) {
  102810. var hostSourceFile = sourceFilesCache.get(path);
  102811. if (hostSourceFile !== undefined) {
  102812. if (isFileMissingOnHost(hostSourceFile)) {
  102813. // The next version, lets set it as presence unknown file
  102814. sourceFilesCache.set(path, { version: false });
  102815. }
  102816. else {
  102817. hostSourceFile.version = false;
  102818. }
  102819. }
  102820. }
  102821. function getSourceVersion(path) {
  102822. var hostSourceFile = sourceFilesCache.get(path);
  102823. return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
  102824. }
  102825. function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
  102826. var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
  102827. // If this is the source file thats in the cache and new program doesnt need it,
  102828. // remove the cached entry.
  102829. // Note we arent deleting entry if file became missing in new program or
  102830. // there was version update and new source file was created.
  102831. if (hostSourceFileInfo !== undefined) {
  102832. // record the missing file paths so they can be removed later if watchers arent tracking them
  102833. if (isFileMissingOnHost(hostSourceFileInfo)) {
  102834. (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
  102835. }
  102836. else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
  102837. if (hostSourceFileInfo.fileWatcher) {
  102838. hostSourceFileInfo.fileWatcher.close();
  102839. }
  102840. sourceFilesCache.delete(oldSourceFile.resolvedPath);
  102841. if (!hasSourceFileByPath) {
  102842. resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
  102843. }
  102844. }
  102845. }
  102846. }
  102847. function reportWatchDiagnostic(message) {
  102848. if (host.onWatchStatusChange) {
  102849. host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
  102850. }
  102851. }
  102852. // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
  102853. // operations (such as saving all modified files in an editor) a chance to complete before we kick
  102854. // off a new compilation.
  102855. function scheduleProgramUpdate() {
  102856. if (!host.setTimeout || !host.clearTimeout) {
  102857. return;
  102858. }
  102859. if (timerToUpdateProgram) {
  102860. host.clearTimeout(timerToUpdateProgram);
  102861. }
  102862. writeLog("Scheduling update");
  102863. timerToUpdateProgram = host.setTimeout(updateProgram, 250);
  102864. }
  102865. function scheduleProgramReload() {
  102866. ts.Debug.assert(!!configFileName);
  102867. reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
  102868. scheduleProgramUpdate();
  102869. }
  102870. function updateProgram() {
  102871. timerToUpdateProgram = undefined;
  102872. reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
  102873. switch (reloadLevel) {
  102874. case ts.ConfigFileProgramReloadLevel.Partial:
  102875. ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
  102876. reloadFileNamesFromConfigFile();
  102877. break;
  102878. case ts.ConfigFileProgramReloadLevel.Full:
  102879. ts.perfLogger.logStartUpdateProgram("FullConfigReload");
  102880. reloadConfigFile();
  102881. break;
  102882. default:
  102883. ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
  102884. synchronizeProgram();
  102885. break;
  102886. }
  102887. ts.perfLogger.logStopUpdateProgram("Done");
  102888. }
  102889. function reloadFileNamesFromConfigFile() {
  102890. writeLog("Reloading new file names and options");
  102891. var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
  102892. if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
  102893. hasChangedConfigFileParsingErrors = true;
  102894. }
  102895. rootFileNames = result.fileNames;
  102896. // Update the program
  102897. synchronizeProgram();
  102898. }
  102899. function reloadConfigFile() {
  102900. writeLog("Reloading config file: " + configFileName);
  102901. reloadLevel = ts.ConfigFileProgramReloadLevel.None;
  102902. if (cachedDirectoryStructureHost) {
  102903. cachedDirectoryStructureHost.clearCache();
  102904. }
  102905. parseConfigFile();
  102906. hasChangedCompilerOptions = true;
  102907. synchronizeProgram();
  102908. // Update the wild card directory watch
  102909. watchConfigFileWildCardDirectories();
  102910. }
  102911. function parseConfigFile() {
  102912. setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217
  102913. }
  102914. function setConfigFileParsingResult(configFileParseResult) {
  102915. rootFileNames = configFileParseResult.fileNames;
  102916. compilerOptions = configFileParseResult.options;
  102917. watchOptions = configFileParseResult.watchOptions;
  102918. configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
  102919. projectReferences = configFileParseResult.projectReferences;
  102920. configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
  102921. canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
  102922. hasChangedConfigFileParsingErrors = true;
  102923. }
  102924. function onSourceFileChange(fileName, eventKind, path) {
  102925. updateCachedSystemWithFile(fileName, path, eventKind);
  102926. // Update the source file cache
  102927. if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
  102928. resolutionCache.invalidateResolutionOfFile(path);
  102929. }
  102930. resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
  102931. nextSourceFileVersion(path);
  102932. // Update the program
  102933. scheduleProgramUpdate();
  102934. }
  102935. function updateCachedSystemWithFile(fileName, path, eventKind) {
  102936. if (cachedDirectoryStructureHost) {
  102937. cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
  102938. }
  102939. }
  102940. function watchMissingFilePath(missingFilePath) {
  102941. return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
  102942. }
  102943. function onMissingFileChange(fileName, eventKind, missingFilePath) {
  102944. updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
  102945. if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
  102946. missingFilesMap.get(missingFilePath).close();
  102947. missingFilesMap.delete(missingFilePath);
  102948. // Delete the entry in the source files cache so that new source file is created
  102949. nextSourceFileVersion(missingFilePath);
  102950. // When a missing file is created, we should update the graph.
  102951. scheduleProgramUpdate();
  102952. }
  102953. }
  102954. function watchConfigFileWildCardDirectories() {
  102955. if (configFileSpecs) {
  102956. ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
  102957. }
  102958. else if (watchedWildcardDirectories) {
  102959. ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
  102960. }
  102961. }
  102962. function watchWildcardDirectory(directory, flags) {
  102963. return watchDirectory(host, directory, function (fileOrDirectory) {
  102964. ts.Debug.assert(!!configFileName);
  102965. var fileOrDirectoryPath = toPath(fileOrDirectory);
  102966. // Since the file existence changed, update the sourceFiles cache
  102967. if (cachedDirectoryStructureHost) {
  102968. cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
  102969. }
  102970. nextSourceFileVersion(fileOrDirectoryPath);
  102971. fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
  102972. if (!fileOrDirectoryPath)
  102973. return;
  102974. // If the the added or created file or directory is not supported file name, ignore the file
  102975. // But when watched directory is added/removed, we need to reload the file list
  102976. if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
  102977. writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
  102978. return;
  102979. }
  102980. // Reload is pending, do the reload
  102981. if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
  102982. reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
  102983. // Schedule Update the program
  102984. scheduleProgramUpdate();
  102985. }
  102986. }, flags, watchOptions, ts.WatchType.WildcardDirectory);
  102987. }
  102988. }
  102989. ts.createWatchProgram = createWatchProgram;
  102990. })(ts || (ts = {}));
  102991. /*@internal*/
  102992. var ts;
  102993. (function (ts) {
  102994. var UpToDateStatusType;
  102995. (function (UpToDateStatusType) {
  102996. UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
  102997. UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
  102998. /**
  102999. * The project appears out of date because its upstream inputs are newer than its outputs,
  103000. * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
  103001. * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
  103002. */
  103003. UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
  103004. /**
  103005. * The project appears out of date because its upstream inputs are newer than its outputs,
  103006. * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
  103007. * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
  103008. */
  103009. UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
  103010. UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
  103011. UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
  103012. UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
  103013. UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
  103014. UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
  103015. UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
  103016. UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
  103017. /**
  103018. * Projects with no outputs (i.e. "solution" files)
  103019. */
  103020. UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
  103021. })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
  103022. function resolveConfigFileProjectName(project) {
  103023. if (ts.fileExtensionIs(project, ".json" /* Json */)) {
  103024. return project;
  103025. }
  103026. return ts.combinePaths(project, "tsconfig.json");
  103027. }
  103028. ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
  103029. })(ts || (ts = {}));
  103030. var ts;
  103031. (function (ts) {
  103032. var minimumDate = new Date(-8640000000000000);
  103033. var maximumDate = new Date(8640000000000000);
  103034. var BuildResultFlags;
  103035. (function (BuildResultFlags) {
  103036. BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
  103037. /**
  103038. * No errors of any kind occurred during build
  103039. */
  103040. BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
  103041. /**
  103042. * None of the .d.ts files emitted by this build were
  103043. * different from the existing files on disk
  103044. */
  103045. BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
  103046. BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
  103047. BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
  103048. BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
  103049. BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
  103050. BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
  103051. BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
  103052. })(BuildResultFlags || (BuildResultFlags = {}));
  103053. function createConfigFileMap() {
  103054. return ts.createMap();
  103055. }
  103056. function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
  103057. var existingValue = configFileMap.get(resolved);
  103058. var newValue;
  103059. if (!existingValue) {
  103060. newValue = createT();
  103061. configFileMap.set(resolved, newValue);
  103062. }
  103063. return existingValue || newValue;
  103064. }
  103065. function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
  103066. return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
  103067. }
  103068. function newer(date1, date2) {
  103069. return date2 > date1 ? date2 : date1;
  103070. }
  103071. function isDeclarationFile(fileName) {
  103072. return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
  103073. }
  103074. /*@internal*/
  103075. function isCircularBuildOrder(buildOrder) {
  103076. return !!buildOrder && !!buildOrder.buildOrder;
  103077. }
  103078. ts.isCircularBuildOrder = isCircularBuildOrder;
  103079. /*@internal*/
  103080. function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
  103081. return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
  103082. }
  103083. ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
  103084. /**
  103085. * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
  103086. */
  103087. function createBuilderStatusReporter(system, pretty) {
  103088. return function (diagnostic) {
  103089. var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
  103090. output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
  103091. system.write(output);
  103092. };
  103093. }
  103094. ts.createBuilderStatusReporter = createBuilderStatusReporter;
  103095. function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
  103096. var host = ts.createProgramHost(system, createProgram);
  103097. host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
  103098. host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
  103099. host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
  103100. host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
  103101. host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
  103102. host.now = ts.maybeBind(system, system.now); // For testing
  103103. return host;
  103104. }
  103105. function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
  103106. if (system === void 0) { system = ts.sys; }
  103107. var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
  103108. host.reportErrorSummary = reportErrorSummary;
  103109. return host;
  103110. }
  103111. ts.createSolutionBuilderHost = createSolutionBuilderHost;
  103112. function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
  103113. if (system === void 0) { system = ts.sys; }
  103114. var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
  103115. var watchHost = ts.createWatchHost(system, reportWatchStatus);
  103116. ts.copyProperties(host, watchHost);
  103117. return host;
  103118. }
  103119. ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
  103120. function getCompilerOptionsOfBuildOptions(buildOptions) {
  103121. var result = {};
  103122. ts.commonOptionsWithBuild.forEach(function (option) {
  103123. if (ts.hasProperty(buildOptions, option.name))
  103124. result[option.name] = buildOptions[option.name];
  103125. });
  103126. return result;
  103127. }
  103128. function createSolutionBuilder(host, rootNames, defaultOptions) {
  103129. return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
  103130. }
  103131. ts.createSolutionBuilder = createSolutionBuilder;
  103132. function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
  103133. return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
  103134. }
  103135. ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
  103136. function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
  103137. var host = hostOrHostWithWatch;
  103138. var hostWithWatch = hostOrHostWithWatch;
  103139. var currentDirectory = host.getCurrentDirectory();
  103140. var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  103141. // State of the solution
  103142. var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
  103143. var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
  103144. ts.setGetSourceFileAsHashVersioned(compilerHost, host);
  103145. compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
  103146. compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
  103147. compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
  103148. var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
  103149. if (!compilerHost.resolveModuleNames) {
  103150. var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
  103151. compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
  103152. return ts.loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
  103153. };
  103154. }
  103155. var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
  103156. var state = {
  103157. host: host,
  103158. hostWithWatch: hostWithWatch,
  103159. currentDirectory: currentDirectory,
  103160. getCanonicalFileName: getCanonicalFileName,
  103161. parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
  103162. writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
  103163. // State of solution
  103164. options: options,
  103165. baseCompilerOptions: baseCompilerOptions,
  103166. rootNames: rootNames,
  103167. baseWatchOptions: baseWatchOptions,
  103168. resolvedConfigFilePaths: ts.createMap(),
  103169. configFileCache: createConfigFileMap(),
  103170. projectStatus: createConfigFileMap(),
  103171. buildInfoChecked: createConfigFileMap(),
  103172. extendedConfigCache: ts.createMap(),
  103173. builderPrograms: createConfigFileMap(),
  103174. diagnostics: createConfigFileMap(),
  103175. projectPendingBuild: createConfigFileMap(),
  103176. projectErrorsReported: createConfigFileMap(),
  103177. compilerHost: compilerHost,
  103178. moduleResolutionCache: moduleResolutionCache,
  103179. // Mutable state
  103180. buildOrder: undefined,
  103181. readFileWithCache: function (f) { return host.readFile(f); },
  103182. projectCompilerOptions: baseCompilerOptions,
  103183. cache: undefined,
  103184. allProjectBuildPending: true,
  103185. needsSummary: true,
  103186. watchAllProjectsPending: watch,
  103187. currentInvalidatedProject: undefined,
  103188. // Watch state
  103189. watch: watch,
  103190. allWatchedWildcardDirectories: createConfigFileMap(),
  103191. allWatchedInputFiles: createConfigFileMap(),
  103192. allWatchedConfigFiles: createConfigFileMap(),
  103193. timerToBuildInvalidatedProject: undefined,
  103194. reportFileChangeDetected: false,
  103195. watchFile: watchFile,
  103196. watchFilePath: watchFilePath,
  103197. watchDirectory: watchDirectory,
  103198. writeLog: writeLog,
  103199. };
  103200. return state;
  103201. }
  103202. function toPath(state, fileName) {
  103203. return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
  103204. }
  103205. function toResolvedConfigFilePath(state, fileName) {
  103206. var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
  103207. var path = resolvedConfigFilePaths.get(fileName);
  103208. if (path !== undefined)
  103209. return path;
  103210. var resolvedPath = toPath(state, fileName);
  103211. resolvedConfigFilePaths.set(fileName, resolvedPath);
  103212. return resolvedPath;
  103213. }
  103214. function isParsedCommandLine(entry) {
  103215. return !!entry.options;
  103216. }
  103217. function parseConfigFile(state, configFileName, configFilePath) {
  103218. var configFileCache = state.configFileCache;
  103219. var value = configFileCache.get(configFilePath);
  103220. if (value) {
  103221. return isParsedCommandLine(value) ? value : undefined;
  103222. }
  103223. var diagnostic;
  103224. var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
  103225. var parsed;
  103226. if (host.getParsedCommandLine) {
  103227. parsed = host.getParsedCommandLine(configFileName);
  103228. if (!parsed)
  103229. diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
  103230. }
  103231. else {
  103232. parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
  103233. parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
  103234. parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
  103235. }
  103236. configFileCache.set(configFilePath, parsed || diagnostic);
  103237. return parsed;
  103238. }
  103239. function resolveProjectName(state, name) {
  103240. return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
  103241. }
  103242. function createBuildOrder(state, roots) {
  103243. var temporaryMarks = ts.createMap();
  103244. var permanentMarks = ts.createMap();
  103245. var circularityReportStack = [];
  103246. var buildOrder;
  103247. var circularDiagnostics;
  103248. for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
  103249. var root = roots_1[_i];
  103250. visit(root);
  103251. }
  103252. return circularDiagnostics ?
  103253. { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
  103254. buildOrder || ts.emptyArray;
  103255. function visit(configFileName, inCircularContext) {
  103256. var projPath = toResolvedConfigFilePath(state, configFileName);
  103257. // Already visited
  103258. if (permanentMarks.has(projPath))
  103259. return;
  103260. // Circular
  103261. if (temporaryMarks.has(projPath)) {
  103262. if (!inCircularContext) {
  103263. (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
  103264. }
  103265. return;
  103266. }
  103267. temporaryMarks.set(projPath, true);
  103268. circularityReportStack.push(configFileName);
  103269. var parsed = parseConfigFile(state, configFileName, projPath);
  103270. if (parsed && parsed.projectReferences) {
  103271. for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
  103272. var ref = _a[_i];
  103273. var resolvedRefPath = resolveProjectName(state, ref.path);
  103274. visit(resolvedRefPath, inCircularContext || ref.circular);
  103275. }
  103276. }
  103277. circularityReportStack.pop();
  103278. permanentMarks.set(projPath, true);
  103279. (buildOrder || (buildOrder = [])).push(configFileName);
  103280. }
  103281. }
  103282. function getBuildOrder(state) {
  103283. return state.buildOrder || createStateBuildOrder(state);
  103284. }
  103285. function createStateBuildOrder(state) {
  103286. var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
  103287. // Clear all to ResolvedConfigFilePaths cache to start fresh
  103288. state.resolvedConfigFilePaths.clear();
  103289. var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
  103290. var noopOnDelete = { onDeleteValue: ts.noop };
  103291. // Config file cache
  103292. ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
  103293. ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
  103294. ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
  103295. ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
  103296. ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
  103297. ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
  103298. ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
  103299. // Remove watches for the program no longer in the solution
  103300. if (state.watch) {
  103301. ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
  103302. ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
  103303. ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
  103304. }
  103305. return state.buildOrder = buildOrder;
  103306. }
  103307. function getBuildOrderFor(state, project, onlyReferences) {
  103308. var resolvedProject = project && resolveProjectName(state, project);
  103309. var buildOrderFromState = getBuildOrder(state);
  103310. if (isCircularBuildOrder(buildOrderFromState))
  103311. return buildOrderFromState;
  103312. if (resolvedProject) {
  103313. var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
  103314. var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
  103315. if (projectIndex === -1)
  103316. return undefined;
  103317. }
  103318. var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
  103319. ts.Debug.assert(!isCircularBuildOrder(buildOrder));
  103320. ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
  103321. ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
  103322. return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
  103323. }
  103324. function enableCache(state) {
  103325. if (state.cache) {
  103326. disableCache(state);
  103327. }
  103328. var compilerHost = state.compilerHost, host = state.host;
  103329. var originalReadFileWithCache = state.readFileWithCache;
  103330. var originalGetSourceFile = compilerHost.getSourceFile;
  103331. var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
  103332. var args = [];
  103333. for (var _i = 0; _i < arguments.length; _i++) {
  103334. args[_i] = arguments[_i];
  103335. }
  103336. return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
  103337. }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
  103338. state.readFileWithCache = readFileWithCache;
  103339. compilerHost.getSourceFile = getSourceFileWithCache;
  103340. state.cache = {
  103341. originalReadFile: originalReadFile,
  103342. originalFileExists: originalFileExists,
  103343. originalDirectoryExists: originalDirectoryExists,
  103344. originalCreateDirectory: originalCreateDirectory,
  103345. originalWriteFile: originalWriteFile,
  103346. originalReadFileWithCache: originalReadFileWithCache,
  103347. originalGetSourceFile: originalGetSourceFile,
  103348. };
  103349. }
  103350. function disableCache(state) {
  103351. if (!state.cache)
  103352. return;
  103353. var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
  103354. host.readFile = cache.originalReadFile;
  103355. host.fileExists = cache.originalFileExists;
  103356. host.directoryExists = cache.originalDirectoryExists;
  103357. host.createDirectory = cache.originalCreateDirectory;
  103358. host.writeFile = cache.originalWriteFile;
  103359. compilerHost.getSourceFile = cache.originalGetSourceFile;
  103360. state.readFileWithCache = cache.originalReadFileWithCache;
  103361. extendedConfigCache.clear();
  103362. if (moduleResolutionCache) {
  103363. moduleResolutionCache.directoryToModuleNameMap.clear();
  103364. moduleResolutionCache.moduleNameToDirectoryMap.clear();
  103365. }
  103366. state.cache = undefined;
  103367. }
  103368. function clearProjectStatus(state, resolved) {
  103369. state.projectStatus.delete(resolved);
  103370. state.diagnostics.delete(resolved);
  103371. }
  103372. function addProjToQueue(_a, proj, reloadLevel) {
  103373. var projectPendingBuild = _a.projectPendingBuild;
  103374. var value = projectPendingBuild.get(proj);
  103375. if (value === undefined) {
  103376. projectPendingBuild.set(proj, reloadLevel);
  103377. }
  103378. else if (value < reloadLevel) {
  103379. projectPendingBuild.set(proj, reloadLevel);
  103380. }
  103381. }
  103382. function setupInitialBuild(state, cancellationToken) {
  103383. // Set initial build if not already built
  103384. if (!state.allProjectBuildPending)
  103385. return;
  103386. state.allProjectBuildPending = false;
  103387. if (state.options.watch) {
  103388. reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
  103389. }
  103390. enableCache(state);
  103391. var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
  103392. buildOrder.forEach(function (configFileName) {
  103393. return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
  103394. });
  103395. if (cancellationToken) {
  103396. cancellationToken.throwIfCancellationRequested();
  103397. }
  103398. }
  103399. var InvalidatedProjectKind;
  103400. (function (InvalidatedProjectKind) {
  103401. InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
  103402. InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
  103403. InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
  103404. })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
  103405. function doneInvalidatedProject(state, projectPath) {
  103406. state.projectPendingBuild.delete(projectPath);
  103407. state.currentInvalidatedProject = undefined;
  103408. return state.diagnostics.has(projectPath) ?
  103409. ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
  103410. ts.ExitStatus.Success;
  103411. }
  103412. function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
  103413. var updateOutputFileStampsPending = true;
  103414. return {
  103415. kind: InvalidatedProjectKind.UpdateOutputFileStamps,
  103416. project: project,
  103417. projectPath: projectPath,
  103418. buildOrder: buildOrder,
  103419. getCompilerOptions: function () { return config.options; },
  103420. getCurrentDirectory: function () { return state.currentDirectory; },
  103421. updateOutputFileStatmps: function () {
  103422. updateOutputTimestamps(state, config, projectPath);
  103423. updateOutputFileStampsPending = false;
  103424. },
  103425. done: function () {
  103426. if (updateOutputFileStampsPending) {
  103427. updateOutputTimestamps(state, config, projectPath);
  103428. }
  103429. return doneInvalidatedProject(state, projectPath);
  103430. }
  103431. };
  103432. }
  103433. function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
  103434. var Step;
  103435. (function (Step) {
  103436. Step[Step["CreateProgram"] = 0] = "CreateProgram";
  103437. Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
  103438. Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
  103439. Step[Step["Emit"] = 3] = "Emit";
  103440. Step[Step["EmitBundle"] = 4] = "EmitBundle";
  103441. Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
  103442. Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
  103443. Step[Step["Done"] = 7] = "Done";
  103444. })(Step || (Step = {}));
  103445. var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
  103446. var program;
  103447. var buildResult;
  103448. var invalidatedProjectOfBundle;
  103449. return kind === InvalidatedProjectKind.Build ?
  103450. {
  103451. kind: kind,
  103452. project: project,
  103453. projectPath: projectPath,
  103454. buildOrder: buildOrder,
  103455. getCompilerOptions: function () { return config.options; },
  103456. getCurrentDirectory: function () { return state.currentDirectory; },
  103457. getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
  103458. getProgram: function () {
  103459. return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
  103460. },
  103461. getSourceFile: function (fileName) {
  103462. return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
  103463. },
  103464. getSourceFiles: function () {
  103465. return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
  103466. },
  103467. getOptionsDiagnostics: function (cancellationToken) {
  103468. return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
  103469. },
  103470. getGlobalDiagnostics: function (cancellationToken) {
  103471. return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
  103472. },
  103473. getConfigFileParsingDiagnostics: function () {
  103474. return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
  103475. },
  103476. getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
  103477. return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
  103478. },
  103479. getAllDependencies: function (sourceFile) {
  103480. return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
  103481. },
  103482. getSemanticDiagnostics: function (sourceFile, cancellationToken) {
  103483. return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
  103484. },
  103485. getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
  103486. return withProgramOrUndefined(function (program) {
  103487. return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
  103488. program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
  103489. });
  103490. },
  103491. emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  103492. if (targetSourceFile || emitOnlyDtsFiles) {
  103493. return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
  103494. }
  103495. executeSteps(Step.SemanticDiagnostics, cancellationToken);
  103496. if (step !== Step.Emit)
  103497. return undefined;
  103498. return emit(writeFile, cancellationToken, customTransformers);
  103499. },
  103500. done: done
  103501. } :
  103502. {
  103503. kind: kind,
  103504. project: project,
  103505. projectPath: projectPath,
  103506. buildOrder: buildOrder,
  103507. getCompilerOptions: function () { return config.options; },
  103508. getCurrentDirectory: function () { return state.currentDirectory; },
  103509. emit: function (writeFile, customTransformers) {
  103510. if (step !== Step.EmitBundle)
  103511. return invalidatedProjectOfBundle;
  103512. return emitBundle(writeFile, customTransformers);
  103513. },
  103514. done: done,
  103515. };
  103516. function done(cancellationToken, writeFile, customTransformers) {
  103517. executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
  103518. return doneInvalidatedProject(state, projectPath);
  103519. }
  103520. function withProgramOrUndefined(action) {
  103521. executeSteps(Step.CreateProgram);
  103522. return program && action(program);
  103523. }
  103524. function withProgramOrEmptyArray(action) {
  103525. return withProgramOrUndefined(action) || ts.emptyArray;
  103526. }
  103527. function createProgram() {
  103528. ts.Debug.assert(program === undefined);
  103529. if (state.options.dry) {
  103530. reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
  103531. buildResult = BuildResultFlags.Success;
  103532. step = Step.QueueReferencingProjects;
  103533. return;
  103534. }
  103535. if (state.options.verbose)
  103536. reportStatus(state, ts.Diagnostics.Building_project_0, project);
  103537. if (config.fileNames.length === 0) {
  103538. reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
  103539. // Nothing to build - must be a solution file, basically
  103540. buildResult = BuildResultFlags.None;
  103541. step = Step.QueueReferencingProjects;
  103542. return;
  103543. }
  103544. var host = state.host, compilerHost = state.compilerHost;
  103545. state.projectCompilerOptions = config.options;
  103546. // Update module resolution cache if needed
  103547. updateModuleResolutionCache(state, project, config);
  103548. // Create program
  103549. program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
  103550. step++;
  103551. }
  103552. function handleDiagnostics(diagnostics, errorFlags, errorType) {
  103553. if (diagnostics.length) {
  103554. buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
  103555. step = Step.QueueReferencingProjects;
  103556. }
  103557. else {
  103558. step++;
  103559. }
  103560. }
  103561. function getSyntaxDiagnostics(cancellationToken) {
  103562. ts.Debug.assertDefined(program);
  103563. handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
  103564. }
  103565. function getSemanticDiagnostics(cancellationToken) {
  103566. handleDiagnostics(ts.Debug.assertDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
  103567. }
  103568. function emit(writeFileCallback, cancellationToken, customTransformers) {
  103569. ts.Debug.assertDefined(program);
  103570. ts.Debug.assert(step === Step.Emit);
  103571. // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
  103572. program.backupState();
  103573. var declDiagnostics;
  103574. var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
  103575. var outputFiles = [];
  103576. var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics,
  103577. /*writeFileName*/ undefined,
  103578. /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken,
  103579. /*emitOnlyDts*/ false, customTransformers).emitResult;
  103580. // Don't emit .d.ts if there are decl file errors
  103581. if (declDiagnostics) {
  103582. program.restoreState();
  103583. buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
  103584. step = Step.QueueReferencingProjects;
  103585. return {
  103586. emitSkipped: true,
  103587. diagnostics: emitResult.diagnostics
  103588. };
  103589. }
  103590. // Actual Emit
  103591. var host = state.host, compilerHost = state.compilerHost;
  103592. var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
  103593. var newestDeclarationFileContentChangedTime = minimumDate;
  103594. var anyDtsChanged = false;
  103595. var emitterDiagnostics = ts.createDiagnosticCollection();
  103596. var emittedOutputs = ts.createMap();
  103597. outputFiles.forEach(function (_a) {
  103598. var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
  103599. var priorChangeTime;
  103600. if (!anyDtsChanged && isDeclarationFile(name)) {
  103601. // Check for unchanged .d.ts files
  103602. if (host.fileExists(name) && state.readFileWithCache(name) === text) {
  103603. priorChangeTime = host.getModifiedTime(name);
  103604. }
  103605. else {
  103606. resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
  103607. anyDtsChanged = true;
  103608. }
  103609. }
  103610. emittedOutputs.set(toPath(state, name), name);
  103611. ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
  103612. if (priorChangeTime !== undefined) {
  103613. newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
  103614. }
  103615. });
  103616. finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime,
  103617. /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
  103618. return emitResult;
  103619. }
  103620. function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
  103621. var emitDiagnostics = emitterDiagnostics.getDiagnostics();
  103622. if (emitDiagnostics.length) {
  103623. buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
  103624. step = Step.QueueReferencingProjects;
  103625. return emitDiagnostics;
  103626. }
  103627. if (state.writeFileName) {
  103628. emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
  103629. if (program)
  103630. ts.listFiles(program, state.writeFileName);
  103631. }
  103632. // Update time stamps for rest of the outputs
  103633. var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
  103634. state.diagnostics.delete(projectPath);
  103635. state.projectStatus.set(projectPath, {
  103636. type: ts.UpToDateStatusType.UpToDate,
  103637. newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
  103638. maximumDate :
  103639. newestDeclarationFileContentChangedTime,
  103640. oldestOutputFileName: oldestOutputFileName
  103641. });
  103642. afterProgramDone(state, projectPath, program, config);
  103643. state.projectCompilerOptions = state.baseCompilerOptions;
  103644. step = Step.QueueReferencingProjects;
  103645. buildResult = resultFlags;
  103646. return emitDiagnostics;
  103647. }
  103648. function emitBundle(writeFileCallback, customTransformers) {
  103649. ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
  103650. if (state.options.dry) {
  103651. reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
  103652. buildResult = BuildResultFlags.Success;
  103653. step = Step.QueueReferencingProjects;
  103654. return undefined;
  103655. }
  103656. if (state.options.verbose)
  103657. reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
  103658. // Update js, and source map
  103659. var compilerHost = state.compilerHost;
  103660. state.projectCompilerOptions = config.options;
  103661. var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
  103662. var refName = resolveProjectName(state, ref.path);
  103663. return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
  103664. }, customTransformers);
  103665. if (ts.isString(outputFiles)) {
  103666. reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
  103667. step = Step.BuildInvalidatedProjectOfBundle;
  103668. return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
  103669. }
  103670. // Actual Emit
  103671. ts.Debug.assert(!!outputFiles.length);
  103672. var emitterDiagnostics = ts.createDiagnosticCollection();
  103673. var emittedOutputs = ts.createMap();
  103674. outputFiles.forEach(function (_a) {
  103675. var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
  103676. emittedOutputs.set(toPath(state, name), name);
  103677. ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
  103678. });
  103679. var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate,
  103680. /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
  103681. return { emitSkipped: false, diagnostics: emitDiagnostics };
  103682. }
  103683. function executeSteps(till, cancellationToken, writeFile, customTransformers) {
  103684. while (step <= till && step < Step.Done) {
  103685. var currentStep = step;
  103686. switch (step) {
  103687. case Step.CreateProgram:
  103688. createProgram();
  103689. break;
  103690. case Step.SyntaxDiagnostics:
  103691. getSyntaxDiagnostics(cancellationToken);
  103692. break;
  103693. case Step.SemanticDiagnostics:
  103694. getSemanticDiagnostics(cancellationToken);
  103695. break;
  103696. case Step.Emit:
  103697. emit(writeFile, cancellationToken, customTransformers);
  103698. break;
  103699. case Step.EmitBundle:
  103700. emitBundle(writeFile, customTransformers);
  103701. break;
  103702. case Step.BuildInvalidatedProjectOfBundle:
  103703. ts.Debug.assertDefined(invalidatedProjectOfBundle).done(cancellationToken);
  103704. step = Step.Done;
  103705. break;
  103706. case Step.QueueReferencingProjects:
  103707. queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.assertDefined(buildResult));
  103708. step++;
  103709. break;
  103710. // Should never be done
  103711. case Step.Done:
  103712. default:
  103713. ts.assertType(step);
  103714. }
  103715. ts.Debug.assert(step > currentStep);
  103716. }
  103717. }
  103718. }
  103719. function needsBuild(_a, status, config) {
  103720. var options = _a.options;
  103721. if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
  103722. return true;
  103723. return config.fileNames.length === 0 ||
  103724. !!ts.getConfigFileParsingDiagnostics(config).length ||
  103725. !ts.isIncrementalCompilation(config.options);
  103726. }
  103727. function getNextInvalidatedProject(state, buildOrder, reportQueue) {
  103728. if (!state.projectPendingBuild.size)
  103729. return undefined;
  103730. if (isCircularBuildOrder(buildOrder))
  103731. return undefined;
  103732. if (state.currentInvalidatedProject) {
  103733. // Only if same buildOrder the currentInvalidated project can be sent again
  103734. return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
  103735. state.currentInvalidatedProject :
  103736. undefined;
  103737. }
  103738. var options = state.options, projectPendingBuild = state.projectPendingBuild;
  103739. for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
  103740. var project = buildOrder[projectIndex];
  103741. var projectPath = toResolvedConfigFilePath(state, project);
  103742. var reloadLevel = state.projectPendingBuild.get(projectPath);
  103743. if (reloadLevel === undefined)
  103744. continue;
  103745. if (reportQueue) {
  103746. reportQueue = false;
  103747. reportBuildQueue(state, buildOrder);
  103748. }
  103749. var config = parseConfigFile(state, project, projectPath);
  103750. if (!config) {
  103751. reportParseConfigFileDiagnostic(state, projectPath);
  103752. projectPendingBuild.delete(projectPath);
  103753. continue;
  103754. }
  103755. if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
  103756. watchConfigFile(state, project, projectPath, config);
  103757. watchWildCardDirectories(state, project, projectPath, config);
  103758. watchInputFiles(state, project, projectPath, config);
  103759. }
  103760. else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
  103761. // Update file names
  103762. var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
  103763. ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
  103764. config.fileNames = result.fileNames;
  103765. watchInputFiles(state, project, projectPath, config);
  103766. }
  103767. var status = getUpToDateStatus(state, config, projectPath);
  103768. verboseReportProjectStatus(state, project, status);
  103769. if (!options.force) {
  103770. if (status.type === ts.UpToDateStatusType.UpToDate) {
  103771. reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
  103772. projectPendingBuild.delete(projectPath);
  103773. // Up to date, skip
  103774. if (options.dry) {
  103775. // In a dry build, inform the user of this fact
  103776. reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
  103777. }
  103778. continue;
  103779. }
  103780. if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
  103781. reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
  103782. return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
  103783. }
  103784. }
  103785. if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
  103786. reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
  103787. projectPendingBuild.delete(projectPath);
  103788. if (options.verbose) {
  103789. reportStatus(state, status.upstreamProjectBlocked ?
  103790. ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
  103791. ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
  103792. }
  103793. continue;
  103794. }
  103795. if (status.type === ts.UpToDateStatusType.ContainerOnly) {
  103796. reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
  103797. projectPendingBuild.delete(projectPath);
  103798. // Do nothing
  103799. continue;
  103800. }
  103801. return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
  103802. InvalidatedProjectKind.Build :
  103803. InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
  103804. }
  103805. return undefined;
  103806. }
  103807. function listEmittedFile(_a, proj, file) {
  103808. var writeFileName = _a.writeFileName;
  103809. if (writeFileName && proj.options.listEmittedFiles) {
  103810. writeFileName("TSFILE: " + file);
  103811. }
  103812. }
  103813. function getOldProgram(_a, proj, parsed) {
  103814. var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
  103815. if (options.force)
  103816. return undefined;
  103817. var value = builderPrograms.get(proj);
  103818. if (value)
  103819. return value;
  103820. return ts.readBuilderProgram(parsed.options, compilerHost);
  103821. }
  103822. function afterProgramDone(_a, proj, program, config) {
  103823. var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
  103824. if (program) {
  103825. if (host.afterProgramEmitAndDiagnostics) {
  103826. host.afterProgramEmitAndDiagnostics(program);
  103827. }
  103828. if (watch) {
  103829. program.releaseProgram();
  103830. builderPrograms.set(proj, program);
  103831. }
  103832. }
  103833. else if (host.afterEmitBundle) {
  103834. host.afterEmitBundle(config);
  103835. }
  103836. }
  103837. function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
  103838. reportAndStoreErrors(state, resolvedPath, diagnostics);
  103839. // List files if any other build error using program (emit errors already report files)
  103840. if (program && state.writeFileName)
  103841. ts.listFiles(program, state.writeFileName);
  103842. state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
  103843. afterProgramDone(state, resolvedPath, program, config);
  103844. state.projectCompilerOptions = state.baseCompilerOptions;
  103845. return errorFlags;
  103846. }
  103847. function updateModuleResolutionCache(state, proj, config) {
  103848. if (!state.moduleResolutionCache)
  103849. return;
  103850. // Update module resolution cache if needed
  103851. var moduleResolutionCache = state.moduleResolutionCache;
  103852. var projPath = toPath(state, proj);
  103853. if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
  103854. // The own map will be for projectCompilerOptions
  103855. ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
  103856. moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
  103857. moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
  103858. }
  103859. else {
  103860. // Set correct own map
  103861. ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
  103862. var ref = {
  103863. sourceFile: config.options.configFile,
  103864. commandLine: config
  103865. };
  103866. moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
  103867. moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
  103868. }
  103869. moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
  103870. moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
  103871. }
  103872. function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
  103873. // Check tsconfig time
  103874. var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
  103875. if (oldestOutputFileTime < tsconfigTime) {
  103876. return {
  103877. type: ts.UpToDateStatusType.OutOfDateWithSelf,
  103878. outOfDateOutputFileName: oldestOutputFileName,
  103879. newerInputFileName: configFile
  103880. };
  103881. }
  103882. }
  103883. function getUpToDateStatusWorker(state, project, resolvedPath) {
  103884. var newestInputFileName = undefined;
  103885. var newestInputFileTime = minimumDate;
  103886. var host = state.host;
  103887. // Get timestamps of input files
  103888. for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
  103889. var inputFile = _a[_i];
  103890. if (!host.fileExists(inputFile)) {
  103891. return {
  103892. type: ts.UpToDateStatusType.Unbuildable,
  103893. reason: inputFile + " does not exist"
  103894. };
  103895. }
  103896. var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
  103897. if (inputTime > newestInputFileTime) {
  103898. newestInputFileName = inputFile;
  103899. newestInputFileTime = inputTime;
  103900. }
  103901. }
  103902. // Container if no files are specified in the project
  103903. if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
  103904. return {
  103905. type: ts.UpToDateStatusType.ContainerOnly
  103906. };
  103907. }
  103908. // Collect the expected outputs of this project
  103909. var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
  103910. // Now see if all outputs are newer than the newest input
  103911. var oldestOutputFileName = "(none)";
  103912. var oldestOutputFileTime = maximumDate;
  103913. var newestOutputFileName = "(none)";
  103914. var newestOutputFileTime = minimumDate;
  103915. var missingOutputFileName;
  103916. var newestDeclarationFileContentChangedTime = minimumDate;
  103917. var isOutOfDateWithInputs = false;
  103918. for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
  103919. var output = outputs_1[_b];
  103920. // Output is missing; can stop checking
  103921. // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
  103922. if (!host.fileExists(output)) {
  103923. missingOutputFileName = output;
  103924. break;
  103925. }
  103926. var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
  103927. if (outputTime < oldestOutputFileTime) {
  103928. oldestOutputFileTime = outputTime;
  103929. oldestOutputFileName = output;
  103930. }
  103931. // If an output is older than the newest input, we can stop checking
  103932. // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
  103933. if (outputTime < newestInputFileTime) {
  103934. isOutOfDateWithInputs = true;
  103935. break;
  103936. }
  103937. if (outputTime > newestOutputFileTime) {
  103938. newestOutputFileTime = outputTime;
  103939. newestOutputFileName = output;
  103940. }
  103941. // Keep track of when the most recent time a .d.ts file was changed.
  103942. // In addition to file timestamps, we also keep track of when a .d.ts file
  103943. // had its file touched but not had its contents changed - this allows us
  103944. // to skip a downstream typecheck
  103945. if (isDeclarationFile(output)) {
  103946. var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
  103947. newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
  103948. }
  103949. }
  103950. var pseudoUpToDate = false;
  103951. var usesPrepend = false;
  103952. var upstreamChangedProject;
  103953. if (project.projectReferences) {
  103954. state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
  103955. for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
  103956. var ref = _d[_c];
  103957. usesPrepend = usesPrepend || !!(ref.prepend);
  103958. var resolvedRef = ts.resolveProjectReferencePath(ref);
  103959. var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
  103960. var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
  103961. // Its a circular reference ignore the status of this project
  103962. if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
  103963. refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
  103964. continue;
  103965. }
  103966. // An upstream project is blocked
  103967. if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
  103968. refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
  103969. return {
  103970. type: ts.UpToDateStatusType.UpstreamBlocked,
  103971. upstreamProjectName: ref.path,
  103972. upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
  103973. };
  103974. }
  103975. // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
  103976. if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
  103977. return {
  103978. type: ts.UpToDateStatusType.UpstreamOutOfDate,
  103979. upstreamProjectName: ref.path
  103980. };
  103981. }
  103982. // Check oldest output file name only if there is no missing output file name
  103983. if (!missingOutputFileName) {
  103984. // If the upstream project's newest file is older than our oldest output, we
  103985. // can't be out of date because of it
  103986. if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
  103987. continue;
  103988. }
  103989. // If the upstream project has only change .d.ts files, and we've built
  103990. // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
  103991. if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
  103992. pseudoUpToDate = true;
  103993. upstreamChangedProject = ref.path;
  103994. continue;
  103995. }
  103996. // We have an output older than an upstream output - we are out of date
  103997. ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
  103998. return {
  103999. type: ts.UpToDateStatusType.OutOfDateWithUpstream,
  104000. outOfDateOutputFileName: oldestOutputFileName,
  104001. newerProjectName: ref.path
  104002. };
  104003. }
  104004. }
  104005. }
  104006. if (missingOutputFileName !== undefined) {
  104007. return {
  104008. type: ts.UpToDateStatusType.OutputMissing,
  104009. missingOutputFileName: missingOutputFileName
  104010. };
  104011. }
  104012. if (isOutOfDateWithInputs) {
  104013. return {
  104014. type: ts.UpToDateStatusType.OutOfDateWithSelf,
  104015. outOfDateOutputFileName: oldestOutputFileName,
  104016. newerInputFileName: newestInputFileName
  104017. };
  104018. }
  104019. else {
  104020. // Check tsconfig time
  104021. var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
  104022. if (configStatus)
  104023. return configStatus;
  104024. // Check extended config time
  104025. var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
  104026. if (extendedConfigStatus)
  104027. return extendedConfigStatus;
  104028. }
  104029. if (!state.buildInfoChecked.has(resolvedPath)) {
  104030. state.buildInfoChecked.set(resolvedPath, true);
  104031. var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
  104032. if (buildInfoPath) {
  104033. var value = state.readFileWithCache(buildInfoPath);
  104034. var buildInfo = value && ts.getBuildInfo(value);
  104035. if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
  104036. return {
  104037. type: ts.UpToDateStatusType.TsVersionOutputOfDate,
  104038. version: buildInfo.version
  104039. };
  104040. }
  104041. }
  104042. }
  104043. if (usesPrepend && pseudoUpToDate) {
  104044. return {
  104045. type: ts.UpToDateStatusType.OutOfDateWithPrepend,
  104046. outOfDateOutputFileName: oldestOutputFileName,
  104047. newerProjectName: upstreamChangedProject
  104048. };
  104049. }
  104050. // Up to date
  104051. return {
  104052. type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
  104053. newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
  104054. newestInputFileTime: newestInputFileTime,
  104055. newestOutputFileTime: newestOutputFileTime,
  104056. newestInputFileName: newestInputFileName,
  104057. newestOutputFileName: newestOutputFileName,
  104058. oldestOutputFileName: oldestOutputFileName
  104059. };
  104060. }
  104061. function getUpToDateStatus(state, project, resolvedPath) {
  104062. if (project === undefined) {
  104063. return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
  104064. }
  104065. var prior = state.projectStatus.get(resolvedPath);
  104066. if (prior !== undefined) {
  104067. return prior;
  104068. }
  104069. var actual = getUpToDateStatusWorker(state, project, resolvedPath);
  104070. state.projectStatus.set(resolvedPath, actual);
  104071. return actual;
  104072. }
  104073. function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
  104074. var host = state.host;
  104075. var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
  104076. if (!skipOutputs || outputs.length !== skipOutputs.size) {
  104077. var reportVerbose = !!state.options.verbose;
  104078. var now = host.now ? host.now() : new Date();
  104079. for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
  104080. var file = outputs_2[_i];
  104081. if (skipOutputs && skipOutputs.has(toPath(state, file))) {
  104082. continue;
  104083. }
  104084. if (reportVerbose) {
  104085. reportVerbose = false;
  104086. reportStatus(state, verboseMessage, proj.options.configFilePath);
  104087. }
  104088. if (isDeclarationFile(file)) {
  104089. priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
  104090. }
  104091. host.setModifiedTime(file, now);
  104092. }
  104093. }
  104094. return priorNewestUpdateTime;
  104095. }
  104096. function updateOutputTimestamps(state, proj, resolvedPath) {
  104097. if (state.options.dry) {
  104098. return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
  104099. }
  104100. var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
  104101. state.projectStatus.set(resolvedPath, {
  104102. type: ts.UpToDateStatusType.UpToDate,
  104103. newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
  104104. oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
  104105. });
  104106. }
  104107. function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
  104108. // Queue only if there are no errors
  104109. if (buildResult & BuildResultFlags.AnyErrors)
  104110. return;
  104111. // Only composite projects can be referenced by other projects
  104112. if (!config.options.composite)
  104113. return;
  104114. // Always use build order to queue projects
  104115. for (var index = projectIndex + 1; index < buildOrder.length; index++) {
  104116. var nextProject = buildOrder[index];
  104117. var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
  104118. if (state.projectPendingBuild.has(nextProjectPath))
  104119. continue;
  104120. var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
  104121. if (!nextProjectConfig || !nextProjectConfig.projectReferences)
  104122. continue;
  104123. for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
  104124. var ref = _a[_i];
  104125. var resolvedRefPath = resolveProjectName(state, ref.path);
  104126. if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
  104127. continue;
  104128. // If the project is referenced with prepend, always build downstream projects,
  104129. // If declaration output is changed, build the project
  104130. // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
  104131. var status = state.projectStatus.get(nextProjectPath);
  104132. if (status) {
  104133. switch (status.type) {
  104134. case ts.UpToDateStatusType.UpToDate:
  104135. if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
  104136. if (ref.prepend) {
  104137. state.projectStatus.set(nextProjectPath, {
  104138. type: ts.UpToDateStatusType.OutOfDateWithPrepend,
  104139. outOfDateOutputFileName: status.oldestOutputFileName,
  104140. newerProjectName: project
  104141. });
  104142. }
  104143. else {
  104144. status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
  104145. }
  104146. break;
  104147. }
  104148. // falls through
  104149. case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
  104150. case ts.UpToDateStatusType.OutOfDateWithPrepend:
  104151. if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
  104152. state.projectStatus.set(nextProjectPath, {
  104153. type: ts.UpToDateStatusType.OutOfDateWithUpstream,
  104154. outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
  104155. newerProjectName: project
  104156. });
  104157. }
  104158. break;
  104159. case ts.UpToDateStatusType.UpstreamBlocked:
  104160. if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
  104161. clearProjectStatus(state, nextProjectPath);
  104162. }
  104163. break;
  104164. }
  104165. }
  104166. addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
  104167. break;
  104168. }
  104169. }
  104170. }
  104171. function build(state, project, cancellationToken, onlyReferences) {
  104172. var buildOrder = getBuildOrderFor(state, project, onlyReferences);
  104173. if (!buildOrder)
  104174. return ts.ExitStatus.InvalidProject_OutputsSkipped;
  104175. setupInitialBuild(state, cancellationToken);
  104176. var reportQueue = true;
  104177. var successfulProjects = 0;
  104178. while (true) {
  104179. var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
  104180. if (!invalidatedProject)
  104181. break;
  104182. reportQueue = false;
  104183. invalidatedProject.done(cancellationToken);
  104184. if (!state.diagnostics.has(invalidatedProject.projectPath))
  104185. successfulProjects++;
  104186. }
  104187. disableCache(state);
  104188. reportErrorSummary(state, buildOrder);
  104189. startWatching(state, buildOrder);
  104190. return isCircularBuildOrder(buildOrder)
  104191. ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
  104192. : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
  104193. ? ts.ExitStatus.Success
  104194. : successfulProjects
  104195. ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
  104196. : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
  104197. }
  104198. function clean(state, project, onlyReferences) {
  104199. var buildOrder = getBuildOrderFor(state, project, onlyReferences);
  104200. if (!buildOrder)
  104201. return ts.ExitStatus.InvalidProject_OutputsSkipped;
  104202. if (isCircularBuildOrder(buildOrder)) {
  104203. reportErrors(state, buildOrder.circularDiagnostics);
  104204. return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
  104205. }
  104206. var options = state.options, host = state.host;
  104207. var filesToDelete = options.dry ? [] : undefined;
  104208. for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
  104209. var proj = buildOrder_1[_i];
  104210. var resolvedPath = toResolvedConfigFilePath(state, proj);
  104211. var parsed = parseConfigFile(state, proj, resolvedPath);
  104212. if (parsed === undefined) {
  104213. // File has gone missing; fine to ignore here
  104214. reportParseConfigFileDiagnostic(state, resolvedPath);
  104215. continue;
  104216. }
  104217. var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
  104218. for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
  104219. var output = outputs_3[_a];
  104220. if (host.fileExists(output)) {
  104221. if (filesToDelete) {
  104222. filesToDelete.push(output);
  104223. }
  104224. else {
  104225. host.deleteFile(output);
  104226. invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
  104227. }
  104228. }
  104229. }
  104230. }
  104231. if (filesToDelete) {
  104232. reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
  104233. }
  104234. return ts.ExitStatus.Success;
  104235. }
  104236. function invalidateProject(state, resolved, reloadLevel) {
  104237. // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
  104238. if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
  104239. reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
  104240. }
  104241. if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
  104242. state.configFileCache.delete(resolved);
  104243. state.buildOrder = undefined;
  104244. }
  104245. state.needsSummary = true;
  104246. clearProjectStatus(state, resolved);
  104247. addProjToQueue(state, resolved, reloadLevel);
  104248. enableCache(state);
  104249. }
  104250. function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
  104251. state.reportFileChangeDetected = true;
  104252. invalidateProject(state, resolvedPath, reloadLevel);
  104253. scheduleBuildInvalidatedProject(state);
  104254. }
  104255. function scheduleBuildInvalidatedProject(state) {
  104256. var hostWithWatch = state.hostWithWatch;
  104257. if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
  104258. return;
  104259. }
  104260. if (state.timerToBuildInvalidatedProject) {
  104261. hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
  104262. }
  104263. state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
  104264. }
  104265. function buildNextInvalidatedProject(state) {
  104266. state.timerToBuildInvalidatedProject = undefined;
  104267. if (state.reportFileChangeDetected) {
  104268. state.reportFileChangeDetected = false;
  104269. state.projectErrorsReported.clear();
  104270. reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
  104271. }
  104272. var buildOrder = getBuildOrder(state);
  104273. var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
  104274. if (invalidatedProject) {
  104275. invalidatedProject.done();
  104276. if (state.projectPendingBuild.size) {
  104277. // Schedule next project for build
  104278. if (state.watch && !state.timerToBuildInvalidatedProject) {
  104279. scheduleBuildInvalidatedProject(state);
  104280. }
  104281. return;
  104282. }
  104283. }
  104284. disableCache(state);
  104285. reportErrorSummary(state, buildOrder);
  104286. }
  104287. function watchConfigFile(state, resolved, resolvedPath, parsed) {
  104288. if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
  104289. return;
  104290. state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
  104291. invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
  104292. }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
  104293. }
  104294. function isSameFile(state, file1, file2) {
  104295. return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
  104296. }
  104297. function isOutputFile(state, fileName, configFile) {
  104298. if (configFile.options.noEmit)
  104299. return false;
  104300. // ts or tsx files are not output
  104301. if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
  104302. (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
  104303. return false;
  104304. }
  104305. // If options have --outFile or --out, check if its that
  104306. var out = configFile.options.outFile || configFile.options.out;
  104307. if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
  104308. return true;
  104309. }
  104310. // If declarationDir is specified, return if its a file in that directory
  104311. if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
  104312. return true;
  104313. }
  104314. // If --outDir, check if file is in that directory
  104315. if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
  104316. return true;
  104317. }
  104318. return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
  104319. }
  104320. function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
  104321. if (!state.watch)
  104322. return;
  104323. ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
  104324. var fileOrDirectoryPath = toPath(state, fileOrDirectory);
  104325. if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
  104326. state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
  104327. return;
  104328. }
  104329. if (isOutputFile(state, fileOrDirectory, parsed)) {
  104330. state.writeLog(fileOrDirectory + " is output file");
  104331. return;
  104332. }
  104333. invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
  104334. }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
  104335. }
  104336. function watchInputFiles(state, resolved, resolvedPath, parsed) {
  104337. if (!state.watch)
  104338. return;
  104339. ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
  104340. createNewValue: function (path, input) { return state.watchFilePath(state.hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, path, ts.WatchType.SourceFile, resolved); },
  104341. onDeleteValue: ts.closeFileWatcher,
  104342. });
  104343. }
  104344. function startWatching(state, buildOrder) {
  104345. if (!state.watchAllProjectsPending)
  104346. return;
  104347. state.watchAllProjectsPending = false;
  104348. for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
  104349. var resolved = _a[_i];
  104350. var resolvedPath = toResolvedConfigFilePath(state, resolved);
  104351. var cfg = parseConfigFile(state, resolved, resolvedPath);
  104352. // Watch this file
  104353. watchConfigFile(state, resolved, resolvedPath, cfg);
  104354. if (cfg) {
  104355. // Update watchers for wildcard directories
  104356. watchWildCardDirectories(state, resolved, resolvedPath, cfg);
  104357. // Watch input files
  104358. watchInputFiles(state, resolved, resolvedPath, cfg);
  104359. }
  104360. }
  104361. }
  104362. function stopWatching(state) {
  104363. ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
  104364. ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
  104365. ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
  104366. }
  104367. function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
  104368. var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
  104369. return {
  104370. build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
  104371. clean: function (project) { return clean(state, project); },
  104372. buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
  104373. cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
  104374. getNextInvalidatedProject: function (cancellationToken) {
  104375. setupInitialBuild(state, cancellationToken);
  104376. return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
  104377. },
  104378. getBuildOrder: function () { return getBuildOrder(state); },
  104379. getUpToDateStatusOfProject: function (project) {
  104380. var configFileName = resolveProjectName(state, project);
  104381. var configFilePath = toResolvedConfigFilePath(state, configFileName);
  104382. return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
  104383. },
  104384. invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
  104385. buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
  104386. getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
  104387. close: function () { return stopWatching(state); },
  104388. };
  104389. }
  104390. function relName(state, path) {
  104391. return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
  104392. }
  104393. function reportStatus(state, message) {
  104394. var args = [];
  104395. for (var _i = 2; _i < arguments.length; _i++) {
  104396. args[_i - 2] = arguments[_i];
  104397. }
  104398. state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
  104399. }
  104400. function reportWatchStatus(state, message) {
  104401. var args = [];
  104402. for (var _i = 2; _i < arguments.length; _i++) {
  104403. args[_i - 2] = arguments[_i];
  104404. }
  104405. if (state.hostWithWatch.onWatchStatusChange) {
  104406. state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
  104407. }
  104408. }
  104409. function reportErrors(_a, errors) {
  104410. var host = _a.host;
  104411. errors.forEach(function (err) { return host.reportDiagnostic(err); });
  104412. }
  104413. function reportAndStoreErrors(state, proj, errors) {
  104414. reportErrors(state, errors);
  104415. state.projectErrorsReported.set(proj, true);
  104416. if (errors.length) {
  104417. state.diagnostics.set(proj, errors);
  104418. }
  104419. }
  104420. function reportParseConfigFileDiagnostic(state, proj) {
  104421. reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
  104422. }
  104423. function reportErrorSummary(state, buildOrder) {
  104424. if (!state.needsSummary)
  104425. return;
  104426. state.needsSummary = false;
  104427. var canReportSummary = state.watch || !!state.host.reportErrorSummary;
  104428. var diagnostics = state.diagnostics;
  104429. var totalErrors = 0;
  104430. if (isCircularBuildOrder(buildOrder)) {
  104431. reportBuildQueue(state, buildOrder.buildOrder);
  104432. reportErrors(state, buildOrder.circularDiagnostics);
  104433. if (canReportSummary)
  104434. totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
  104435. }
  104436. else {
  104437. // Report errors from the other projects
  104438. buildOrder.forEach(function (project) {
  104439. var projectPath = toResolvedConfigFilePath(state, project);
  104440. if (!state.projectErrorsReported.has(projectPath)) {
  104441. reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
  104442. }
  104443. });
  104444. if (canReportSummary)
  104445. diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
  104446. }
  104447. if (state.watch) {
  104448. reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
  104449. }
  104450. else if (state.host.reportErrorSummary) {
  104451. state.host.reportErrorSummary(totalErrors);
  104452. }
  104453. }
  104454. /**
  104455. * Report the build ordering inferred from the current project graph if we're in verbose mode
  104456. */
  104457. function reportBuildQueue(state, buildQueue) {
  104458. if (state.options.verbose) {
  104459. reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n * " + relName(state, s); }).join(""));
  104460. }
  104461. }
  104462. function reportUpToDateStatus(state, configFileName, status) {
  104463. switch (status.type) {
  104464. case ts.UpToDateStatusType.OutOfDateWithSelf:
  104465. return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName));
  104466. case ts.UpToDateStatusType.OutOfDateWithUpstream:
  104467. return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName));
  104468. case ts.UpToDateStatusType.OutputMissing:
  104469. return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName));
  104470. case ts.UpToDateStatusType.UpToDate:
  104471. if (status.newestInputFileTime !== undefined) {
  104472. return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || ""));
  104473. }
  104474. // Don't report anything for "up to date because it was already built" -- too verbose
  104475. break;
  104476. case ts.UpToDateStatusType.OutOfDateWithPrepend:
  104477. return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName));
  104478. case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
  104479. return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
  104480. case ts.UpToDateStatusType.UpstreamOutOfDate:
  104481. return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName));
  104482. case ts.UpToDateStatusType.UpstreamBlocked:
  104483. return reportStatus(state, status.upstreamProjectBlocked ?
  104484. ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
  104485. ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
  104486. case ts.UpToDateStatusType.Unbuildable:
  104487. return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
  104488. case ts.UpToDateStatusType.TsVersionOutputOfDate:
  104489. return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version);
  104490. case ts.UpToDateStatusType.ContainerOnly:
  104491. // Don't report status on "solution" projects
  104492. // falls through
  104493. case ts.UpToDateStatusType.ComputingUpstream:
  104494. // Should never leak from getUptoDateStatusWorker
  104495. break;
  104496. default:
  104497. ts.assertType(status);
  104498. }
  104499. }
  104500. /**
  104501. * Report the up-to-date status of a project if we're in verbose mode
  104502. */
  104503. function verboseReportProjectStatus(state, configFileName, status) {
  104504. if (state.options.verbose) {
  104505. reportUpToDateStatus(state, configFileName, status);
  104506. }
  104507. }
  104508. })(ts || (ts = {}));
  104509. var ts;
  104510. (function (ts) {
  104511. var server;
  104512. (function (server) {
  104513. /* @internal */
  104514. server.ActionSet = "action::set";
  104515. /* @internal */
  104516. server.ActionInvalidate = "action::invalidate";
  104517. /* @internal */
  104518. server.ActionPackageInstalled = "action::packageInstalled";
  104519. /* @internal */
  104520. server.EventTypesRegistry = "event::typesRegistry";
  104521. /* @internal */
  104522. server.EventBeginInstallTypes = "event::beginInstallTypes";
  104523. /* @internal */
  104524. server.EventEndInstallTypes = "event::endInstallTypes";
  104525. /* @internal */
  104526. server.EventInitializationFailed = "event::initializationFailed";
  104527. /* @internal */
  104528. var Arguments;
  104529. (function (Arguments) {
  104530. Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
  104531. Arguments.LogFile = "--logFile";
  104532. Arguments.EnableTelemetry = "--enableTelemetry";
  104533. Arguments.TypingSafeListLocation = "--typingSafeListLocation";
  104534. Arguments.TypesMapLocation = "--typesMapLocation";
  104535. /**
  104536. * This argument specifies the location of the NPM executable.
  104537. * typingsInstaller will run the command with `${npmLocation} install ...`.
  104538. */
  104539. Arguments.NpmLocation = "--npmLocation";
  104540. /**
  104541. * Flag indicating that the typings installer should try to validate the default npm location.
  104542. * If the default npm is not found when this flag is enabled, fallback to `npm install`
  104543. */
  104544. Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
  104545. })(Arguments = server.Arguments || (server.Arguments = {}));
  104546. /* @internal */
  104547. function hasArgument(argumentName) {
  104548. return ts.sys.args.indexOf(argumentName) >= 0;
  104549. }
  104550. server.hasArgument = hasArgument;
  104551. /* @internal */
  104552. function findArgument(argumentName) {
  104553. var index = ts.sys.args.indexOf(argumentName);
  104554. return index >= 0 && index < ts.sys.args.length - 1
  104555. ? ts.sys.args[index + 1]
  104556. : undefined;
  104557. }
  104558. server.findArgument = findArgument;
  104559. /* @internal */
  104560. function nowString() {
  104561. // E.g. "12:34:56.789"
  104562. var d = new Date();
  104563. return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
  104564. }
  104565. server.nowString = nowString;
  104566. })(server = ts.server || (ts.server = {}));
  104567. })(ts || (ts = {}));
  104568. /* @internal */
  104569. var ts;
  104570. (function (ts) {
  104571. var JsTyping;
  104572. (function (JsTyping) {
  104573. function isTypingUpToDate(cachedTyping, availableTypingVersions) {
  104574. var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
  104575. return availableVersion.compareTo(cachedTyping.version) <= 0;
  104576. }
  104577. JsTyping.isTypingUpToDate = isTypingUpToDate;
  104578. JsTyping.nodeCoreModuleList = [
  104579. "assert",
  104580. "async_hooks",
  104581. "buffer",
  104582. "child_process",
  104583. "cluster",
  104584. "console",
  104585. "constants",
  104586. "crypto",
  104587. "dgram",
  104588. "dns",
  104589. "domain",
  104590. "events",
  104591. "fs",
  104592. "http",
  104593. "https",
  104594. "http2",
  104595. "inspector",
  104596. "net",
  104597. "os",
  104598. "path",
  104599. "perf_hooks",
  104600. "process",
  104601. "punycode",
  104602. "querystring",
  104603. "readline",
  104604. "repl",
  104605. "stream",
  104606. "string_decoder",
  104607. "timers",
  104608. "tls",
  104609. "tty",
  104610. "url",
  104611. "util",
  104612. "v8",
  104613. "vm",
  104614. "zlib"
  104615. ];
  104616. JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
  104617. function nonRelativeModuleNameForTypingCache(moduleName) {
  104618. return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
  104619. }
  104620. JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
  104621. function loadSafeList(host, safeListPath) {
  104622. var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
  104623. return ts.createMapFromTemplate(result.config);
  104624. }
  104625. JsTyping.loadSafeList = loadSafeList;
  104626. function loadTypesMap(host, typesMapPath) {
  104627. var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
  104628. if (result.config) {
  104629. return ts.createMapFromTemplate(result.config.simpleMap);
  104630. }
  104631. return undefined;
  104632. }
  104633. JsTyping.loadTypesMap = loadTypesMap;
  104634. /**
  104635. * @param host is the object providing I/O related operations.
  104636. * @param fileNames are the file names that belong to the same project
  104637. * @param projectRootPath is the path to the project root directory
  104638. * @param safeListPath is the path used to retrieve the safe list
  104639. * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
  104640. * @param typeAcquisition is used to customize the typing acquisition process
  104641. * @param compilerOptions are used as a source for typing inference
  104642. */
  104643. function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
  104644. if (!typeAcquisition || !typeAcquisition.enable) {
  104645. return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
  104646. }
  104647. // A typing name to typing file path mapping
  104648. var inferredTypings = ts.createMap();
  104649. // Only infer typings for .js and .jsx files
  104650. fileNames = ts.mapDefined(fileNames, function (fileName) {
  104651. var path = ts.normalizePath(fileName);
  104652. if (ts.hasJSFileExtension(path)) {
  104653. return path;
  104654. }
  104655. });
  104656. var filesToWatch = [];
  104657. if (typeAcquisition.include)
  104658. addInferredTypings(typeAcquisition.include, "Explicitly included types");
  104659. var exclude = typeAcquisition.exclude || [];
  104660. // Directories to search for package.json, bower.json and other typing information
  104661. var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
  104662. possibleSearchDirs.set(projectRootPath, true);
  104663. possibleSearchDirs.forEach(function (_true, searchDir) {
  104664. var packageJsonPath = ts.combinePaths(searchDir, "package.json");
  104665. getTypingNamesFromJson(packageJsonPath, filesToWatch);
  104666. var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
  104667. getTypingNamesFromJson(bowerJsonPath, filesToWatch);
  104668. var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
  104669. getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
  104670. var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
  104671. getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
  104672. });
  104673. getTypingNamesFromSourceFileNames(fileNames);
  104674. // add typings for unresolved imports
  104675. if (unresolvedImports) {
  104676. var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
  104677. addInferredTypings(module_1, "Inferred typings from unresolved imports");
  104678. }
  104679. // Add the cached typing locations for inferred typings that are already installed
  104680. packageNameToTypingLocation.forEach(function (typing, name) {
  104681. var registryEntry = typesRegistry.get(name);
  104682. if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
  104683. inferredTypings.set(name, typing.typingLocation);
  104684. }
  104685. });
  104686. // Remove typings that the user has added to the exclude list
  104687. for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
  104688. var excludeTypingName = exclude_1[_i];
  104689. var didDelete = inferredTypings.delete(excludeTypingName);
  104690. if (didDelete && log)
  104691. log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
  104692. }
  104693. var newTypingNames = [];
  104694. var cachedTypingPaths = [];
  104695. inferredTypings.forEach(function (inferred, typing) {
  104696. if (inferred !== undefined) {
  104697. cachedTypingPaths.push(inferred);
  104698. }
  104699. else {
  104700. newTypingNames.push(typing);
  104701. }
  104702. });
  104703. var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
  104704. if (log)
  104705. log("Result: " + JSON.stringify(result));
  104706. return result;
  104707. function addInferredTyping(typingName) {
  104708. if (!inferredTypings.has(typingName)) {
  104709. inferredTypings.set(typingName, undefined); // TODO: GH#18217
  104710. }
  104711. }
  104712. function addInferredTypings(typingNames, message) {
  104713. if (log)
  104714. log(message + ": " + JSON.stringify(typingNames));
  104715. ts.forEach(typingNames, addInferredTyping);
  104716. }
  104717. /**
  104718. * Get the typing info from common package manager json files like package.json or bower.json
  104719. */
  104720. function getTypingNamesFromJson(jsonPath, filesToWatch) {
  104721. if (!host.fileExists(jsonPath)) {
  104722. return;
  104723. }
  104724. filesToWatch.push(jsonPath);
  104725. var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
  104726. var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
  104727. addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
  104728. }
  104729. /**
  104730. * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
  104731. * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
  104732. * to the 'angular-route' typing name.
  104733. * @param fileNames are the names for source files in the project
  104734. */
  104735. function getTypingNamesFromSourceFileNames(fileNames) {
  104736. var fromFileNames = ts.mapDefined(fileNames, function (j) {
  104737. if (!ts.hasJSFileExtension(j))
  104738. return undefined;
  104739. var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
  104740. var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
  104741. return safeList.get(cleanedTypingName);
  104742. });
  104743. if (fromFileNames.length) {
  104744. addInferredTypings(fromFileNames, "Inferred typings from file names");
  104745. }
  104746. var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
  104747. if (hasJsxFile) {
  104748. if (log)
  104749. log("Inferred 'react' typings due to presence of '.jsx' extension");
  104750. addInferredTyping("react");
  104751. }
  104752. }
  104753. /**
  104754. * Infer typing names from packages folder (ex: node_module, bower_components)
  104755. * @param packagesFolderPath is the path to the packages folder
  104756. */
  104757. function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
  104758. filesToWatch.push(packagesFolderPath);
  104759. // Todo: add support for ModuleResolutionHost too
  104760. if (!host.directoryExists(packagesFolderPath)) {
  104761. return;
  104762. }
  104763. // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
  104764. var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
  104765. if (log)
  104766. log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
  104767. var packageNames = [];
  104768. for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
  104769. var fileName = fileNames_1[_i];
  104770. var normalizedFileName = ts.normalizePath(fileName);
  104771. var baseFileName = ts.getBaseFileName(normalizedFileName);
  104772. if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
  104773. continue;
  104774. }
  104775. var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
  104776. var packageJson = result_1.config;
  104777. // npm 3's package.json contains a "_requiredBy" field
  104778. // we should include all the top level module names for npm 2, and only module names whose
  104779. // "_requiredBy" field starts with "#" or equals "/" for npm 3.
  104780. if (baseFileName === "package.json" && packageJson._requiredBy &&
  104781. ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
  104782. continue;
  104783. }
  104784. // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
  104785. // to download d.ts files from DefinitelyTyped
  104786. if (!packageJson.name) {
  104787. continue;
  104788. }
  104789. var ownTypes = packageJson.types || packageJson.typings;
  104790. if (ownTypes) {
  104791. var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
  104792. if (log)
  104793. log(" Package '" + packageJson.name + "' provides its own types.");
  104794. inferredTypings.set(packageJson.name, absolutePath);
  104795. }
  104796. else {
  104797. packageNames.push(packageJson.name);
  104798. }
  104799. }
  104800. addInferredTypings(packageNames, " Found package names");
  104801. }
  104802. }
  104803. JsTyping.discoverTypings = discoverTypings;
  104804. var NameValidationResult;
  104805. (function (NameValidationResult) {
  104806. NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
  104807. NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
  104808. NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
  104809. NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
  104810. NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
  104811. NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
  104812. })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
  104813. var maxPackageNameLength = 214;
  104814. /**
  104815. * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
  104816. */
  104817. function validatePackageName(packageName) {
  104818. return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
  104819. }
  104820. JsTyping.validatePackageName = validatePackageName;
  104821. function validatePackageNameWorker(packageName, supportScopedPackage) {
  104822. if (!packageName) {
  104823. return 1 /* EmptyName */;
  104824. }
  104825. if (packageName.length > maxPackageNameLength) {
  104826. return 2 /* NameTooLong */;
  104827. }
  104828. if (packageName.charCodeAt(0) === 46 /* dot */) {
  104829. return 3 /* NameStartsWithDot */;
  104830. }
  104831. if (packageName.charCodeAt(0) === 95 /* _ */) {
  104832. return 4 /* NameStartsWithUnderscore */;
  104833. }
  104834. // check if name is scope package like: starts with @ and has one '/' in the middle
  104835. // scoped packages are not currently supported
  104836. if (supportScopedPackage) {
  104837. var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
  104838. if (matches) {
  104839. var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
  104840. if (scopeResult !== 0 /* Ok */) {
  104841. return { name: matches[1], isScopeName: true, result: scopeResult };
  104842. }
  104843. var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
  104844. if (packageResult !== 0 /* Ok */) {
  104845. return { name: matches[2], isScopeName: false, result: packageResult };
  104846. }
  104847. return 0 /* Ok */;
  104848. }
  104849. }
  104850. if (encodeURIComponent(packageName) !== packageName) {
  104851. return 5 /* NameContainsNonURISafeCharacters */;
  104852. }
  104853. return 0 /* Ok */;
  104854. }
  104855. function renderPackageNameValidationFailure(result, typing) {
  104856. return typeof result === "object" ?
  104857. renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
  104858. renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
  104859. }
  104860. JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
  104861. function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
  104862. var kind = isScopeName ? "Scope" : "Package";
  104863. switch (result) {
  104864. case 1 /* EmptyName */:
  104865. return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
  104866. case 2 /* NameTooLong */:
  104867. return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
  104868. case 3 /* NameStartsWithDot */:
  104869. return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
  104870. case 4 /* NameStartsWithUnderscore */:
  104871. return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
  104872. case 5 /* NameContainsNonURISafeCharacters */:
  104873. return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
  104874. case 0 /* Ok */:
  104875. return ts.Debug.fail(); // Shouldn't have called this.
  104876. default:
  104877. throw ts.Debug.assertNever(result);
  104878. }
  104879. }
  104880. })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
  104881. })(ts || (ts = {}));
  104882. var ts;
  104883. (function (ts) {
  104884. var ScriptSnapshot;
  104885. (function (ScriptSnapshot) {
  104886. var StringScriptSnapshot = /** @class */ (function () {
  104887. function StringScriptSnapshot(text) {
  104888. this.text = text;
  104889. }
  104890. StringScriptSnapshot.prototype.getText = function (start, end) {
  104891. return start === 0 && end === this.text.length
  104892. ? this.text
  104893. : this.text.substring(start, end);
  104894. };
  104895. StringScriptSnapshot.prototype.getLength = function () {
  104896. return this.text.length;
  104897. };
  104898. StringScriptSnapshot.prototype.getChangeRange = function () {
  104899. // Text-based snapshots do not support incremental parsing. Return undefined
  104900. // to signal that to the caller.
  104901. return undefined;
  104902. };
  104903. return StringScriptSnapshot;
  104904. }());
  104905. function fromString(text) {
  104906. return new StringScriptSnapshot(text);
  104907. }
  104908. ScriptSnapshot.fromString = fromString;
  104909. })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
  104910. /* @internal */
  104911. var PackageJsonDependencyGroup;
  104912. (function (PackageJsonDependencyGroup) {
  104913. PackageJsonDependencyGroup[PackageJsonDependencyGroup["Dependencies"] = 1] = "Dependencies";
  104914. PackageJsonDependencyGroup[PackageJsonDependencyGroup["DevDependencies"] = 2] = "DevDependencies";
  104915. PackageJsonDependencyGroup[PackageJsonDependencyGroup["PeerDependencies"] = 4] = "PeerDependencies";
  104916. PackageJsonDependencyGroup[PackageJsonDependencyGroup["OptionalDependencies"] = 8] = "OptionalDependencies";
  104917. PackageJsonDependencyGroup[PackageJsonDependencyGroup["All"] = 15] = "All";
  104918. })(PackageJsonDependencyGroup = ts.PackageJsonDependencyGroup || (ts.PackageJsonDependencyGroup = {}));
  104919. /* @internal */
  104920. ts.emptyOptions = {};
  104921. var HighlightSpanKind;
  104922. (function (HighlightSpanKind) {
  104923. HighlightSpanKind["none"] = "none";
  104924. HighlightSpanKind["definition"] = "definition";
  104925. HighlightSpanKind["reference"] = "reference";
  104926. HighlightSpanKind["writtenReference"] = "writtenReference";
  104927. })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {}));
  104928. var IndentStyle;
  104929. (function (IndentStyle) {
  104930. IndentStyle[IndentStyle["None"] = 0] = "None";
  104931. IndentStyle[IndentStyle["Block"] = 1] = "Block";
  104932. IndentStyle[IndentStyle["Smart"] = 2] = "Smart";
  104933. })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {}));
  104934. var SemicolonPreference;
  104935. (function (SemicolonPreference) {
  104936. SemicolonPreference["Ignore"] = "ignore";
  104937. SemicolonPreference["Insert"] = "insert";
  104938. SemicolonPreference["Remove"] = "remove";
  104939. })(SemicolonPreference = ts.SemicolonPreference || (ts.SemicolonPreference = {}));
  104940. function getDefaultFormatCodeSettings(newLineCharacter) {
  104941. return {
  104942. indentSize: 4,
  104943. tabSize: 4,
  104944. newLineCharacter: newLineCharacter || "\n",
  104945. convertTabsToSpaces: true,
  104946. indentStyle: IndentStyle.Smart,
  104947. insertSpaceAfterConstructor: false,
  104948. insertSpaceAfterCommaDelimiter: true,
  104949. insertSpaceAfterSemicolonInForStatements: true,
  104950. insertSpaceBeforeAndAfterBinaryOperators: true,
  104951. insertSpaceAfterKeywordsInControlFlowStatements: true,
  104952. insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
  104953. insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
  104954. insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
  104955. insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
  104956. insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
  104957. insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
  104958. insertSpaceBeforeFunctionParenthesis: false,
  104959. placeOpenBraceOnNewLineForFunctions: false,
  104960. placeOpenBraceOnNewLineForControlBlocks: false,
  104961. semicolons: SemicolonPreference.Ignore,
  104962. };
  104963. }
  104964. ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings;
  104965. /* @internal */
  104966. ts.testFormatSettings = getDefaultFormatCodeSettings("\n");
  104967. var SymbolDisplayPartKind;
  104968. (function (SymbolDisplayPartKind) {
  104969. SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName";
  104970. SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className";
  104971. SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName";
  104972. SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName";
  104973. SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName";
  104974. SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword";
  104975. SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak";
  104976. SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral";
  104977. SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral";
  104978. SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName";
  104979. SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName";
  104980. SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName";
  104981. SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator";
  104982. SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName";
  104983. SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName";
  104984. SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation";
  104985. SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space";
  104986. SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text";
  104987. SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName";
  104988. SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName";
  104989. SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
  104990. SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
  104991. })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
  104992. var OutliningSpanKind;
  104993. (function (OutliningSpanKind) {
  104994. /** Single or multi-line comments */
  104995. OutliningSpanKind["Comment"] = "comment";
  104996. /** Sections marked by '// #region' and '// #endregion' comments */
  104997. OutliningSpanKind["Region"] = "region";
  104998. /** Declarations and expressions */
  104999. OutliningSpanKind["Code"] = "code";
  105000. /** Contiguous blocks of import declarations */
  105001. OutliningSpanKind["Imports"] = "imports";
  105002. })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
  105003. var OutputFileType;
  105004. (function (OutputFileType) {
  105005. OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
  105006. OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap";
  105007. OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration";
  105008. })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {}));
  105009. var EndOfLineState;
  105010. (function (EndOfLineState) {
  105011. EndOfLineState[EndOfLineState["None"] = 0] = "None";
  105012. EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia";
  105013. EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral";
  105014. EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral";
  105015. EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate";
  105016. EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail";
  105017. EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition";
  105018. })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {}));
  105019. var TokenClass;
  105020. (function (TokenClass) {
  105021. TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation";
  105022. TokenClass[TokenClass["Keyword"] = 1] = "Keyword";
  105023. TokenClass[TokenClass["Operator"] = 2] = "Operator";
  105024. TokenClass[TokenClass["Comment"] = 3] = "Comment";
  105025. TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace";
  105026. TokenClass[TokenClass["Identifier"] = 5] = "Identifier";
  105027. TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral";
  105028. TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral";
  105029. TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral";
  105030. TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral";
  105031. })(TokenClass = ts.TokenClass || (ts.TokenClass = {}));
  105032. var ScriptElementKind;
  105033. (function (ScriptElementKind) {
  105034. ScriptElementKind["unknown"] = "";
  105035. ScriptElementKind["warning"] = "warning";
  105036. /** predefined type (void) or keyword (class) */
  105037. ScriptElementKind["keyword"] = "keyword";
  105038. /** top level script node */
  105039. ScriptElementKind["scriptElement"] = "script";
  105040. /** module foo {} */
  105041. ScriptElementKind["moduleElement"] = "module";
  105042. /** class X {} */
  105043. ScriptElementKind["classElement"] = "class";
  105044. /** var x = class X {} */
  105045. ScriptElementKind["localClassElement"] = "local class";
  105046. /** interface Y {} */
  105047. ScriptElementKind["interfaceElement"] = "interface";
  105048. /** type T = ... */
  105049. ScriptElementKind["typeElement"] = "type";
  105050. /** enum E */
  105051. ScriptElementKind["enumElement"] = "enum";
  105052. ScriptElementKind["enumMemberElement"] = "enum member";
  105053. /**
  105054. * Inside module and script only
  105055. * const v = ..
  105056. */
  105057. ScriptElementKind["variableElement"] = "var";
  105058. /** Inside function */
  105059. ScriptElementKind["localVariableElement"] = "local var";
  105060. /**
  105061. * Inside module and script only
  105062. * function f() { }
  105063. */
  105064. ScriptElementKind["functionElement"] = "function";
  105065. /** Inside function */
  105066. ScriptElementKind["localFunctionElement"] = "local function";
  105067. /** class X { [public|private]* foo() {} } */
  105068. ScriptElementKind["memberFunctionElement"] = "method";
  105069. /** class X { [public|private]* [get|set] foo:number; } */
  105070. ScriptElementKind["memberGetAccessorElement"] = "getter";
  105071. ScriptElementKind["memberSetAccessorElement"] = "setter";
  105072. /**
  105073. * class X { [public|private]* foo:number; }
  105074. * interface Y { foo:number; }
  105075. */
  105076. ScriptElementKind["memberVariableElement"] = "property";
  105077. /** class X { constructor() { } } */
  105078. ScriptElementKind["constructorImplementationElement"] = "constructor";
  105079. /** interface Y { ():number; } */
  105080. ScriptElementKind["callSignatureElement"] = "call";
  105081. /** interface Y { []:number; } */
  105082. ScriptElementKind["indexSignatureElement"] = "index";
  105083. /** interface Y { new():Y; } */
  105084. ScriptElementKind["constructSignatureElement"] = "construct";
  105085. /** function foo(*Y*: string) */
  105086. ScriptElementKind["parameterElement"] = "parameter";
  105087. ScriptElementKind["typeParameterElement"] = "type parameter";
  105088. ScriptElementKind["primitiveType"] = "primitive type";
  105089. ScriptElementKind["label"] = "label";
  105090. ScriptElementKind["alias"] = "alias";
  105091. ScriptElementKind["constElement"] = "const";
  105092. ScriptElementKind["letElement"] = "let";
  105093. ScriptElementKind["directory"] = "directory";
  105094. ScriptElementKind["externalModuleName"] = "external module name";
  105095. /**
  105096. * <JsxTagName attribute1 attribute2={0} />
  105097. */
  105098. ScriptElementKind["jsxAttribute"] = "JSX attribute";
  105099. /** String literal */
  105100. ScriptElementKind["string"] = "string";
  105101. })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
  105102. var ScriptElementKindModifier;
  105103. (function (ScriptElementKindModifier) {
  105104. ScriptElementKindModifier["none"] = "";
  105105. ScriptElementKindModifier["publicMemberModifier"] = "public";
  105106. ScriptElementKindModifier["privateMemberModifier"] = "private";
  105107. ScriptElementKindModifier["protectedMemberModifier"] = "protected";
  105108. ScriptElementKindModifier["exportedModifier"] = "export";
  105109. ScriptElementKindModifier["ambientModifier"] = "declare";
  105110. ScriptElementKindModifier["staticModifier"] = "static";
  105111. ScriptElementKindModifier["abstractModifier"] = "abstract";
  105112. ScriptElementKindModifier["optionalModifier"] = "optional";
  105113. ScriptElementKindModifier["dtsModifier"] = ".d.ts";
  105114. ScriptElementKindModifier["tsModifier"] = ".ts";
  105115. ScriptElementKindModifier["tsxModifier"] = ".tsx";
  105116. ScriptElementKindModifier["jsModifier"] = ".js";
  105117. ScriptElementKindModifier["jsxModifier"] = ".jsx";
  105118. ScriptElementKindModifier["jsonModifier"] = ".json";
  105119. })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {}));
  105120. var ClassificationTypeNames;
  105121. (function (ClassificationTypeNames) {
  105122. ClassificationTypeNames["comment"] = "comment";
  105123. ClassificationTypeNames["identifier"] = "identifier";
  105124. ClassificationTypeNames["keyword"] = "keyword";
  105125. ClassificationTypeNames["numericLiteral"] = "number";
  105126. ClassificationTypeNames["bigintLiteral"] = "bigint";
  105127. ClassificationTypeNames["operator"] = "operator";
  105128. ClassificationTypeNames["stringLiteral"] = "string";
  105129. ClassificationTypeNames["whiteSpace"] = "whitespace";
  105130. ClassificationTypeNames["text"] = "text";
  105131. ClassificationTypeNames["punctuation"] = "punctuation";
  105132. ClassificationTypeNames["className"] = "class name";
  105133. ClassificationTypeNames["enumName"] = "enum name";
  105134. ClassificationTypeNames["interfaceName"] = "interface name";
  105135. ClassificationTypeNames["moduleName"] = "module name";
  105136. ClassificationTypeNames["typeParameterName"] = "type parameter name";
  105137. ClassificationTypeNames["typeAliasName"] = "type alias name";
  105138. ClassificationTypeNames["parameterName"] = "parameter name";
  105139. ClassificationTypeNames["docCommentTagName"] = "doc comment tag name";
  105140. ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name";
  105141. ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name";
  105142. ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name";
  105143. ClassificationTypeNames["jsxAttribute"] = "jsx attribute";
  105144. ClassificationTypeNames["jsxText"] = "jsx text";
  105145. ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value";
  105146. })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {}));
  105147. var ClassificationType;
  105148. (function (ClassificationType) {
  105149. ClassificationType[ClassificationType["comment"] = 1] = "comment";
  105150. ClassificationType[ClassificationType["identifier"] = 2] = "identifier";
  105151. ClassificationType[ClassificationType["keyword"] = 3] = "keyword";
  105152. ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral";
  105153. ClassificationType[ClassificationType["operator"] = 5] = "operator";
  105154. ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral";
  105155. ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
  105156. ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace";
  105157. ClassificationType[ClassificationType["text"] = 9] = "text";
  105158. ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation";
  105159. ClassificationType[ClassificationType["className"] = 11] = "className";
  105160. ClassificationType[ClassificationType["enumName"] = 12] = "enumName";
  105161. ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName";
  105162. ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName";
  105163. ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName";
  105164. ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName";
  105165. ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName";
  105166. ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName";
  105167. ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName";
  105168. ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName";
  105169. ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
  105170. ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute";
  105171. ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText";
  105172. ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
  105173. ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral";
  105174. })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {}));
  105175. })(ts || (ts = {}));
  105176. /* @internal */
  105177. var ts;
  105178. (function (ts) {
  105179. // These utilities are common to multiple language service features.
  105180. //#region
  105181. ts.scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
  105182. var SemanticMeaning;
  105183. (function (SemanticMeaning) {
  105184. SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
  105185. SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value";
  105186. SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type";
  105187. SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace";
  105188. SemanticMeaning[SemanticMeaning["All"] = 7] = "All";
  105189. })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {}));
  105190. function getMeaningFromDeclaration(node) {
  105191. switch (node.kind) {
  105192. case 242 /* VariableDeclaration */:
  105193. return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */;
  105194. case 156 /* Parameter */:
  105195. case 191 /* BindingElement */:
  105196. case 159 /* PropertyDeclaration */:
  105197. case 158 /* PropertySignature */:
  105198. case 281 /* PropertyAssignment */:
  105199. case 282 /* ShorthandPropertyAssignment */:
  105200. case 161 /* MethodDeclaration */:
  105201. case 160 /* MethodSignature */:
  105202. case 162 /* Constructor */:
  105203. case 163 /* GetAccessor */:
  105204. case 164 /* SetAccessor */:
  105205. case 244 /* FunctionDeclaration */:
  105206. case 201 /* FunctionExpression */:
  105207. case 202 /* ArrowFunction */:
  105208. case 280 /* CatchClause */:
  105209. case 273 /* JsxAttribute */:
  105210. return 1 /* Value */;
  105211. case 155 /* TypeParameter */:
  105212. case 246 /* InterfaceDeclaration */:
  105213. case 247 /* TypeAliasDeclaration */:
  105214. case 173 /* TypeLiteral */:
  105215. return 2 /* Type */;
  105216. case 321 /* JSDocTypedefTag */:
  105217. // If it has no name node, it shares the name with the value declaration below it.
  105218. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
  105219. case 284 /* EnumMember */:
  105220. case 245 /* ClassDeclaration */:
  105221. return 1 /* Value */ | 2 /* Type */;
  105222. case 249 /* ModuleDeclaration */:
  105223. if (ts.isAmbientModule(node)) {
  105224. return 4 /* Namespace */ | 1 /* Value */;
  105225. }
  105226. else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) {
  105227. return 4 /* Namespace */ | 1 /* Value */;
  105228. }
  105229. else {
  105230. return 4 /* Namespace */;
  105231. }
  105232. case 248 /* EnumDeclaration */:
  105233. case 257 /* NamedImports */:
  105234. case 258 /* ImportSpecifier */:
  105235. case 253 /* ImportEqualsDeclaration */:
  105236. case 254 /* ImportDeclaration */:
  105237. case 259 /* ExportAssignment */:
  105238. case 260 /* ExportDeclaration */:
  105239. return 7 /* All */;
  105240. // An external module can be a Value
  105241. case 290 /* SourceFile */:
  105242. return 4 /* Namespace */ | 1 /* Value */;
  105243. }
  105244. return 7 /* All */;
  105245. }
  105246. ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
  105247. function getMeaningFromLocation(node) {
  105248. node = getAdjustedReferenceLocation(node);
  105249. if (node.kind === 290 /* SourceFile */) {
  105250. return 1 /* Value */;
  105251. }
  105252. else if (node.parent.kind === 259 /* ExportAssignment */ || node.parent.kind === 265 /* ExternalModuleReference */) {
  105253. return 7 /* All */;
  105254. }
  105255. else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
  105256. return getMeaningFromRightHandSideOfImportEquals(node);
  105257. }
  105258. else if (ts.isDeclarationName(node)) {
  105259. return getMeaningFromDeclaration(node.parent);
  105260. }
  105261. else if (isTypeReference(node)) {
  105262. return 2 /* Type */;
  105263. }
  105264. else if (isNamespaceReference(node)) {
  105265. return 4 /* Namespace */;
  105266. }
  105267. else if (ts.isTypeParameterDeclaration(node.parent)) {
  105268. ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName
  105269. return 2 /* Type */;
  105270. }
  105271. else if (ts.isLiteralTypeNode(node.parent)) {
  105272. // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
  105273. return 2 /* Type */ | 1 /* Value */;
  105274. }
  105275. else {
  105276. return 1 /* Value */;
  105277. }
  105278. }
  105279. ts.getMeaningFromLocation = getMeaningFromLocation;
  105280. function getMeaningFromRightHandSideOfImportEquals(node) {
  105281. // import a = |b|; // Namespace
  105282. // import a = |b.c|; // Value, type, namespace
  105283. // import a = |b.c|.d; // Namespace
  105284. var name = node.kind === 153 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined;
  105285. return name && name.parent.kind === 253 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */;
  105286. }
  105287. function isInRightSideOfInternalImportEqualsDeclaration(node) {
  105288. while (node.parent.kind === 153 /* QualifiedName */) {
  105289. node = node.parent;
  105290. }
  105291. return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
  105292. }
  105293. ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration;
  105294. function isNamespaceReference(node) {
  105295. return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
  105296. }
  105297. function isQualifiedNameNamespaceReference(node) {
  105298. var root = node;
  105299. var isLastClause = true;
  105300. if (root.parent.kind === 153 /* QualifiedName */) {
  105301. while (root.parent && root.parent.kind === 153 /* QualifiedName */) {
  105302. root = root.parent;
  105303. }
  105304. isLastClause = root.right === node;
  105305. }
  105306. return root.parent.kind === 169 /* TypeReference */ && !isLastClause;
  105307. }
  105308. function isPropertyAccessNamespaceReference(node) {
  105309. var root = node;
  105310. var isLastClause = true;
  105311. if (root.parent.kind === 194 /* PropertyAccessExpression */) {
  105312. while (root.parent && root.parent.kind === 194 /* PropertyAccessExpression */) {
  105313. root = root.parent;
  105314. }
  105315. isLastClause = root.name === node;
  105316. }
  105317. if (!isLastClause && root.parent.kind === 216 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 279 /* HeritageClause */) {
  105318. var decl = root.parent.parent.parent;
  105319. return (decl.kind === 245 /* ClassDeclaration */ && root.parent.parent.token === 113 /* ImplementsKeyword */) ||
  105320. (decl.kind === 246 /* InterfaceDeclaration */ && root.parent.parent.token === 90 /* ExtendsKeyword */);
  105321. }
  105322. return false;
  105323. }
  105324. function isTypeReference(node) {
  105325. if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
  105326. node = node.parent;
  105327. }
  105328. switch (node.kind) {
  105329. case 104 /* ThisKeyword */:
  105330. return !ts.isExpressionNode(node);
  105331. case 183 /* ThisType */:
  105332. return true;
  105333. }
  105334. switch (node.parent.kind) {
  105335. case 169 /* TypeReference */:
  105336. return true;
  105337. case 188 /* ImportType */:
  105338. return !node.parent.isTypeOf;
  105339. case 216 /* ExpressionWithTypeArguments */:
  105340. return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
  105341. }
  105342. return false;
  105343. }
  105344. function isCallExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
  105345. if (includeElementAccess === void 0) { includeElementAccess = false; }
  105346. if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
  105347. return isCalleeWorker(node, ts.isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
  105348. }
  105349. ts.isCallExpressionTarget = isCallExpressionTarget;
  105350. function isNewExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
  105351. if (includeElementAccess === void 0) { includeElementAccess = false; }
  105352. if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
  105353. return isCalleeWorker(node, ts.isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
  105354. }
  105355. ts.isNewExpressionTarget = isNewExpressionTarget;
  105356. function isCallOrNewExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
  105357. if (includeElementAccess === void 0) { includeElementAccess = false; }
  105358. if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
  105359. return isCalleeWorker(node, ts.isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
  105360. }
  105361. ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget;
  105362. function isTaggedTemplateTag(node, includeElementAccess, skipPastOuterExpressions) {
  105363. if (includeElementAccess === void 0) { includeElementAccess = false; }
  105364. if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
  105365. return isCalleeWorker(node, ts.isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions);
  105366. }
  105367. ts.isTaggedTemplateTag = isTaggedTemplateTag;
  105368. function isDecoratorTarget(node, includeElementAccess, skipPastOuterExpressions) {
  105369. if (includeElementAccess === void 0) { includeElementAccess = false; }
  105370. if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
  105371. return isCalleeWorker(node, ts.isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
  105372. }
  105373. ts.isDecoratorTarget = isDecoratorTarget;
  105374. function isJsxOpeningLikeElementTagName(node, includeElementAccess, skipPastOuterExpressions) {
  105375. if (includeElementAccess === void 0) { includeElementAccess = false; }
  105376. if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
  105377. return isCalleeWorker(node, ts.isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions);
  105378. }
  105379. ts.isJsxOpeningLikeElementTagName = isJsxOpeningLikeElementTagName;
  105380. function selectExpressionOfCallOrNewExpressionOrDecorator(node) {
  105381. return node.expression;
  105382. }
  105383. function selectTagOfTaggedTemplateExpression(node) {
  105384. return node.tag;
  105385. }
  105386. function selectTagNameOfJsxOpeningLikeElement(node) {
  105387. return node.tagName;
  105388. }
  105389. function isCalleeWorker(node, pred, calleeSelector, includeElementAccess, skipPastOuterExpressions) {
  105390. var target = includeElementAccess ? climbPastPropertyOrElementAccess(node) : climbPastPropertyAccess(node);
  105391. if (skipPastOuterExpressions) {
  105392. target = ts.skipOuterExpressions(target);
  105393. }
  105394. return !!target && !!target.parent && pred(target.parent) && calleeSelector(target.parent) === target;
  105395. }
  105396. function climbPastPropertyAccess(node) {
  105397. return isRightSideOfPropertyAccess(node) ? node.parent : node;
  105398. }
  105399. ts.climbPastPropertyAccess = climbPastPropertyAccess;
  105400. function climbPastPropertyOrElementAccess(node) {
  105401. return isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node) ? node.parent : node;
  105402. }
  105403. ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess;
  105404. function getTargetLabel(referenceNode, labelName) {
  105405. while (referenceNode) {
  105406. if (referenceNode.kind === 238 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) {
  105407. return referenceNode.label;
  105408. }
  105409. referenceNode = referenceNode.parent;
  105410. }
  105411. return undefined;
  105412. }
  105413. ts.getTargetLabel = getTargetLabel;
  105414. function hasPropertyAccessExpressionWithName(node, funcName) {
  105415. if (!ts.isPropertyAccessExpression(node.expression)) {
  105416. return false;
  105417. }
  105418. return node.expression.name.text === funcName;
  105419. }
  105420. ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName;
  105421. function isJumpStatementTarget(node) {
  105422. var _a;
  105423. return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isBreakOrContinueStatement)) === null || _a === void 0 ? void 0 : _a.label) === node;
  105424. }
  105425. ts.isJumpStatementTarget = isJumpStatementTarget;
  105426. function isLabelOfLabeledStatement(node) {
  105427. var _a;
  105428. return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isLabeledStatement)) === null || _a === void 0 ? void 0 : _a.label) === node;
  105429. }
  105430. ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
  105431. function isLabelName(node) {
  105432. return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
  105433. }
  105434. ts.isLabelName = isLabelName;
  105435. function isTagName(node) {
  105436. var _a;
  105437. return ((_a = ts.tryCast(node.parent, ts.isJSDocTag)) === null || _a === void 0 ? void 0 : _a.tagName) === node;
  105438. }
  105439. ts.isTagName = isTagName;
  105440. function isRightSideOfQualifiedName(node) {
  105441. var _a;
  105442. return ((_a = ts.tryCast(node.parent, ts.isQualifiedName)) === null || _a === void 0 ? void 0 : _a.right) === node;
  105443. }
  105444. ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName;
  105445. function isRightSideOfPropertyAccess(node) {
  105446. var _a;
  105447. return ((_a = ts.tryCast(node.parent, ts.isPropertyAccessExpression)) === null || _a === void 0 ? void 0 : _a.name) === node;
  105448. }
  105449. ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess;
  105450. function isArgumentExpressionOfElementAccess(node) {
  105451. var _a;
  105452. return ((_a = ts.tryCast(node.parent, ts.isElementAccessExpression)) === null || _a === void 0 ? void 0 : _a.argumentExpression) === node;
  105453. }
  105454. ts.isArgumentExpressionOfElementAccess = isArgumentExpressionOfElementAccess;
  105455. function isNameOfModuleDeclaration(node) {
  105456. var _a;
  105457. return ((_a = ts.tryCast(node.parent, ts.isModuleDeclaration)) === null || _a === void 0 ? void 0 : _a.name) === node;
  105458. }
  105459. ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration;
  105460. function isNameOfFunctionDeclaration(node) {
  105461. var _a;
  105462. return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isFunctionLike)) === null || _a === void 0 ? void 0 : _a.name) === node;
  105463. }
  105464. ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration;
  105465. function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
  105466. switch (node.parent.kind) {
  105467. case 159 /* PropertyDeclaration */:
  105468. case 158 /* PropertySignature */:
  105469. case 281 /* PropertyAssignment */:
  105470. case 284 /* EnumMember */:
  105471. case 161 /* MethodDeclaration */:
  105472. case 160 /* MethodSignature */:
  105473. case 163 /* GetAccessor */:
  105474. case 164 /* SetAccessor */:
  105475. case 249 /* ModuleDeclaration */:
  105476. return ts.getNameOfDeclaration(node.parent) === node;
  105477. case 195 /* ElementAccessExpression */:
  105478. return node.parent.argumentExpression === node;
  105479. case 154 /* ComputedPropertyName */:
  105480. return true;
  105481. case 187 /* LiteralType */:
  105482. return node.parent.parent.kind === 185 /* IndexedAccessType */;
  105483. default:
  105484. return false;
  105485. }
  105486. }
  105487. ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess;
  105488. function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
  105489. return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
  105490. ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
  105491. }
  105492. ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
  105493. function getContainerNode(node) {
  105494. if (ts.isJSDocTypeAlias(node)) {
  105495. // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
  105496. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
  105497. // Then we get parent again in the loop.
  105498. node = node.parent.parent;
  105499. }
  105500. while (true) {
  105501. node = node.parent;
  105502. if (!node) {
  105503. return undefined;
  105504. }
  105505. switch (node.kind) {
  105506. case 290 /* SourceFile */:
  105507. case 161 /* MethodDeclaration */:
  105508. case 160 /* MethodSignature */:
  105509. case 244 /* FunctionDeclaration */:
  105510. case 201 /* FunctionExpression */:
  105511. case 163 /* GetAccessor */:
  105512. case 164 /* SetAccessor */:
  105513. case 245 /* ClassDeclaration */:
  105514. case 246 /* InterfaceDeclaration */:
  105515. case 248 /* EnumDeclaration */:
  105516. case 249 /* ModuleDeclaration */:
  105517. return node;
  105518. }
  105519. }
  105520. }
  105521. ts.getContainerNode = getContainerNode;
  105522. function getNodeKind(node) {
  105523. switch (node.kind) {
  105524. case 290 /* SourceFile */:
  105525. return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
  105526. case 249 /* ModuleDeclaration */:
  105527. return "module" /* moduleElement */;
  105528. case 245 /* ClassDeclaration */:
  105529. case 214 /* ClassExpression */:
  105530. return "class" /* classElement */;
  105531. case 246 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
  105532. case 247 /* TypeAliasDeclaration */:
  105533. case 314 /* JSDocCallbackTag */:
  105534. case 321 /* JSDocTypedefTag */:
  105535. return "type" /* typeElement */;
  105536. case 248 /* EnumDeclaration */: return "enum" /* enumElement */;
  105537. case 242 /* VariableDeclaration */:
  105538. return getKindOfVariableDeclaration(node);
  105539. case 191 /* BindingElement */:
  105540. return getKindOfVariableDeclaration(ts.getRootDeclaration(node));
  105541. case 202 /* ArrowFunction */:
  105542. case 244 /* FunctionDeclaration */:
  105543. case 201 /* FunctionExpression */:
  105544. return "function" /* functionElement */;
  105545. case 163 /* GetAccessor */: return "getter" /* memberGetAccessorElement */;
  105546. case 164 /* SetAccessor */: return "setter" /* memberSetAccessorElement */;
  105547. case 161 /* MethodDeclaration */:
  105548. case 160 /* MethodSignature */:
  105549. return "method" /* memberFunctionElement */;
  105550. case 281 /* PropertyAssignment */:
  105551. var initializer = node.initializer;
  105552. return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
  105553. case 159 /* PropertyDeclaration */:
  105554. case 158 /* PropertySignature */:
  105555. case 282 /* ShorthandPropertyAssignment */:
  105556. case 283 /* SpreadAssignment */:
  105557. return "property" /* memberVariableElement */;
  105558. case 167 /* IndexSignature */: return "index" /* indexSignatureElement */;
  105559. case 166 /* ConstructSignature */: return "construct" /* constructSignatureElement */;
  105560. case 165 /* CallSignature */: return "call" /* callSignatureElement */;
  105561. case 162 /* Constructor */: return "constructor" /* constructorImplementationElement */;
  105562. case 155 /* TypeParameter */: return "type parameter" /* typeParameterElement */;
  105563. case 284 /* EnumMember */: return "enum member" /* enumMemberElement */;
  105564. case 156 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */;
  105565. case 253 /* ImportEqualsDeclaration */:
  105566. case 258 /* ImportSpecifier */:
  105567. case 263 /* ExportSpecifier */:
  105568. case 256 /* NamespaceImport */:
  105569. case 262 /* NamespaceExport */:
  105570. return "alias" /* alias */;
  105571. case 209 /* BinaryExpression */:
  105572. var kind = ts.getAssignmentDeclarationKind(node);
  105573. var right = node.right;
  105574. switch (kind) {
  105575. case 7 /* ObjectDefinePropertyValue */:
  105576. case 8 /* ObjectDefinePropertyExports */:
  105577. case 9 /* ObjectDefinePrototypeProperty */:
  105578. case 0 /* None */:
  105579. return "" /* unknown */;
  105580. case 1 /* ExportsProperty */:
  105581. case 2 /* ModuleExports */:
  105582. var rightKind = getNodeKind(right);
  105583. return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind;
  105584. case 3 /* PrototypeProperty */:
  105585. return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
  105586. case 4 /* ThisProperty */:
  105587. return "property" /* memberVariableElement */; // property
  105588. case 5 /* Property */:
  105589. // static method / property
  105590. return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
  105591. case 6 /* Prototype */:
  105592. return "local class" /* localClassElement */;
  105593. default: {
  105594. ts.assertType(kind);
  105595. return "" /* unknown */;
  105596. }
  105597. }
  105598. case 75 /* Identifier */:
  105599. return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */;
  105600. case 259 /* ExportAssignment */:
  105601. var scriptKind = getNodeKind(node.expression);
  105602. // If the expression didn't come back with something (like it does for an identifiers)
  105603. return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind;
  105604. default:
  105605. return "" /* unknown */;
  105606. }
  105607. function getKindOfVariableDeclaration(v) {
  105608. return ts.isVarConst(v)
  105609. ? "const" /* constElement */
  105610. : ts.isLet(v)
  105611. ? "let" /* letElement */
  105612. : "var" /* variableElement */;
  105613. }
  105614. }
  105615. ts.getNodeKind = getNodeKind;
  105616. function isThis(node) {
  105617. switch (node.kind) {
  105618. case 104 /* ThisKeyword */:
  105619. // case SyntaxKind.ThisType: TODO: GH#9267
  105620. return true;
  105621. case 75 /* Identifier */:
  105622. // 'this' as a parameter
  105623. return ts.identifierIsThisKeyword(node) && node.parent.kind === 156 /* Parameter */;
  105624. default:
  105625. return false;
  105626. }
  105627. }
  105628. ts.isThis = isThis;
  105629. // Matches the beginning of a triple slash directive
  105630. var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
  105631. function getLineStartPositionForPosition(position, sourceFile) {
  105632. var lineStarts = ts.getLineStarts(sourceFile);
  105633. var line = sourceFile.getLineAndCharacterOfPosition(position).line;
  105634. return lineStarts[line];
  105635. }
  105636. ts.getLineStartPositionForPosition = getLineStartPositionForPosition;
  105637. function rangeContainsRange(r1, r2) {
  105638. return startEndContainsRange(r1.pos, r1.end, r2);
  105639. }
  105640. ts.rangeContainsRange = rangeContainsRange;
  105641. function rangeContainsRangeExclusive(r1, r2) {
  105642. return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
  105643. }
  105644. ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive;
  105645. function rangeContainsPosition(r, pos) {
  105646. return r.pos <= pos && pos <= r.end;
  105647. }
  105648. ts.rangeContainsPosition = rangeContainsPosition;
  105649. function rangeContainsPositionExclusive(r, pos) {
  105650. return r.pos < pos && pos < r.end;
  105651. }
  105652. ts.rangeContainsPositionExclusive = rangeContainsPositionExclusive;
  105653. function startEndContainsRange(start, end, range) {
  105654. return start <= range.pos && end >= range.end;
  105655. }
  105656. ts.startEndContainsRange = startEndContainsRange;
  105657. function rangeContainsStartEnd(range, start, end) {
  105658. return range.pos <= start && range.end >= end;
  105659. }
  105660. ts.rangeContainsStartEnd = rangeContainsStartEnd;
  105661. function rangeOverlapsWithStartEnd(r1, start, end) {
  105662. return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
  105663. }
  105664. ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd;
  105665. function nodeOverlapsWithStartEnd(node, sourceFile, start, end) {
  105666. return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
  105667. }
  105668. ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd;
  105669. function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
  105670. var start = Math.max(start1, start2);
  105671. var end = Math.min(end1, end2);
  105672. return start < end;
  105673. }
  105674. ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd;
  105675. /**
  105676. * Assumes `candidate.start <= position` holds.
  105677. */
  105678. function positionBelongsToNode(candidate, position, sourceFile) {
  105679. ts.Debug.assert(candidate.pos <= position);
  105680. return position < candidate.end || !isCompletedNode(candidate, sourceFile);
  105681. }
  105682. ts.positionBelongsToNode = positionBelongsToNode;
  105683. function isCompletedNode(n, sourceFile) {
  105684. if (n === undefined || ts.nodeIsMissing(n)) {
  105685. return false;
  105686. }
  105687. switch (n.kind) {
  105688. case 245 /* ClassDeclaration */:
  105689. case 246 /* InterfaceDeclaration */:
  105690. case 248 /* EnumDeclaration */:
  105691. case 193 /* ObjectLiteralExpression */:
  105692. case 189 /* ObjectBindingPattern */:
  105693. case 173 /* TypeLiteral */:
  105694. case 223 /* Block */:
  105695. case 250 /* ModuleBlock */:
  105696. case 251 /* CaseBlock */:
  105697. case 257 /* NamedImports */:
  105698. case 261 /* NamedExports */:
  105699. return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile);
  105700. case 280 /* CatchClause */:
  105701. return isCompletedNode(n.block, sourceFile);
  105702. case 197 /* NewExpression */:
  105703. if (!n.arguments) {
  105704. return true;
  105705. }
  105706. // falls through
  105707. case 196 /* CallExpression */:
  105708. case 200 /* ParenthesizedExpression */:
  105709. case 182 /* ParenthesizedType */:
  105710. return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile);
  105711. case 170 /* FunctionType */:
  105712. case 171 /* ConstructorType */:
  105713. return isCompletedNode(n.type, sourceFile);
  105714. case 162 /* Constructor */:
  105715. case 163 /* GetAccessor */:
  105716. case 164 /* SetAccessor */:
  105717. case 244 /* FunctionDeclaration */:
  105718. case 201 /* FunctionExpression */:
  105719. case 161 /* MethodDeclaration */:
  105720. case 160 /* MethodSignature */:
  105721. case 166 /* ConstructSignature */:
  105722. case 165 /* CallSignature */:
  105723. case 202 /* ArrowFunction */:
  105724. if (n.body) {
  105725. return isCompletedNode(n.body, sourceFile);
  105726. }
  105727. if (n.type) {
  105728. return isCompletedNode(n.type, sourceFile);
  105729. }
  105730. // Even though type parameters can be unclosed, we can get away with
  105731. // having at least a closing paren.
  105732. return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile);
  105733. case 249 /* ModuleDeclaration */:
  105734. return !!n.body && isCompletedNode(n.body, sourceFile);
  105735. case 227 /* IfStatement */:
  105736. if (n.elseStatement) {
  105737. return isCompletedNode(n.elseStatement, sourceFile);
  105738. }
  105739. return isCompletedNode(n.thenStatement, sourceFile);
  105740. case 226 /* ExpressionStatement */:
  105741. return isCompletedNode(n.expression, sourceFile) ||
  105742. hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile);
  105743. case 192 /* ArrayLiteralExpression */:
  105744. case 190 /* ArrayBindingPattern */:
  105745. case 195 /* ElementAccessExpression */:
  105746. case 154 /* ComputedPropertyName */:
  105747. case 175 /* TupleType */:
  105748. return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile);
  105749. case 167 /* IndexSignature */:
  105750. if (n.type) {
  105751. return isCompletedNode(n.type, sourceFile);
  105752. }
  105753. return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile);
  105754. case 277 /* CaseClause */:
  105755. case 278 /* DefaultClause */:
  105756. // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed
  105757. return false;
  105758. case 230 /* ForStatement */:
  105759. case 231 /* ForInStatement */:
  105760. case 232 /* ForOfStatement */:
  105761. case 229 /* WhileStatement */:
  105762. return isCompletedNode(n.statement, sourceFile);
  105763. case 228 /* DoStatement */:
  105764. // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
  105765. return hasChildOfKind(n, 111 /* WhileKeyword */, sourceFile)
  105766. ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile)
  105767. : isCompletedNode(n.statement, sourceFile);
  105768. case 172 /* TypeQuery */:
  105769. return isCompletedNode(n.exprName, sourceFile);
  105770. case 204 /* TypeOfExpression */:
  105771. case 203 /* DeleteExpression */:
  105772. case 205 /* VoidExpression */:
  105773. case 212 /* YieldExpression */:
  105774. case 213 /* SpreadElement */:
  105775. var unaryWordExpression = n;
  105776. return isCompletedNode(unaryWordExpression.expression, sourceFile);
  105777. case 198 /* TaggedTemplateExpression */:
  105778. return isCompletedNode(n.template, sourceFile);
  105779. case 211 /* TemplateExpression */:
  105780. var lastSpan = ts.lastOrUndefined(n.templateSpans);
  105781. return isCompletedNode(lastSpan, sourceFile);
  105782. case 221 /* TemplateSpan */:
  105783. return ts.nodeIsPresent(n.literal);
  105784. case 260 /* ExportDeclaration */:
  105785. case 254 /* ImportDeclaration */:
  105786. return ts.nodeIsPresent(n.moduleSpecifier);
  105787. case 207 /* PrefixUnaryExpression */:
  105788. return isCompletedNode(n.operand, sourceFile);
  105789. case 209 /* BinaryExpression */:
  105790. return isCompletedNode(n.right, sourceFile);
  105791. case 210 /* ConditionalExpression */:
  105792. return isCompletedNode(n.whenFalse, sourceFile);
  105793. default:
  105794. return true;
  105795. }
  105796. }
  105797. /*
  105798. * Checks if node ends with 'expectedLastToken'.
  105799. * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
  105800. */
  105801. function nodeEndsWith(n, expectedLastToken, sourceFile) {
  105802. var children = n.getChildren(sourceFile);
  105803. if (children.length) {
  105804. var lastChild = ts.last(children);
  105805. if (lastChild.kind === expectedLastToken) {
  105806. return true;
  105807. }
  105808. else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) {
  105809. return children[children.length - 2].kind === expectedLastToken;
  105810. }
  105811. }
  105812. return false;
  105813. }
  105814. function findListItemInfo(node) {
  105815. var list = findContainingList(node);
  105816. // It is possible at this point for syntaxList to be undefined, either if
  105817. // node.parent had no list child, or if none of its list children contained
  105818. // the span of node. If this happens, return undefined. The caller should
  105819. // handle this case.
  105820. if (!list) {
  105821. return undefined;
  105822. }
  105823. var children = list.getChildren();
  105824. var listItemIndex = ts.indexOfNode(children, node);
  105825. return {
  105826. listItemIndex: listItemIndex,
  105827. list: list
  105828. };
  105829. }
  105830. ts.findListItemInfo = findListItemInfo;
  105831. function hasChildOfKind(n, kind, sourceFile) {
  105832. return !!findChildOfKind(n, kind, sourceFile);
  105833. }
  105834. ts.hasChildOfKind = hasChildOfKind;
  105835. function findChildOfKind(n, kind, sourceFile) {
  105836. return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; });
  105837. }
  105838. ts.findChildOfKind = findChildOfKind;
  105839. function findContainingList(node) {
  105840. // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will
  105841. // be parented by the container of the SyntaxList, not the SyntaxList itself.
  105842. // In order to find the list item index, we first need to locate SyntaxList itself and then search
  105843. // for the position of the relevant node (or comma).
  105844. var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
  105845. // Either we didn't find an appropriate list, or the list must contain us.
  105846. ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
  105847. return syntaxList;
  105848. }
  105849. ts.findContainingList = findContainingList;
  105850. function isDefaultModifier(node) {
  105851. return node.kind === 84 /* DefaultKeyword */;
  105852. }
  105853. function isClassKeyword(node) {
  105854. return node.kind === 80 /* ClassKeyword */;
  105855. }
  105856. function isFunctionKeyword(node) {
  105857. return node.kind === 94 /* FunctionKeyword */;
  105858. }
  105859. function getAdjustedLocationForClass(node) {
  105860. if (ts.isNamedDeclaration(node)) {
  105861. return node.name;
  105862. }
  105863. if (ts.isClassDeclaration(node)) {
  105864. // for class and function declarations, use the `default` modifier
  105865. // when the declaration is unnamed.
  105866. var defaultModifier = ts.find(node.modifiers, isDefaultModifier);
  105867. if (defaultModifier)
  105868. return defaultModifier;
  105869. }
  105870. if (ts.isClassExpression(node)) {
  105871. // for class expressions, use the `class` keyword when the class is unnamed
  105872. var classKeyword = ts.find(node.getChildren(), isClassKeyword);
  105873. if (classKeyword)
  105874. return classKeyword;
  105875. }
  105876. }
  105877. function getAdjustedLocationForFunction(node) {
  105878. if (ts.isNamedDeclaration(node)) {
  105879. return node.name;
  105880. }
  105881. if (ts.isFunctionDeclaration(node)) {
  105882. // for class and function declarations, use the `default` modifier
  105883. // when the declaration is unnamed.
  105884. var defaultModifier = ts.find(node.modifiers, isDefaultModifier);
  105885. if (defaultModifier)
  105886. return defaultModifier;
  105887. }
  105888. if (ts.isFunctionExpression(node)) {
  105889. // for function expressions, use the `function` keyword when the function is unnamed
  105890. var functionKeyword = ts.find(node.getChildren(), isFunctionKeyword);
  105891. if (functionKeyword)
  105892. return functionKeyword;
  105893. }
  105894. }
  105895. function getAdjustedLocationForDeclaration(node, forRename) {
  105896. if (!forRename) {
  105897. switch (node.kind) {
  105898. case 245 /* ClassDeclaration */:
  105899. case 214 /* ClassExpression */:
  105900. return getAdjustedLocationForClass(node);
  105901. case 244 /* FunctionDeclaration */:
  105902. case 201 /* FunctionExpression */:
  105903. return getAdjustedLocationForFunction(node);
  105904. }
  105905. }
  105906. if (ts.isNamedDeclaration(node)) {
  105907. return node.name;
  105908. }
  105909. }
  105910. function getAdjustedLocationForImportDeclaration(node, forRename) {
  105911. if (node.importClause) {
  105912. if (node.importClause.name && node.importClause.namedBindings) {
  105913. // do not adjust if we have both a name and named bindings
  105914. return;
  105915. }
  105916. // /**/import [|name|] from ...;
  105917. // import /**/type [|name|] from ...;
  105918. if (node.importClause.name) {
  105919. return node.importClause.name;
  105920. }
  105921. // /**/import { [|name|] } from ...;
  105922. // /**/import { propertyName as [|name|] } from ...;
  105923. // /**/import * as [|name|] from ...;
  105924. // import /**/type { [|name|] } from ...;
  105925. // import /**/type { propertyName as [|name|] } from ...;
  105926. // import /**/type * as [|name|] from ...;
  105927. if (node.importClause.namedBindings) {
  105928. if (ts.isNamedImports(node.importClause.namedBindings)) {
  105929. // do nothing if there is more than one binding
  105930. var onlyBinding = ts.singleOrUndefined(node.importClause.namedBindings.elements);
  105931. if (!onlyBinding) {
  105932. return;
  105933. }
  105934. return onlyBinding.name;
  105935. }
  105936. else if (ts.isNamespaceImport(node.importClause.namedBindings)) {
  105937. return node.importClause.namedBindings.name;
  105938. }
  105939. }
  105940. }
  105941. if (!forRename) {
  105942. // /**/import "[|module|]";
  105943. // /**/import ... from "[|module|]";
  105944. // import /**/type ... from "[|module|]";
  105945. return node.moduleSpecifier;
  105946. }
  105947. }
  105948. function getAdjustedLocationForExportDeclaration(node, forRename) {
  105949. if (node.exportClause) {
  105950. // /**/export { [|name|] } ...
  105951. // /**/export { propertyName as [|name|] } ...
  105952. // /**/export * as [|name|] ...
  105953. // export /**/type { [|name|] } from ...
  105954. // export /**/type { propertyName as [|name|] } from ...
  105955. // export /**/type * as [|name|] ...
  105956. if (ts.isNamedExports(node.exportClause)) {
  105957. // do nothing if there is more than one binding
  105958. var onlyBinding = ts.singleOrUndefined(node.exportClause.elements);
  105959. if (!onlyBinding) {
  105960. return;
  105961. }
  105962. return node.exportClause.elements[0].name;
  105963. }
  105964. else if (ts.isNamespaceExport(node.exportClause)) {
  105965. return node.exportClause.name;
  105966. }
  105967. }
  105968. if (!forRename) {
  105969. // /**/export * from "[|module|]";
  105970. // export /**/type * from "[|module|]";
  105971. return node.moduleSpecifier;
  105972. }
  105973. }
  105974. function getAdjustedLocationForHeritageClause(node) {
  105975. // /**/extends [|name|]
  105976. // /**/implements [|name|]
  105977. if (node.types.length === 1) {
  105978. return node.types[0].expression;
  105979. }
  105980. // /**/extends name1, name2 ...
  105981. // /**/implements name1, name2 ...
  105982. }
  105983. function getAdjustedLocation(node, forRename) {
  105984. var parent = node.parent;
  105985. // /**/<modifier> [|name|] ...
  105986. // /**/<modifier> <class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
  105987. // /**/<class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
  105988. // /**/import [|name|] = ...
  105989. //
  105990. // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled
  105991. // specially by `getSymbolAtLocation`.
  105992. if (ts.isModifier(node) && (forRename || node.kind !== 84 /* DefaultKeyword */) ? ts.contains(parent.modifiers, node) :
  105993. node.kind === 80 /* ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) :
  105994. node.kind === 94 /* FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) :
  105995. node.kind === 114 /* InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) :
  105996. node.kind === 88 /* EnumKeyword */ ? ts.isEnumDeclaration(parent) :
  105997. node.kind === 145 /* TypeKeyword */ ? ts.isTypeAliasDeclaration(parent) :
  105998. node.kind === 136 /* NamespaceKeyword */ || node.kind === 135 /* ModuleKeyword */ ? ts.isModuleDeclaration(parent) :
  105999. node.kind === 96 /* ImportKeyword */ ? ts.isImportEqualsDeclaration(parent) :
  106000. node.kind === 131 /* GetKeyword */ ? ts.isGetAccessorDeclaration(parent) :
  106001. node.kind === 142 /* SetKeyword */ && ts.isSetAccessorDeclaration(parent)) {
  106002. var location = getAdjustedLocationForDeclaration(parent, forRename);
  106003. if (location) {
  106004. return location;
  106005. }
  106006. }
  106007. // /**/<var|let|const> [|name|] ...
  106008. if ((node.kind === 109 /* VarKeyword */ || node.kind === 81 /* ConstKeyword */ || node.kind === 115 /* LetKeyword */) &&
  106009. ts.isVariableDeclarationList(parent) && parent.declarations.length === 1) {
  106010. var decl = parent.declarations[0];
  106011. if (ts.isIdentifier(decl.name)) {
  106012. return decl.name;
  106013. }
  106014. }
  106015. if (node.kind === 145 /* TypeKeyword */) {
  106016. // import /**/type [|name|] from ...;
  106017. // import /**/type { [|name|] } from ...;
  106018. // import /**/type { propertyName as [|name|] } from ...;
  106019. // import /**/type ... from "[|module|]";
  106020. if (ts.isImportClause(parent) && parent.isTypeOnly) {
  106021. var location = getAdjustedLocationForImportDeclaration(parent.parent, forRename);
  106022. if (location) {
  106023. return location;
  106024. }
  106025. }
  106026. // export /**/type { [|name|] } from ...;
  106027. // export /**/type { propertyName as [|name|] } from ...;
  106028. // export /**/type * from "[|module|]";
  106029. // export /**/type * as ... from "[|module|]";
  106030. if (ts.isExportDeclaration(parent) && parent.isTypeOnly) {
  106031. var location = getAdjustedLocationForExportDeclaration(parent, forRename);
  106032. if (location) {
  106033. return location;
  106034. }
  106035. }
  106036. }
  106037. // import { propertyName /**/as [|name|] } ...
  106038. // import * /**/as [|name|] ...
  106039. // export { propertyName /**/as [|name|] } ...
  106040. // export * /**/as [|name|] ...
  106041. if (node.kind === 123 /* AsKeyword */) {
  106042. if (ts.isImportSpecifier(parent) && parent.propertyName ||
  106043. ts.isExportSpecifier(parent) && parent.propertyName ||
  106044. ts.isNamespaceImport(parent) ||
  106045. ts.isNamespaceExport(parent)) {
  106046. return parent.name;
  106047. }
  106048. if (ts.isExportDeclaration(parent) && parent.exportClause && ts.isNamespaceExport(parent.exportClause)) {
  106049. return parent.exportClause.name;
  106050. }
  106051. }
  106052. // /**/import [|name|] from ...;
  106053. // /**/import { [|name|] } from ...;
  106054. // /**/import { propertyName as [|name|] } from ...;
  106055. // /**/import ... from "[|module|]";
  106056. // /**/import "[|module|]";
  106057. if (node.kind === 96 /* ImportKeyword */ && ts.isImportDeclaration(parent)) {
  106058. var location = getAdjustedLocationForImportDeclaration(parent, forRename);
  106059. if (location) {
  106060. return location;
  106061. }
  106062. }
  106063. if (node.kind === 89 /* ExportKeyword */) {
  106064. // /**/export { [|name|] } ...;
  106065. // /**/export { propertyName as [|name|] } ...;
  106066. // /**/export * from "[|module|]";
  106067. // /**/export * as ... from "[|module|]";
  106068. if (ts.isExportDeclaration(parent)) {
  106069. var location = getAdjustedLocationForExportDeclaration(parent, forRename);
  106070. if (location) {
  106071. return location;
  106072. }
  106073. }
  106074. // NOTE: We don't adjust the location of the `default` keyword as that is handled specially by `getSymbolAtLocation`.
  106075. // /**/export default [|name|];
  106076. // /**/export = [|name|];
  106077. if (ts.isExportAssignment(parent)) {
  106078. return ts.skipOuterExpressions(parent.expression);
  106079. }
  106080. }
  106081. // import name = /**/require("[|module|]");
  106082. if (node.kind === 139 /* RequireKeyword */ && ts.isExternalModuleReference(parent)) {
  106083. return parent.expression;
  106084. }
  106085. // import ... /**/from "[|module|]";
  106086. // export ... /**/from "[|module|]";
  106087. if (node.kind === 149 /* FromKeyword */ && (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) && parent.moduleSpecifier) {
  106088. return parent.moduleSpecifier;
  106089. }
  106090. // class ... /**/extends [|name|] ...
  106091. // class ... /**/implements [|name|] ...
  106092. // class ... /**/implements name1, name2 ...
  106093. // interface ... /**/extends [|name|] ...
  106094. // interface ... /**/extends name1, name2 ...
  106095. if ((node.kind === 90 /* ExtendsKeyword */ || node.kind === 113 /* ImplementsKeyword */) && ts.isHeritageClause(parent) && parent.token === node.kind) {
  106096. var location = getAdjustedLocationForHeritageClause(parent);
  106097. if (location) {
  106098. return location;
  106099. }
  106100. }
  106101. if (node.kind === 90 /* ExtendsKeyword */) {
  106102. // ... <T /**/extends [|U|]> ...
  106103. if (ts.isTypeParameterDeclaration(parent) && parent.constraint && ts.isTypeReferenceNode(parent.constraint)) {
  106104. return parent.constraint.typeName;
  106105. }
  106106. // ... T /**/extends [|U|] ? ...
  106107. if (ts.isConditionalTypeNode(parent) && ts.isTypeReferenceNode(parent.extendsType)) {
  106108. return parent.extendsType.typeName;
  106109. }
  106110. }
  106111. // ... T extends /**/infer [|U|] ? ...
  106112. if (node.kind === 132 /* InferKeyword */ && ts.isInferTypeNode(parent)) {
  106113. return parent.typeParameter.name;
  106114. }
  106115. // { [ [|K|] /**/in keyof T]: ... }
  106116. if (node.kind === 97 /* InKeyword */ && ts.isTypeParameterDeclaration(parent) && ts.isMappedTypeNode(parent.parent)) {
  106117. return parent.name;
  106118. }
  106119. // /**/keyof [|T|]
  106120. if (node.kind === 134 /* KeyOfKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 134 /* KeyOfKeyword */ &&
  106121. ts.isTypeReferenceNode(parent.type)) {
  106122. return parent.type.typeName;
  106123. }
  106124. // /**/readonly [|name|][]
  106125. if (node.kind === 138 /* ReadonlyKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 138 /* ReadonlyKeyword */ &&
  106126. ts.isArrayTypeNode(parent.type) && ts.isTypeReferenceNode(parent.type.elementType)) {
  106127. return parent.type.elementType.typeName;
  106128. }
  106129. if (!forRename) {
  106130. // /**/new [|name|]
  106131. // /**/void [|name|]
  106132. // /**/void obj.[|name|]
  106133. // /**/typeof [|name|]
  106134. // /**/typeof obj.[|name|]
  106135. // /**/await [|name|]
  106136. // /**/await obj.[|name|]
  106137. // /**/yield [|name|]
  106138. // /**/yield obj.[|name|]
  106139. // /**/delete obj.[|name|]
  106140. if (node.kind === 99 /* NewKeyword */ && ts.isNewExpression(parent) ||
  106141. node.kind === 110 /* VoidKeyword */ && ts.isVoidExpression(parent) ||
  106142. node.kind === 108 /* TypeOfKeyword */ && ts.isTypeOfExpression(parent) ||
  106143. node.kind === 127 /* AwaitKeyword */ && ts.isAwaitExpression(parent) ||
  106144. node.kind === 121 /* YieldKeyword */ && ts.isYieldExpression(parent) ||
  106145. node.kind === 85 /* DeleteKeyword */ && ts.isDeleteExpression(parent)) {
  106146. if (parent.expression) {
  106147. return ts.skipOuterExpressions(parent.expression);
  106148. }
  106149. }
  106150. // left /**/in [|name|]
  106151. // left /**/instanceof [|name|]
  106152. if ((node.kind === 97 /* InKeyword */ || node.kind === 98 /* InstanceOfKeyword */) && ts.isBinaryExpression(parent) && parent.operatorToken === node) {
  106153. return ts.skipOuterExpressions(parent.right);
  106154. }
  106155. // left /**/as [|name|]
  106156. if (node.kind === 123 /* AsKeyword */ && ts.isAsExpression(parent) && ts.isTypeReferenceNode(parent.type)) {
  106157. return parent.type.typeName;
  106158. }
  106159. // for (... /**/in [|name|])
  106160. // for (... /**/of [|name|])
  106161. if (node.kind === 97 /* InKeyword */ && ts.isForInStatement(parent) ||
  106162. node.kind === 152 /* OfKeyword */ && ts.isForOfStatement(parent)) {
  106163. return ts.skipOuterExpressions(parent.expression);
  106164. }
  106165. }
  106166. return node;
  106167. }
  106168. /**
  106169. * Adjusts the location used for "find references" and "go to definition" when the cursor was not
  106170. * on a property name.
  106171. */
  106172. function getAdjustedReferenceLocation(node) {
  106173. return getAdjustedLocation(node, /*forRename*/ false);
  106174. }
  106175. ts.getAdjustedReferenceLocation = getAdjustedReferenceLocation;
  106176. /**
  106177. * Adjusts the location used for "rename" when the cursor was not on a property name.
  106178. */
  106179. function getAdjustedRenameLocation(node) {
  106180. return getAdjustedLocation(node, /*forRename*/ true);
  106181. }
  106182. ts.getAdjustedRenameLocation = getAdjustedRenameLocation;
  106183. /**
  106184. * Gets the token whose text has range [start, end) and
  106185. * position >= start and (position < end or (position === end && token is literal or keyword or identifier))
  106186. */
  106187. function getTouchingPropertyName(sourceFile, position) {
  106188. return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind) || ts.isPrivateIdentifier(n); });
  106189. }
  106190. ts.getTouchingPropertyName = getTouchingPropertyName;
  106191. /**
  106192. * Returns the token if position is in [start, end).
  106193. * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true
  106194. */
  106195. function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) {
  106196. return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false);
  106197. }
  106198. ts.getTouchingToken = getTouchingToken;
  106199. /** Returns a token if position is in [start-of-leading-trivia, end) */
  106200. function getTokenAtPosition(sourceFile, position) {
  106201. return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false);
  106202. }
  106203. ts.getTokenAtPosition = getTokenAtPosition;
  106204. /** Get the token whose text contains the position */
  106205. function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) {
  106206. var current = sourceFile;
  106207. outer: while (true) {
  106208. // find the child that contains 'position'
  106209. for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) {
  106210. var child = _a[_i];
  106211. var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true);
  106212. if (start > position) {
  106213. // If this child begins after position, then all subsequent children will as well.
  106214. break;
  106215. }
  106216. var end = child.getEnd();
  106217. if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) {
  106218. current = child;
  106219. continue outer;
  106220. }
  106221. else if (includePrecedingTokenAtEndPosition && end === position) {
  106222. var previousToken = findPrecedingToken(position, sourceFile, child);
  106223. if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) {
  106224. return previousToken;
  106225. }
  106226. }
  106227. }
  106228. return current;
  106229. }
  106230. }
  106231. /**
  106232. * The token on the left of the position is the token that strictly includes the position
  106233. * or sits to the left of the cursor if it is on a boundary. For example
  106234. *
  106235. * fo|o -> will return foo
  106236. * foo <comment> |bar -> will return foo
  106237. *
  106238. */
  106239. function findTokenOnLeftOfPosition(file, position) {
  106240. // Ideally, getTokenAtPosition should return a token. However, it is currently
  106241. // broken, so we do a check to make sure the result was indeed a token.
  106242. var tokenAtPosition = getTokenAtPosition(file, position);
  106243. if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
  106244. return tokenAtPosition;
  106245. }
  106246. return findPrecedingToken(position, file);
  106247. }
  106248. ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
  106249. function findNextToken(previousToken, parent, sourceFile) {
  106250. return find(parent);
  106251. function find(n) {
  106252. if (ts.isToken(n) && n.pos === previousToken.end) {
  106253. // this is token that starts at the end of previous token - return it
  106254. return n;
  106255. }
  106256. return ts.firstDefined(n.getChildren(sourceFile), function (child) {
  106257. var shouldDiveInChildNode =
  106258. // previous token is enclosed somewhere in the child
  106259. (child.pos <= previousToken.pos && child.end > previousToken.end) ||
  106260. // previous token ends exactly at the beginning of child
  106261. (child.pos === previousToken.end);
  106262. return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined;
  106263. });
  106264. }
  106265. }
  106266. ts.findNextToken = findNextToken;
  106267. /**
  106268. * Finds the rightmost token satisfying `token.end <= position`,
  106269. * excluding `JsxText` tokens containing only whitespace.
  106270. */
  106271. function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) {
  106272. var result = find(startNode || sourceFile);
  106273. ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
  106274. return result;
  106275. function find(n) {
  106276. if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
  106277. return n;
  106278. }
  106279. var children = n.getChildren(sourceFile);
  106280. for (var i = 0; i < children.length; i++) {
  106281. var child = children[i];
  106282. // Note that the span of a node's tokens is [node.getStart(...), node.end).
  106283. // Given that `position < child.end` and child has constituent tokens, we distinguish these cases:
  106284. // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`):
  106285. // we need to find the last token in a previous child.
  106286. // 2) `position` is within the same span: we recurse on `child`.
  106287. if (position < child.end) {
  106288. var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc);
  106289. var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
  106290. !nodeHasTokens(child, sourceFile) ||
  106291. isWhiteSpaceOnlyJsxText(child);
  106292. if (lookInPreviousChild) {
  106293. // actual start of the node is past the position - previous token should be at the end of previous child
  106294. var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
  106295. return candidate_1 && findRightmostToken(candidate_1, sourceFile);
  106296. }
  106297. else {
  106298. // candidate should be in this node
  106299. return find(child);
  106300. }
  106301. }
  106302. }
  106303. ts.Debug.assert(startNode !== undefined || n.kind === 290 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
  106304. // Here we know that none of child token nodes embrace the position,
  106305. // the only known case is when position is at the end of the file.
  106306. // Try to find the rightmost token in the file without filtering.
  106307. // Namely we are skipping the check: 'position < node.end'
  106308. var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
  106309. return candidate && findRightmostToken(candidate, sourceFile);
  106310. }
  106311. }
  106312. ts.findPrecedingToken = findPrecedingToken;
  106313. function isNonWhitespaceToken(n) {
  106314. return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n);
  106315. }
  106316. function findRightmostToken(n, sourceFile) {
  106317. if (isNonWhitespaceToken(n)) {
  106318. return n;
  106319. }
  106320. var children = n.getChildren(sourceFile);
  106321. var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
  106322. return candidate && findRightmostToken(candidate, sourceFile);
  106323. }
  106324. /**
  106325. * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
  106326. */
  106327. function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
  106328. for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
  106329. var child = children[i];
  106330. if (isWhiteSpaceOnlyJsxText(child)) {
  106331. ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
  106332. }
  106333. else if (nodeHasTokens(children[i], sourceFile)) {
  106334. return children[i];
  106335. }
  106336. }
  106337. }
  106338. function isInString(sourceFile, position, previousToken) {
  106339. if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); }
  106340. if (previousToken && ts.isStringTextContainingNode(previousToken)) {
  106341. var start = previousToken.getStart(sourceFile);
  106342. var end = previousToken.getEnd();
  106343. // To be "in" one of these literals, the position has to be:
  106344. // 1. entirely within the token text.
  106345. // 2. at the end position of an unterminated token.
  106346. // 3. at the end of a regular expression (due to trailing flags like '/foo/g').
  106347. if (start < position && position < end) {
  106348. return true;
  106349. }
  106350. if (position === end) {
  106351. return !!previousToken.isUnterminated;
  106352. }
  106353. }
  106354. return false;
  106355. }
  106356. ts.isInString = isInString;
  106357. /**
  106358. * returns true if the position is in between the open and close elements of an JSX expression.
  106359. */
  106360. function isInsideJsxElementOrAttribute(sourceFile, position) {
  106361. var token = getTokenAtPosition(sourceFile, position);
  106362. if (!token) {
  106363. return false;
  106364. }
  106365. if (token.kind === 11 /* JsxText */) {
  106366. return true;
  106367. }
  106368. // <div>Hello |</div>
  106369. if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) {
  106370. return true;
  106371. }
  106372. // <div> { | </div> or <div a={| </div>
  106373. if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxExpression */) {
  106374. return true;
  106375. }
  106376. // <div> {
  106377. // |
  106378. // } < /div>
  106379. if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 276 /* JsxExpression */) {
  106380. return true;
  106381. }
  106382. // <div>|</div>
  106383. if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 269 /* JsxClosingElement */) {
  106384. return true;
  106385. }
  106386. return false;
  106387. }
  106388. ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
  106389. function isWhiteSpaceOnlyJsxText(node) {
  106390. return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
  106391. }
  106392. function isInTemplateString(sourceFile, position) {
  106393. var token = getTokenAtPosition(sourceFile, position);
  106394. return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
  106395. }
  106396. ts.isInTemplateString = isInTemplateString;
  106397. function isInJSXText(sourceFile, position) {
  106398. var token = getTokenAtPosition(sourceFile, position);
  106399. if (ts.isJsxText(token)) {
  106400. return true;
  106401. }
  106402. if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) {
  106403. return true;
  106404. }
  106405. if (token.kind === 29 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) {
  106406. return true;
  106407. }
  106408. return false;
  106409. }
  106410. ts.isInJSXText = isInJSXText;
  106411. function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
  106412. var tokenKind = token.kind;
  106413. var remainingMatchingTokens = 0;
  106414. while (true) {
  106415. var preceding = findPrecedingToken(token.getFullStart(), sourceFile);
  106416. if (!preceding) {
  106417. return undefined;
  106418. }
  106419. token = preceding;
  106420. if (token.kind === matchingTokenKind) {
  106421. if (remainingMatchingTokens === 0) {
  106422. return token;
  106423. }
  106424. remainingMatchingTokens--;
  106425. }
  106426. else if (token.kind === tokenKind) {
  106427. remainingMatchingTokens++;
  106428. }
  106429. }
  106430. }
  106431. ts.findPrecedingMatchingToken = findPrecedingMatchingToken;
  106432. function removeOptionality(type, isOptionalExpression, isOptionalChain) {
  106433. return isOptionalExpression ? type.getNonNullableType() :
  106434. isOptionalChain ? type.getNonOptionalType() :
  106435. type;
  106436. }
  106437. ts.removeOptionality = removeOptionality;
  106438. function isPossiblyTypeArgumentPosition(token, sourceFile, checker) {
  106439. var info = getPossibleTypeArgumentsInfo(token, sourceFile);
  106440. return info !== undefined && (ts.isPartOfTypeNode(info.called) ||
  106441. getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 ||
  106442. isPossiblyTypeArgumentPosition(info.called, sourceFile, checker));
  106443. }
  106444. ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition;
  106445. function getPossibleGenericSignatures(called, typeArgumentCount, checker) {
  106446. var type = checker.getTypeAtLocation(called);
  106447. if (ts.isOptionalChain(called.parent)) {
  106448. type = removeOptionality(type, !!called.parent.questionDotToken, /*isOptionalChain*/ true);
  106449. }
  106450. var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures();
  106451. return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; });
  106452. }
  106453. ts.getPossibleGenericSignatures = getPossibleGenericSignatures;
  106454. // Get info for an expression like `f <` that may be the start of type arguments.
  106455. function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
  106456. var token = tokenIn;
  106457. // This function determines if the node could be type argument position
  106458. // Since during editing, when type argument list is not complete,
  106459. // the tree could be of any shape depending on the tokens parsed before current node,
  106460. // scanning of the previous identifier followed by "<" before current node would give us better result
  106461. // Note that we also balance out the already provided type arguments, arrays, object literals while doing so
  106462. var remainingLessThanTokens = 0;
  106463. var nTypeArguments = 0;
  106464. while (token) {
  106465. switch (token.kind) {
  106466. case 29 /* LessThanToken */:
  106467. // Found the beginning of the generic argument expression
  106468. token = findPrecedingToken(token.getFullStart(), sourceFile);
  106469. if (token && token.kind === 28 /* QuestionDotToken */) {
  106470. token = findPrecedingToken(token.getFullStart(), sourceFile);
  106471. }
  106472. if (!token || !ts.isIdentifier(token))
  106473. return undefined;
  106474. if (!remainingLessThanTokens) {
  106475. return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments };
  106476. }
  106477. remainingLessThanTokens--;
  106478. break;
  106479. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  106480. remainingLessThanTokens = +3;
  106481. break;
  106482. case 48 /* GreaterThanGreaterThanToken */:
  106483. remainingLessThanTokens = +2;
  106484. break;
  106485. case 31 /* GreaterThanToken */:
  106486. remainingLessThanTokens++;
  106487. break;
  106488. case 19 /* CloseBraceToken */:
  106489. // This can be object type, skip until we find the matching open brace token
  106490. // Skip until the matching open brace token
  106491. token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile);
  106492. if (!token)
  106493. return undefined;
  106494. break;
  106495. case 21 /* CloseParenToken */:
  106496. // This can be object type, skip until we find the matching open brace token
  106497. // Skip until the matching open brace token
  106498. token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile);
  106499. if (!token)
  106500. return undefined;
  106501. break;
  106502. case 23 /* CloseBracketToken */:
  106503. // This can be object type, skip until we find the matching open brace token
  106504. // Skip until the matching open brace token
  106505. token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile);
  106506. if (!token)
  106507. return undefined;
  106508. break;
  106509. // Valid tokens in a type name. Skip.
  106510. case 27 /* CommaToken */:
  106511. nTypeArguments++;
  106512. break;
  106513. case 38 /* EqualsGreaterThanToken */:
  106514. // falls through
  106515. case 75 /* Identifier */:
  106516. case 10 /* StringLiteral */:
  106517. case 8 /* NumericLiteral */:
  106518. case 9 /* BigIntLiteral */:
  106519. case 106 /* TrueKeyword */:
  106520. case 91 /* FalseKeyword */:
  106521. // falls through
  106522. case 108 /* TypeOfKeyword */:
  106523. case 90 /* ExtendsKeyword */:
  106524. case 134 /* KeyOfKeyword */:
  106525. case 24 /* DotToken */:
  106526. case 51 /* BarToken */:
  106527. case 57 /* QuestionToken */:
  106528. case 58 /* ColonToken */:
  106529. break;
  106530. default:
  106531. if (ts.isTypeNode(token)) {
  106532. break;
  106533. }
  106534. // Invalid token in type
  106535. return undefined;
  106536. }
  106537. token = findPrecedingToken(token.getFullStart(), sourceFile);
  106538. }
  106539. return undefined;
  106540. }
  106541. ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo;
  106542. /**
  106543. * Returns true if the cursor at position in sourceFile is within a comment.
  106544. *
  106545. * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
  106546. * @param predicate Additional predicate to test on the comment range.
  106547. */
  106548. function isInComment(sourceFile, position, tokenAtPosition) {
  106549. return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition);
  106550. }
  106551. ts.isInComment = isInComment;
  106552. function hasDocComment(sourceFile, position) {
  106553. var token = getTokenAtPosition(sourceFile, position);
  106554. return !!ts.findAncestor(token, ts.isJSDoc);
  106555. }
  106556. ts.hasDocComment = hasDocComment;
  106557. function nodeHasTokens(n, sourceFile) {
  106558. // If we have a token or node that has a non-zero width, it must have tokens.
  106559. // Note: getWidth() does not take trivia into account.
  106560. return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
  106561. }
  106562. function getNodeModifiers(node) {
  106563. var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */;
  106564. var result = [];
  106565. if (flags & 8 /* Private */)
  106566. result.push("private" /* privateMemberModifier */);
  106567. if (flags & 16 /* Protected */)
  106568. result.push("protected" /* protectedMemberModifier */);
  106569. if (flags & 4 /* Public */)
  106570. result.push("public" /* publicMemberModifier */);
  106571. if (flags & 32 /* Static */)
  106572. result.push("static" /* staticModifier */);
  106573. if (flags & 128 /* Abstract */)
  106574. result.push("abstract" /* abstractModifier */);
  106575. if (flags & 1 /* Export */)
  106576. result.push("export" /* exportedModifier */);
  106577. if (node.flags & 8388608 /* Ambient */)
  106578. result.push("declare" /* ambientModifier */);
  106579. if (node.kind === 259 /* ExportAssignment */)
  106580. result.push("export" /* exportedModifier */);
  106581. return result.length > 0 ? result.join(",") : "" /* none */;
  106582. }
  106583. ts.getNodeModifiers = getNodeModifiers;
  106584. function getTypeArgumentOrTypeParameterList(node) {
  106585. if (node.kind === 169 /* TypeReference */ || node.kind === 196 /* CallExpression */) {
  106586. return node.typeArguments;
  106587. }
  106588. if (ts.isFunctionLike(node) || node.kind === 245 /* ClassDeclaration */ || node.kind === 246 /* InterfaceDeclaration */) {
  106589. return node.typeParameters;
  106590. }
  106591. return undefined;
  106592. }
  106593. ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList;
  106594. function isComment(kind) {
  106595. return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
  106596. }
  106597. ts.isComment = isComment;
  106598. function isStringOrRegularExpressionOrTemplateLiteral(kind) {
  106599. if (kind === 10 /* StringLiteral */
  106600. || kind === 13 /* RegularExpressionLiteral */
  106601. || ts.isTemplateLiteralKind(kind)) {
  106602. return true;
  106603. }
  106604. return false;
  106605. }
  106606. ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral;
  106607. function isPunctuation(kind) {
  106608. return 18 /* FirstPunctuation */ <= kind && kind <= 74 /* LastPunctuation */;
  106609. }
  106610. ts.isPunctuation = isPunctuation;
  106611. function isInsideTemplateLiteral(node, position, sourceFile) {
  106612. return ts.isTemplateLiteralKind(node.kind)
  106613. && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end);
  106614. }
  106615. ts.isInsideTemplateLiteral = isInsideTemplateLiteral;
  106616. function isAccessibilityModifier(kind) {
  106617. switch (kind) {
  106618. case 119 /* PublicKeyword */:
  106619. case 117 /* PrivateKeyword */:
  106620. case 118 /* ProtectedKeyword */:
  106621. return true;
  106622. }
  106623. return false;
  106624. }
  106625. ts.isAccessibilityModifier = isAccessibilityModifier;
  106626. function cloneCompilerOptions(options) {
  106627. var result = ts.clone(options);
  106628. ts.setConfigFileInOptions(result, options && options.configFile);
  106629. return result;
  106630. }
  106631. ts.cloneCompilerOptions = cloneCompilerOptions;
  106632. function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
  106633. if (node.kind === 192 /* ArrayLiteralExpression */ ||
  106634. node.kind === 193 /* ObjectLiteralExpression */) {
  106635. // [a,b,c] from:
  106636. // [a, b, c] = someExpression;
  106637. if (node.parent.kind === 209 /* BinaryExpression */ &&
  106638. node.parent.left === node &&
  106639. node.parent.operatorToken.kind === 62 /* EqualsToken */) {
  106640. return true;
  106641. }
  106642. // [a, b, c] from:
  106643. // for([a, b, c] of expression)
  106644. if (node.parent.kind === 232 /* ForOfStatement */ &&
  106645. node.parent.initializer === node) {
  106646. return true;
  106647. }
  106648. // [a, b, c] of
  106649. // [x, [a, b, c] ] = someExpression
  106650. // or
  106651. // {x, a: {a, b, c} } = someExpression
  106652. if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 281 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
  106653. return true;
  106654. }
  106655. }
  106656. return false;
  106657. }
  106658. ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
  106659. function isInReferenceComment(sourceFile, position) {
  106660. return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true);
  106661. }
  106662. ts.isInReferenceComment = isInReferenceComment;
  106663. function isInNonReferenceComment(sourceFile, position) {
  106664. return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false);
  106665. }
  106666. ts.isInNonReferenceComment = isInNonReferenceComment;
  106667. function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
  106668. var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined);
  106669. return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
  106670. }
  106671. function createTextSpanFromNode(node, sourceFile, endNode) {
  106672. return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd());
  106673. }
  106674. ts.createTextSpanFromNode = createTextSpanFromNode;
  106675. function createTextRangeFromNode(node, sourceFile) {
  106676. return ts.createRange(node.getStart(sourceFile), node.end);
  106677. }
  106678. ts.createTextRangeFromNode = createTextRangeFromNode;
  106679. function createTextSpanFromRange(range) {
  106680. return ts.createTextSpanFromBounds(range.pos, range.end);
  106681. }
  106682. ts.createTextSpanFromRange = createTextSpanFromRange;
  106683. function createTextRangeFromSpan(span) {
  106684. return ts.createRange(span.start, span.start + span.length);
  106685. }
  106686. ts.createTextRangeFromSpan = createTextRangeFromSpan;
  106687. function createTextChangeFromStartLength(start, length, newText) {
  106688. return createTextChange(ts.createTextSpan(start, length), newText);
  106689. }
  106690. ts.createTextChangeFromStartLength = createTextChangeFromStartLength;
  106691. function createTextChange(span, newText) {
  106692. return { span: span, newText: newText };
  106693. }
  106694. ts.createTextChange = createTextChange;
  106695. ts.typeKeywords = [
  106696. 125 /* AnyKeyword */,
  106697. 124 /* AssertsKeyword */,
  106698. 151 /* BigIntKeyword */,
  106699. 128 /* BooleanKeyword */,
  106700. 91 /* FalseKeyword */,
  106701. 134 /* KeyOfKeyword */,
  106702. 137 /* NeverKeyword */,
  106703. 100 /* NullKeyword */,
  106704. 140 /* NumberKeyword */,
  106705. 141 /* ObjectKeyword */,
  106706. 138 /* ReadonlyKeyword */,
  106707. 143 /* StringKeyword */,
  106708. 144 /* SymbolKeyword */,
  106709. 106 /* TrueKeyword */,
  106710. 110 /* VoidKeyword */,
  106711. 146 /* UndefinedKeyword */,
  106712. 147 /* UniqueKeyword */,
  106713. 148 /* UnknownKeyword */,
  106714. ];
  106715. function isTypeKeyword(kind) {
  106716. return ts.contains(ts.typeKeywords, kind);
  106717. }
  106718. ts.isTypeKeyword = isTypeKeyword;
  106719. function isTypeKeywordToken(node) {
  106720. return node.kind === 145 /* TypeKeyword */;
  106721. }
  106722. ts.isTypeKeywordToken = isTypeKeywordToken;
  106723. /** True if the symbol is for an external module, as opposed to a namespace. */
  106724. function isExternalModuleSymbol(moduleSymbol) {
  106725. return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
  106726. }
  106727. ts.isExternalModuleSymbol = isExternalModuleSymbol;
  106728. function nodeSeenTracker() {
  106729. var seen = [];
  106730. return function (node) {
  106731. var id = ts.getNodeId(node);
  106732. return !seen[id] && (seen[id] = true);
  106733. };
  106734. }
  106735. ts.nodeSeenTracker = nodeSeenTracker;
  106736. function getSnapshotText(snap) {
  106737. return snap.getText(0, snap.getLength());
  106738. }
  106739. ts.getSnapshotText = getSnapshotText;
  106740. function repeatString(str, count) {
  106741. var result = "";
  106742. for (var i = 0; i < count; i++) {
  106743. result += str;
  106744. }
  106745. return result;
  106746. }
  106747. ts.repeatString = repeatString;
  106748. function skipConstraint(type) {
  106749. return type.isTypeParameter() ? type.getConstraint() || type : type;
  106750. }
  106751. ts.skipConstraint = skipConstraint;
  106752. function getNameFromPropertyName(name) {
  106753. return name.kind === 154 /* ComputedPropertyName */
  106754. // treat computed property names where expression is string/numeric literal as just string/numeric literal
  106755. ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined
  106756. : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name);
  106757. }
  106758. ts.getNameFromPropertyName = getNameFromPropertyName;
  106759. function programContainsEs6Modules(program) {
  106760. return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; });
  106761. }
  106762. ts.programContainsEs6Modules = programContainsEs6Modules;
  106763. function compilerOptionsIndicateEs6Modules(compilerOptions) {
  106764. return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit;
  106765. }
  106766. ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules;
  106767. function hostUsesCaseSensitiveFileNames(host) {
  106768. return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
  106769. }
  106770. ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
  106771. function hostGetCanonicalFileName(host) {
  106772. return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
  106773. }
  106774. ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
  106775. function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) {
  106776. return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined;
  106777. }
  106778. ts.makeImportIfNecessary = makeImportIfNecessary;
  106779. function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) {
  106780. return ts.createImportDeclaration(
  106781. /*decorators*/ undefined,
  106782. /*modifiers*/ undefined, defaultImport || namedImports
  106783. ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined, isTypeOnly)
  106784. : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier);
  106785. }
  106786. ts.makeImport = makeImport;
  106787. function makeStringLiteral(text, quotePreference) {
  106788. return ts.createLiteral(text, quotePreference === 0 /* Single */);
  106789. }
  106790. ts.makeStringLiteral = makeStringLiteral;
  106791. var QuotePreference;
  106792. (function (QuotePreference) {
  106793. QuotePreference[QuotePreference["Single"] = 0] = "Single";
  106794. QuotePreference[QuotePreference["Double"] = 1] = "Double";
  106795. })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {}));
  106796. function quotePreferenceFromString(str, sourceFile) {
  106797. return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
  106798. }
  106799. ts.quotePreferenceFromString = quotePreferenceFromString;
  106800. function getQuotePreference(sourceFile, preferences) {
  106801. if (preferences.quotePreference && preferences.quotePreference !== "auto") {
  106802. return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
  106803. }
  106804. else {
  106805. var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral);
  106806. return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
  106807. }
  106808. }
  106809. ts.getQuotePreference = getQuotePreference;
  106810. function getQuoteFromPreference(qp) {
  106811. switch (qp) {
  106812. case 0 /* Single */: return "'";
  106813. case 1 /* Double */: return '"';
  106814. default: return ts.Debug.assertNever(qp);
  106815. }
  106816. }
  106817. ts.getQuoteFromPreference = getQuoteFromPreference;
  106818. function symbolNameNoDefault(symbol) {
  106819. var escaped = symbolEscapedNameNoDefault(symbol);
  106820. return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
  106821. }
  106822. ts.symbolNameNoDefault = symbolNameNoDefault;
  106823. function symbolEscapedNameNoDefault(symbol) {
  106824. if (symbol.escapedName !== "default" /* Default */) {
  106825. return symbol.escapedName;
  106826. }
  106827. return ts.firstDefined(symbol.declarations, function (decl) {
  106828. var name = ts.getNameOfDeclaration(decl);
  106829. return name && name.kind === 75 /* Identifier */ ? name.escapedText : undefined;
  106830. });
  106831. }
  106832. ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
  106833. function isObjectBindingElementWithoutPropertyName(bindingElement) {
  106834. return ts.isBindingElement(bindingElement) &&
  106835. ts.isObjectBindingPattern(bindingElement.parent) &&
  106836. ts.isIdentifier(bindingElement.name) &&
  106837. !bindingElement.propertyName;
  106838. }
  106839. ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName;
  106840. function getPropertySymbolFromBindingElement(checker, bindingElement) {
  106841. var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
  106842. return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
  106843. }
  106844. ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
  106845. /**
  106846. * Find symbol of the given property-name and add the symbol to the given result array
  106847. * @param symbol a symbol to start searching for the given propertyName
  106848. * @param propertyName a name of property to search for
  106849. * @param result an array of symbol of found property symbols
  106850. * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
  106851. * The value of previousIterationSymbol is undefined when the function is first called.
  106852. */
  106853. function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
  106854. var seen = ts.createMap();
  106855. return recur(symbol);
  106856. function recur(symbol) {
  106857. // Use `addToSeen` to ensure we don't infinitely recurse in this situation:
  106858. // interface C extends C {
  106859. // /*findRef*/propName: string;
  106860. // }
  106861. if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol)))
  106862. return;
  106863. return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) {
  106864. var type = checker.getTypeAtLocation(typeReference);
  106865. var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
  106866. // Visit the typeReference as well to see if it directly or indirectly uses that property
  106867. return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
  106868. }); });
  106869. }
  106870. }
  106871. ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes;
  106872. function isMemberSymbolInBaseType(memberSymbol, checker) {
  106873. return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false;
  106874. }
  106875. ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType;
  106876. function getParentNodeInSpan(node, file, span) {
  106877. if (!node)
  106878. return undefined;
  106879. while (node.parent) {
  106880. if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) {
  106881. return node;
  106882. }
  106883. node = node.parent;
  106884. }
  106885. }
  106886. ts.getParentNodeInSpan = getParentNodeInSpan;
  106887. function spanContainsNode(span, node, file) {
  106888. return ts.textSpanContainsPosition(span, node.getStart(file)) &&
  106889. node.getEnd() <= ts.textSpanEnd(span);
  106890. }
  106891. function findModifier(node, kind) {
  106892. return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; });
  106893. }
  106894. ts.findModifier = findModifier;
  106895. function insertImport(changes, sourceFile, importDecl, blankLineBetween) {
  106896. var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax);
  106897. if (lastImportDeclaration) {
  106898. changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl);
  106899. }
  106900. else {
  106901. changes.insertNodeAtTopOfFile(sourceFile, importDecl, blankLineBetween);
  106902. }
  106903. }
  106904. ts.insertImport = insertImport;
  106905. function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) {
  106906. ts.Debug.assert(importClause.isTypeOnly);
  106907. return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken);
  106908. }
  106909. ts.getTypeKeywordOfTypeOnlyImport = getTypeKeywordOfTypeOnlyImport;
  106910. function textSpansEqual(a, b) {
  106911. return !!a && !!b && a.start === b.start && a.length === b.length;
  106912. }
  106913. ts.textSpansEqual = textSpansEqual;
  106914. function documentSpansEqual(a, b) {
  106915. return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan);
  106916. }
  106917. ts.documentSpansEqual = documentSpansEqual;
  106918. /**
  106919. * Iterates through 'array' by index and performs the callback on each element of array until the callback
  106920. * returns a truthy value, then returns that value.
  106921. * If no such value is found, the callback is applied to each element of array and undefined is returned.
  106922. */
  106923. function forEachUnique(array, callback) {
  106924. if (array) {
  106925. for (var i = 0; i < array.length; i++) {
  106926. if (array.indexOf(array[i]) === i) {
  106927. var result = callback(array[i], i);
  106928. if (result) {
  106929. return result;
  106930. }
  106931. }
  106932. }
  106933. }
  106934. return undefined;
  106935. }
  106936. ts.forEachUnique = forEachUnique;
  106937. // #endregion
  106938. // Display-part writer helpers
  106939. // #region
  106940. function isFirstDeclarationOfSymbolParameter(symbol) {
  106941. return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 156 /* Parameter */;
  106942. }
  106943. ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter;
  106944. var displayPartWriter = getDisplayPartWriter();
  106945. function getDisplayPartWriter() {
  106946. var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios
  106947. var displayParts;
  106948. var lineStart;
  106949. var indent;
  106950. var length;
  106951. resetWriter();
  106952. var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); };
  106953. return {
  106954. displayParts: function () {
  106955. var finalText = displayParts.length && displayParts[displayParts.length - 1].text;
  106956. if (length > absoluteMaximumLength && finalText && finalText !== "...") {
  106957. if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) {
  106958. displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space));
  106959. }
  106960. displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation));
  106961. }
  106962. return displayParts;
  106963. },
  106964. writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); },
  106965. writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); },
  106966. writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
  106967. writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
  106968. writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); },
  106969. writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
  106970. writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); },
  106971. writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); },
  106972. writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
  106973. writeSymbol: writeSymbol,
  106974. writeLine: writeLine,
  106975. write: unknownWrite,
  106976. writeComment: unknownWrite,
  106977. getText: function () { return ""; },
  106978. getTextPos: function () { return 0; },
  106979. getColumn: function () { return 0; },
  106980. getLine: function () { return 0; },
  106981. isAtStartOfLine: function () { return false; },
  106982. hasTrailingWhitespace: function () { return false; },
  106983. hasTrailingComment: function () { return false; },
  106984. rawWrite: ts.notImplemented,
  106985. getIndent: function () { return indent; },
  106986. increaseIndent: function () { indent++; },
  106987. decreaseIndent: function () { indent--; },
  106988. clear: resetWriter,
  106989. trackSymbol: ts.noop,
  106990. reportInaccessibleThisError: ts.noop,
  106991. reportInaccessibleUniqueSymbolError: ts.noop,
  106992. reportPrivateInBaseOfClassExpression: ts.noop,
  106993. };
  106994. function writeIndent() {
  106995. if (length > absoluteMaximumLength)
  106996. return;
  106997. if (lineStart) {
  106998. var indentString = ts.getIndentString(indent);
  106999. if (indentString) {
  107000. length += indentString.length;
  107001. displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space));
  107002. }
  107003. lineStart = false;
  107004. }
  107005. }
  107006. function writeKind(text, kind) {
  107007. if (length > absoluteMaximumLength)
  107008. return;
  107009. writeIndent();
  107010. length += text.length;
  107011. displayParts.push(displayPart(text, kind));
  107012. }
  107013. function writeSymbol(text, symbol) {
  107014. if (length > absoluteMaximumLength)
  107015. return;
  107016. writeIndent();
  107017. length += text.length;
  107018. displayParts.push(symbolPart(text, symbol));
  107019. }
  107020. function writeLine() {
  107021. if (length > absoluteMaximumLength)
  107022. return;
  107023. length += 1;
  107024. displayParts.push(lineBreakPart());
  107025. lineStart = true;
  107026. }
  107027. function resetWriter() {
  107028. displayParts = [];
  107029. lineStart = true;
  107030. indent = 0;
  107031. length = 0;
  107032. }
  107033. }
  107034. function symbolPart(text, symbol) {
  107035. return displayPart(text, displayPartKind(symbol));
  107036. function displayPartKind(symbol) {
  107037. var flags = symbol.flags;
  107038. if (flags & 3 /* Variable */) {
  107039. return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName;
  107040. }
  107041. else if (flags & 4 /* Property */) {
  107042. return ts.SymbolDisplayPartKind.propertyName;
  107043. }
  107044. else if (flags & 32768 /* GetAccessor */) {
  107045. return ts.SymbolDisplayPartKind.propertyName;
  107046. }
  107047. else if (flags & 65536 /* SetAccessor */) {
  107048. return ts.SymbolDisplayPartKind.propertyName;
  107049. }
  107050. else if (flags & 8 /* EnumMember */) {
  107051. return ts.SymbolDisplayPartKind.enumMemberName;
  107052. }
  107053. else if (flags & 16 /* Function */) {
  107054. return ts.SymbolDisplayPartKind.functionName;
  107055. }
  107056. else if (flags & 32 /* Class */) {
  107057. return ts.SymbolDisplayPartKind.className;
  107058. }
  107059. else if (flags & 64 /* Interface */) {
  107060. return ts.SymbolDisplayPartKind.interfaceName;
  107061. }
  107062. else if (flags & 384 /* Enum */) {
  107063. return ts.SymbolDisplayPartKind.enumName;
  107064. }
  107065. else if (flags & 1536 /* Module */) {
  107066. return ts.SymbolDisplayPartKind.moduleName;
  107067. }
  107068. else if (flags & 8192 /* Method */) {
  107069. return ts.SymbolDisplayPartKind.methodName;
  107070. }
  107071. else if (flags & 262144 /* TypeParameter */) {
  107072. return ts.SymbolDisplayPartKind.typeParameterName;
  107073. }
  107074. else if (flags & 524288 /* TypeAlias */) {
  107075. return ts.SymbolDisplayPartKind.aliasName;
  107076. }
  107077. else if (flags & 2097152 /* Alias */) {
  107078. return ts.SymbolDisplayPartKind.aliasName;
  107079. }
  107080. return ts.SymbolDisplayPartKind.text;
  107081. }
  107082. }
  107083. ts.symbolPart = symbolPart;
  107084. function displayPart(text, kind) {
  107085. return { text: text, kind: ts.SymbolDisplayPartKind[kind] };
  107086. }
  107087. ts.displayPart = displayPart;
  107088. function spacePart() {
  107089. return displayPart(" ", ts.SymbolDisplayPartKind.space);
  107090. }
  107091. ts.spacePart = spacePart;
  107092. function keywordPart(kind) {
  107093. return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword);
  107094. }
  107095. ts.keywordPart = keywordPart;
  107096. function punctuationPart(kind) {
  107097. return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation);
  107098. }
  107099. ts.punctuationPart = punctuationPart;
  107100. function operatorPart(kind) {
  107101. return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator);
  107102. }
  107103. ts.operatorPart = operatorPart;
  107104. function textOrKeywordPart(text) {
  107105. var kind = ts.stringToToken(text);
  107106. return kind === undefined
  107107. ? textPart(text)
  107108. : keywordPart(kind);
  107109. }
  107110. ts.textOrKeywordPart = textOrKeywordPart;
  107111. function textPart(text) {
  107112. return displayPart(text, ts.SymbolDisplayPartKind.text);
  107113. }
  107114. ts.textPart = textPart;
  107115. var carriageReturnLineFeed = "\r\n";
  107116. /**
  107117. * The default is CRLF.
  107118. */
  107119. function getNewLineOrDefaultFromHost(host, formatSettings) {
  107120. return (formatSettings && formatSettings.newLineCharacter) ||
  107121. (host.getNewLine && host.getNewLine()) ||
  107122. carriageReturnLineFeed;
  107123. }
  107124. ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost;
  107125. function lineBreakPart() {
  107126. return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak);
  107127. }
  107128. ts.lineBreakPart = lineBreakPart;
  107129. function mapToDisplayParts(writeDisplayParts) {
  107130. try {
  107131. writeDisplayParts(displayPartWriter);
  107132. return displayPartWriter.displayParts();
  107133. }
  107134. finally {
  107135. displayPartWriter.clear();
  107136. }
  107137. }
  107138. ts.mapToDisplayParts = mapToDisplayParts;
  107139. function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) {
  107140. if (flags === void 0) { flags = 0 /* None */; }
  107141. return mapToDisplayParts(function (writer) {
  107142. typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer);
  107143. });
  107144. }
  107145. ts.typeToDisplayParts = typeToDisplayParts;
  107146. function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) {
  107147. if (flags === void 0) { flags = 0 /* None */; }
  107148. return mapToDisplayParts(function (writer) {
  107149. typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer);
  107150. });
  107151. }
  107152. ts.symbolToDisplayParts = symbolToDisplayParts;
  107153. function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) {
  107154. if (flags === void 0) { flags = 0 /* None */; }
  107155. flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */;
  107156. return mapToDisplayParts(function (writer) {
  107157. typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer);
  107158. });
  107159. }
  107160. ts.signatureToDisplayParts = signatureToDisplayParts;
  107161. function isImportOrExportSpecifierName(location) {
  107162. return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
  107163. }
  107164. ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
  107165. function scriptKindIs(fileName, host) {
  107166. var scriptKinds = [];
  107167. for (var _i = 2; _i < arguments.length; _i++) {
  107168. scriptKinds[_i - 2] = arguments[_i];
  107169. }
  107170. var scriptKind = getScriptKind(fileName, host);
  107171. return ts.some(scriptKinds, function (k) { return k === scriptKind; });
  107172. }
  107173. ts.scriptKindIs = scriptKindIs;
  107174. function getScriptKind(fileName, host) {
  107175. // First check to see if the script kind was specified by the host. Chances are the host
  107176. // may override the default script kind for the file extension.
  107177. return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
  107178. }
  107179. ts.getScriptKind = getScriptKind;
  107180. function getSymbolTarget(symbol, checker) {
  107181. var next = symbol;
  107182. while (isAliasSymbol(next) || (isTransientSymbol(next) && next.target)) {
  107183. if (isTransientSymbol(next) && next.target) {
  107184. next = next.target;
  107185. }
  107186. else {
  107187. next = ts.skipAlias(next, checker);
  107188. }
  107189. }
  107190. return next;
  107191. }
  107192. ts.getSymbolTarget = getSymbolTarget;
  107193. function isTransientSymbol(symbol) {
  107194. return (symbol.flags & 33554432 /* Transient */) !== 0;
  107195. }
  107196. function isAliasSymbol(symbol) {
  107197. return (symbol.flags & 2097152 /* Alias */) !== 0;
  107198. }
  107199. function getUniqueSymbolId(symbol, checker) {
  107200. return ts.getSymbolId(ts.skipAlias(symbol, checker));
  107201. }
  107202. ts.getUniqueSymbolId = getUniqueSymbolId;
  107203. function getFirstNonSpaceCharacterPosition(text, position) {
  107204. while (ts.isWhiteSpaceLike(text.charCodeAt(position))) {
  107205. position += 1;
  107206. }
  107207. return position;
  107208. }
  107209. ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition;
  107210. function getPrecedingNonSpaceCharacterPosition(text, position) {
  107211. while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) {
  107212. position -= 1;
  107213. }
  107214. return position + 1;
  107215. }
  107216. ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition;
  107217. /**
  107218. * Creates a deep, memberwise clone of a node with no source map location.
  107219. *
  107220. * WARNING: This is an expensive operation and is only intended to be used in refactorings
  107221. * and code fixes (because those are triggered by explicit user actions).
  107222. */
  107223. function getSynthesizedDeepClone(node, includeTrivia) {
  107224. if (includeTrivia === void 0) { includeTrivia = true; }
  107225. var clone = node && getSynthesizedDeepCloneWorker(node);
  107226. if (clone && !includeTrivia)
  107227. suppressLeadingAndTrailingTrivia(clone);
  107228. return clone;
  107229. }
  107230. ts.getSynthesizedDeepClone = getSynthesizedDeepClone;
  107231. function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) {
  107232. if (includeTrivia === void 0) { includeTrivia = true; }
  107233. var clone;
  107234. if (renameMap && checker && ts.isBindingElement(node) && ts.isIdentifier(node.name) && ts.isObjectBindingPattern(node.parent)) {
  107235. var symbol = checker.getSymbolAtLocation(node.name);
  107236. var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
  107237. if (renameInfo && renameInfo.text !== (node.name || node.propertyName).getText()) {
  107238. clone = ts.createBindingElement(node.dotDotDotToken, node.propertyName || node.name, renameInfo, node.initializer);
  107239. }
  107240. }
  107241. else if (renameMap && checker && ts.isIdentifier(node)) {
  107242. var symbol = checker.getSymbolAtLocation(node);
  107243. var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
  107244. if (renameInfo) {
  107245. clone = ts.createIdentifier(renameInfo.text);
  107246. }
  107247. }
  107248. if (!clone) {
  107249. clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback);
  107250. }
  107251. if (clone && !includeTrivia)
  107252. suppressLeadingAndTrailingTrivia(clone);
  107253. if (callback && clone)
  107254. callback(node, clone);
  107255. return clone;
  107256. }
  107257. ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames;
  107258. function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) {
  107259. var visited = (renameMap || checker || callback) ?
  107260. ts.visitEachChild(node, wrapper, ts.nullTransformationContext) :
  107261. ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
  107262. if (visited === node) {
  107263. // This only happens for leaf nodes - internal nodes always see their children change.
  107264. var clone_1 = ts.getSynthesizedClone(node);
  107265. if (ts.isStringLiteral(clone_1)) {
  107266. clone_1.textSourceNode = node;
  107267. }
  107268. else if (ts.isNumericLiteral(clone_1)) {
  107269. clone_1.numericLiteralFlags = node.numericLiteralFlags;
  107270. }
  107271. return ts.setTextRange(clone_1, node);
  107272. }
  107273. // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
  107274. // the new node created by visitEachChild with the extra changes getSynthesizedClone
  107275. // would have made.
  107276. visited.parent = undefined;
  107277. return visited;
  107278. function wrapper(node) {
  107279. return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback);
  107280. }
  107281. }
  107282. function getSynthesizedDeepClones(nodes, includeTrivia) {
  107283. if (includeTrivia === void 0) { includeTrivia = true; }
  107284. return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma);
  107285. }
  107286. ts.getSynthesizedDeepClones = getSynthesizedDeepClones;
  107287. /**
  107288. * Sets EmitFlags to suppress leading and trailing trivia on the node.
  107289. */
  107290. function suppressLeadingAndTrailingTrivia(node) {
  107291. suppressLeadingTrivia(node);
  107292. suppressTrailingTrivia(node);
  107293. }
  107294. ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia;
  107295. /**
  107296. * Sets EmitFlags to suppress leading trivia on the node.
  107297. */
  107298. function suppressLeadingTrivia(node) {
  107299. addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild);
  107300. }
  107301. ts.suppressLeadingTrivia = suppressLeadingTrivia;
  107302. /**
  107303. * Sets EmitFlags to suppress trailing trivia on the node.
  107304. */
  107305. function suppressTrailingTrivia(node) {
  107306. addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild);
  107307. }
  107308. ts.suppressTrailingTrivia = suppressTrailingTrivia;
  107309. function addEmitFlagsRecursively(node, flag, getChild) {
  107310. ts.addEmitFlags(node, flag);
  107311. var child = getChild(node);
  107312. if (child)
  107313. addEmitFlagsRecursively(child, flag, getChild);
  107314. }
  107315. function getFirstChild(node) {
  107316. return node.forEachChild(function (child) { return child; });
  107317. }
  107318. function getUniqueName(baseName, sourceFile) {
  107319. var nameText = baseName;
  107320. for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) {
  107321. nameText = baseName + "_" + i;
  107322. }
  107323. return nameText;
  107324. }
  107325. ts.getUniqueName = getUniqueName;
  107326. /**
  107327. * @return The index of the (only) reference to the extracted symbol. We want the cursor
  107328. * to be on the reference, rather than the declaration, because it's closer to where the
  107329. * user was before extracting it.
  107330. */
  107331. function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
  107332. var delta = 0;
  107333. var lastPos = -1;
  107334. for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
  107335. var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
  107336. ts.Debug.assert(fileName === renameFilename);
  107337. for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
  107338. var change = textChanges_1[_b];
  107339. var span = change.span, newText = change.newText;
  107340. var index = indexInTextChange(newText, name);
  107341. if (index !== -1) {
  107342. lastPos = span.start + delta + index;
  107343. // If the reference comes first, return immediately.
  107344. if (!preferLastLocation) {
  107345. return lastPos;
  107346. }
  107347. }
  107348. delta += newText.length - span.length;
  107349. }
  107350. }
  107351. // If the declaration comes first, return the position of the last occurrence.
  107352. ts.Debug.assert(preferLastLocation);
  107353. ts.Debug.assert(lastPos >= 0);
  107354. return lastPos;
  107355. }
  107356. ts.getRenameLocation = getRenameLocation;
  107357. function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  107358. ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
  107359. }
  107360. ts.copyLeadingComments = copyLeadingComments;
  107361. function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  107362. ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
  107363. }
  107364. ts.copyTrailingComments = copyTrailingComments;
  107365. /**
  107366. * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
  107367. * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
  107368. * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
  107369. * `function foo(\* not leading comment for a *\ a: string) {}`
  107370. * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
  107371. */
  107372. function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  107373. ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
  107374. }
  107375. ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
  107376. function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
  107377. return function (pos, end, kind, htnl) {
  107378. if (kind === 3 /* MultiLineCommentTrivia */) {
  107379. // Remove leading /*
  107380. pos += 2;
  107381. // Remove trailing */
  107382. end -= 2;
  107383. }
  107384. else {
  107385. // Remove leading //
  107386. pos += 2;
  107387. }
  107388. cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
  107389. };
  107390. }
  107391. function indexInTextChange(change, name) {
  107392. if (ts.startsWith(change, name))
  107393. return 0;
  107394. // Add a " " to avoid references inside words
  107395. var idx = change.indexOf(" " + name);
  107396. if (idx === -1)
  107397. idx = change.indexOf("." + name);
  107398. if (idx === -1)
  107399. idx = change.indexOf('"' + name);
  107400. return idx === -1 ? -1 : idx + 1;
  107401. }
  107402. function getContextualTypeFromParent(node, checker) {
  107403. var parent = node.parent;
  107404. switch (parent.kind) {
  107405. case 197 /* NewExpression */:
  107406. return checker.getContextualType(parent);
  107407. case 209 /* BinaryExpression */: {
  107408. var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
  107409. return isEqualityOperatorKind(operatorToken.kind)
  107410. ? checker.getTypeAtLocation(node === right ? left : right)
  107411. : checker.getContextualType(node);
  107412. }
  107413. case 277 /* CaseClause */:
  107414. return parent.expression === node ? getSwitchedType(parent, checker) : undefined;
  107415. default:
  107416. return checker.getContextualType(node);
  107417. }
  107418. }
  107419. ts.getContextualTypeFromParent = getContextualTypeFromParent;
  107420. function quote(text, preferences) {
  107421. if (/^\d+$/.test(text)) {
  107422. return text;
  107423. }
  107424. // Editors can pass in undefined or empty string - we want to infer the preference in those cases.
  107425. var quotePreference = preferences.quotePreference || "auto";
  107426. var quoted = JSON.stringify(text);
  107427. switch (quotePreference) {
  107428. // TODO use getQuotePreference to infer the actual quote style.
  107429. case "auto":
  107430. case "double":
  107431. return quoted;
  107432. case "single":
  107433. return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'";
  107434. default:
  107435. return ts.Debug.assertNever(quotePreference);
  107436. }
  107437. }
  107438. ts.quote = quote;
  107439. function isEqualityOperatorKind(kind) {
  107440. switch (kind) {
  107441. case 36 /* EqualsEqualsEqualsToken */:
  107442. case 34 /* EqualsEqualsToken */:
  107443. case 37 /* ExclamationEqualsEqualsToken */:
  107444. case 35 /* ExclamationEqualsToken */:
  107445. return true;
  107446. default:
  107447. return false;
  107448. }
  107449. }
  107450. ts.isEqualityOperatorKind = isEqualityOperatorKind;
  107451. function isStringLiteralOrTemplate(node) {
  107452. switch (node.kind) {
  107453. case 10 /* StringLiteral */:
  107454. case 14 /* NoSubstitutionTemplateLiteral */:
  107455. case 211 /* TemplateExpression */:
  107456. case 198 /* TaggedTemplateExpression */:
  107457. return true;
  107458. default:
  107459. return false;
  107460. }
  107461. }
  107462. ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate;
  107463. function hasIndexSignature(type) {
  107464. return !!type.getStringIndexType() || !!type.getNumberIndexType();
  107465. }
  107466. ts.hasIndexSignature = hasIndexSignature;
  107467. function getSwitchedType(caseClause, checker) {
  107468. return checker.getTypeAtLocation(caseClause.parent.parent.expression);
  107469. }
  107470. ts.getSwitchedType = getSwitchedType;
  107471. function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
  107472. var checker = program.getTypeChecker();
  107473. var typeIsAccessible = true;
  107474. var notAccessible = function () { typeIsAccessible = false; };
  107475. var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
  107476. trackSymbol: function (symbol, declaration, meaning) {
  107477. typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
  107478. },
  107479. reportInaccessibleThisError: notAccessible,
  107480. reportPrivateInBaseOfClassExpression: notAccessible,
  107481. reportInaccessibleUniqueSymbolError: notAccessible,
  107482. moduleResolverHost: {
  107483. readFile: host.readFile,
  107484. fileExists: host.fileExists,
  107485. directoryExists: host.directoryExists,
  107486. getSourceFiles: program.getSourceFiles,
  107487. getCurrentDirectory: program.getCurrentDirectory,
  107488. getCommonSourceDirectory: program.getCommonSourceDirectory,
  107489. }
  107490. });
  107491. return typeIsAccessible ? res : undefined;
  107492. }
  107493. ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
  107494. function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) {
  107495. return kind === 165 /* CallSignature */
  107496. || kind === 166 /* ConstructSignature */
  107497. || kind === 167 /* IndexSignature */
  107498. || kind === 158 /* PropertySignature */
  107499. || kind === 160 /* MethodSignature */;
  107500. }
  107501. ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI;
  107502. function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) {
  107503. return kind === 244 /* FunctionDeclaration */
  107504. || kind === 162 /* Constructor */
  107505. || kind === 161 /* MethodDeclaration */
  107506. || kind === 163 /* GetAccessor */
  107507. || kind === 164 /* SetAccessor */;
  107508. }
  107509. ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI;
  107510. function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) {
  107511. return kind === 249 /* ModuleDeclaration */;
  107512. }
  107513. ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI;
  107514. function syntaxRequiresTrailingSemicolonOrASI(kind) {
  107515. return kind === 225 /* VariableStatement */
  107516. || kind === 226 /* ExpressionStatement */
  107517. || kind === 228 /* DoStatement */
  107518. || kind === 233 /* ContinueStatement */
  107519. || kind === 234 /* BreakStatement */
  107520. || kind === 235 /* ReturnStatement */
  107521. || kind === 239 /* ThrowStatement */
  107522. || kind === 241 /* DebuggerStatement */
  107523. || kind === 159 /* PropertyDeclaration */
  107524. || kind === 247 /* TypeAliasDeclaration */
  107525. || kind === 254 /* ImportDeclaration */
  107526. || kind === 253 /* ImportEqualsDeclaration */
  107527. || kind === 260 /* ExportDeclaration */
  107528. || kind === 252 /* NamespaceExportDeclaration */
  107529. || kind === 259 /* ExportAssignment */;
  107530. }
  107531. ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI;
  107532. ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI);
  107533. function nodeIsASICandidate(node, sourceFile) {
  107534. var lastToken = node.getLastToken(sourceFile);
  107535. if (lastToken && lastToken.kind === 26 /* SemicolonToken */) {
  107536. return false;
  107537. }
  107538. if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
  107539. if (lastToken && lastToken.kind === 27 /* CommaToken */) {
  107540. return false;
  107541. }
  107542. }
  107543. else if (syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(node.kind)) {
  107544. var lastChild = ts.last(node.getChildren(sourceFile));
  107545. if (lastChild && ts.isModuleBlock(lastChild)) {
  107546. return false;
  107547. }
  107548. }
  107549. else if (syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(node.kind)) {
  107550. var lastChild = ts.last(node.getChildren(sourceFile));
  107551. if (lastChild && ts.isFunctionBlock(lastChild)) {
  107552. return false;
  107553. }
  107554. }
  107555. else if (!syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
  107556. return false;
  107557. }
  107558. // See comment in parser’s `parseDoStatement`
  107559. if (node.kind === 228 /* DoStatement */) {
  107560. return true;
  107561. }
  107562. var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; });
  107563. var nextToken = findNextToken(node, topNode, sourceFile);
  107564. if (!nextToken || nextToken.kind === 19 /* CloseBraceToken */) {
  107565. return true;
  107566. }
  107567. var startLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
  107568. var endLine = sourceFile.getLineAndCharacterOfPosition(nextToken.getStart(sourceFile)).line;
  107569. return startLine !== endLine;
  107570. }
  107571. function positionIsASICandidate(pos, context, sourceFile) {
  107572. var contextAncestor = ts.findAncestor(context, function (ancestor) {
  107573. if (ancestor.end !== pos) {
  107574. return "quit";
  107575. }
  107576. return ts.syntaxMayBeASICandidate(ancestor.kind);
  107577. });
  107578. return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile);
  107579. }
  107580. ts.positionIsASICandidate = positionIsASICandidate;
  107581. function probablyUsesSemicolons(sourceFile) {
  107582. var withSemicolon = 0;
  107583. var withoutSemicolon = 0;
  107584. var nStatementsToObserve = 5;
  107585. ts.forEachChild(sourceFile, function visit(node) {
  107586. if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
  107587. var lastToken = node.getLastToken(sourceFile);
  107588. if (lastToken && lastToken.kind === 26 /* SemicolonToken */) {
  107589. withSemicolon++;
  107590. }
  107591. else {
  107592. withoutSemicolon++;
  107593. }
  107594. }
  107595. if (withSemicolon + withoutSemicolon >= nStatementsToObserve) {
  107596. return true;
  107597. }
  107598. return ts.forEachChild(node, visit);
  107599. });
  107600. // One statement missing a semicolon isn’t sufficient evidence to say the user
  107601. // doesn’t want semicolons, because they may not even be done writing that statement.
  107602. if (withSemicolon === 0 && withoutSemicolon <= 1) {
  107603. return true;
  107604. }
  107605. // If even 2/5 places have a semicolon, the user probably wants semicolons
  107606. return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve;
  107607. }
  107608. ts.probablyUsesSemicolons = probablyUsesSemicolons;
  107609. function tryGetDirectories(host, directoryName) {
  107610. return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || [];
  107611. }
  107612. ts.tryGetDirectories = tryGetDirectories;
  107613. function tryReadDirectory(host, path, extensions, exclude, include) {
  107614. return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray;
  107615. }
  107616. ts.tryReadDirectory = tryReadDirectory;
  107617. function tryFileExists(host, path) {
  107618. return tryIOAndConsumeErrors(host, host.fileExists, path);
  107619. }
  107620. ts.tryFileExists = tryFileExists;
  107621. function tryDirectoryExists(host, path) {
  107622. return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false;
  107623. }
  107624. ts.tryDirectoryExists = tryDirectoryExists;
  107625. function tryAndIgnoreErrors(cb) {
  107626. try {
  107627. return cb();
  107628. }
  107629. catch (_a) {
  107630. return undefined;
  107631. }
  107632. }
  107633. ts.tryAndIgnoreErrors = tryAndIgnoreErrors;
  107634. function tryIOAndConsumeErrors(host, toApply) {
  107635. var args = [];
  107636. for (var _i = 2; _i < arguments.length; _i++) {
  107637. args[_i - 2] = arguments[_i];
  107638. }
  107639. return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); });
  107640. }
  107641. ts.tryIOAndConsumeErrors = tryIOAndConsumeErrors;
  107642. function findPackageJsons(startDirectory, host, stopDirectory) {
  107643. var paths = [];
  107644. ts.forEachAncestorDirectory(startDirectory, function (ancestor) {
  107645. if (ancestor === stopDirectory) {
  107646. return true;
  107647. }
  107648. var currentConfigPath = ts.combinePaths(ancestor, "package.json");
  107649. if (tryFileExists(host, currentConfigPath)) {
  107650. paths.push(currentConfigPath);
  107651. }
  107652. });
  107653. return paths;
  107654. }
  107655. ts.findPackageJsons = findPackageJsons;
  107656. function findPackageJson(directory, host) {
  107657. var packageJson;
  107658. ts.forEachAncestorDirectory(directory, function (ancestor) {
  107659. if (ancestor === "node_modules")
  107660. return true;
  107661. packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json");
  107662. if (packageJson) {
  107663. return true; // break out
  107664. }
  107665. });
  107666. return packageJson;
  107667. }
  107668. ts.findPackageJson = findPackageJson;
  107669. function getPackageJsonsVisibleToFile(fileName, host) {
  107670. if (!host.fileExists) {
  107671. return [];
  107672. }
  107673. var packageJsons = [];
  107674. ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (ancestor) {
  107675. var packageJsonFileName = ts.combinePaths(ancestor, "package.json");
  107676. if (host.fileExists(packageJsonFileName)) {
  107677. var info = createPackageJsonInfo(packageJsonFileName, host);
  107678. if (info) {
  107679. packageJsons.push(info);
  107680. }
  107681. }
  107682. });
  107683. return packageJsons;
  107684. }
  107685. ts.getPackageJsonsVisibleToFile = getPackageJsonsVisibleToFile;
  107686. function createPackageJsonInfo(fileName, host) {
  107687. if (!host.readFile) {
  107688. return undefined;
  107689. }
  107690. var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
  107691. var stringContent = host.readFile(fileName);
  107692. if (!stringContent)
  107693. return undefined;
  107694. var content = tryParseJson(stringContent);
  107695. if (!content)
  107696. return false;
  107697. var info = {};
  107698. for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) {
  107699. var key = dependencyKeys_1[_i];
  107700. var dependencies = content[key];
  107701. if (!dependencies) {
  107702. continue;
  107703. }
  107704. var dependencyMap = ts.createMap();
  107705. for (var packageName in dependencies) {
  107706. dependencyMap.set(packageName, dependencies[packageName]);
  107707. }
  107708. info[key] = dependencyMap;
  107709. }
  107710. var dependencyGroups = [
  107711. [1 /* Dependencies */, info.dependencies],
  107712. [2 /* DevDependencies */, info.devDependencies],
  107713. [8 /* OptionalDependencies */, info.optionalDependencies],
  107714. [4 /* PeerDependencies */, info.peerDependencies],
  107715. ];
  107716. return __assign(__assign({}, info), { fileName: fileName,
  107717. get: get,
  107718. has: function (dependencyName, inGroups) {
  107719. return !!get(dependencyName, inGroups);
  107720. } });
  107721. function get(dependencyName, inGroups) {
  107722. if (inGroups === void 0) { inGroups = 15 /* All */; }
  107723. for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
  107724. var _a = dependencyGroups_1[_i], group_1 = _a[0], deps = _a[1];
  107725. if (deps && (inGroups & group_1)) {
  107726. var dep = deps.get(dependencyName);
  107727. if (dep !== undefined) {
  107728. return dep;
  107729. }
  107730. }
  107731. }
  107732. }
  107733. }
  107734. ts.createPackageJsonInfo = createPackageJsonInfo;
  107735. function tryParseJson(text) {
  107736. try {
  107737. return JSON.parse(text);
  107738. }
  107739. catch (_a) {
  107740. return undefined;
  107741. }
  107742. }
  107743. function consumesNodeCoreModules(sourceFile) {
  107744. return ts.some(sourceFile.imports, function (_a) {
  107745. var text = _a.text;
  107746. return ts.JsTyping.nodeCoreModules.has(text);
  107747. });
  107748. }
  107749. ts.consumesNodeCoreModules = consumesNodeCoreModules;
  107750. function isInsideNodeModules(fileOrDirectory) {
  107751. return ts.contains(ts.getPathComponents(fileOrDirectory), "node_modules");
  107752. }
  107753. ts.isInsideNodeModules = isInsideNodeModules;
  107754. function isDiagnosticWithLocation(diagnostic) {
  107755. return diagnostic.file !== undefined && diagnostic.start !== undefined && diagnostic.length !== undefined;
  107756. }
  107757. ts.isDiagnosticWithLocation = isDiagnosticWithLocation;
  107758. function findDiagnosticForNode(node, sortedFileDiagnostics) {
  107759. var span = createTextSpanFromNode(node);
  107760. var index = ts.binarySearchKey(sortedFileDiagnostics, span, ts.identity, ts.compareTextSpans);
  107761. if (index >= 0) {
  107762. var diagnostic = sortedFileDiagnostics[index];
  107763. ts.Debug.assertEqual(diagnostic.file, node.getSourceFile(), "Diagnostics proided to 'findDiagnosticForNode' must be from a single SourceFile");
  107764. return ts.cast(diagnostic, isDiagnosticWithLocation);
  107765. }
  107766. }
  107767. ts.findDiagnosticForNode = findDiagnosticForNode;
  107768. function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) {
  107769. var _a;
  107770. var index = ts.binarySearchKey(sortedFileDiagnostics, span.start, function (diag) { return diag.start; }, ts.compareValues);
  107771. if (index < 0) {
  107772. index = ~index;
  107773. }
  107774. while (((_a = sortedFileDiagnostics[index - 1]) === null || _a === void 0 ? void 0 : _a.start) === span.start) {
  107775. index--;
  107776. }
  107777. var result = [];
  107778. var end = ts.textSpanEnd(span);
  107779. while (true) {
  107780. var diagnostic = ts.tryCast(sortedFileDiagnostics[index], isDiagnosticWithLocation);
  107781. if (!diagnostic || diagnostic.start > end) {
  107782. break;
  107783. }
  107784. if (ts.textSpanContainsTextSpan(span, diagnostic)) {
  107785. result.push(diagnostic);
  107786. }
  107787. index++;
  107788. }
  107789. return result;
  107790. }
  107791. ts.getDiagnosticsWithinSpan = getDiagnosticsWithinSpan;
  107792. /* @internal */
  107793. function getRefactorContextSpan(_a) {
  107794. var startPosition = _a.startPosition, endPosition = _a.endPosition;
  107795. return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
  107796. }
  107797. ts.getRefactorContextSpan = getRefactorContextSpan;
  107798. function mapOneOrMany(valueOrArray, f, resultSelector) {
  107799. if (resultSelector === void 0) { resultSelector = ts.identity; }
  107800. return valueOrArray ? ts.isArray(valueOrArray) ? resultSelector(ts.map(valueOrArray, f)) : f(valueOrArray, 0) : undefined;
  107801. }
  107802. ts.mapOneOrMany = mapOneOrMany;
  107803. /**
  107804. * If the provided value is an array, the first element of the array is returned; otherwise, the provided value is returned instead.
  107805. */
  107806. function firstOrOnly(valueOrArray) {
  107807. return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray;
  107808. }
  107809. ts.firstOrOnly = firstOrOnly;
  107810. // #endregion
  107811. })(ts || (ts = {}));
  107812. var ts;
  107813. (function (ts) {
  107814. /** The classifier is used for syntactic highlighting in editors via the TSServer */
  107815. function createClassifier() {
  107816. var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false);
  107817. function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
  107818. return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
  107819. }
  107820. // If there is a syntactic classifier ('syntacticClassifierAbsent' is false),
  107821. // we will be more conservative in order to avoid conflicting with the syntactic classifier.
  107822. function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
  107823. var token = 0 /* Unknown */;
  107824. var lastNonTriviaToken = 0 /* Unknown */;
  107825. // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact)
  107826. // classification on template strings. Because of the context free nature of templates,
  107827. // the only precise way to classify a template portion would be by propagating the stack across
  107828. // lines, just as we do with the end-of-line state. However, this is a burden for implementers,
  107829. // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead
  107830. // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state.
  107831. // Situations in which this fails are
  107832. // 1) When template strings are nested across different lines:
  107833. // `hello ${ `world
  107834. // ` }`
  107835. //
  107836. // Where on the second line, you will get the closing of a template,
  107837. // a closing curly, and a new template.
  107838. //
  107839. // 2) When substitution expressions have curly braces and the curly brace falls on the next line:
  107840. // `hello ${ () => {
  107841. // return "world" } } `
  107842. //
  107843. // Where on the second line, you will get the 'return' keyword,
  107844. // a string literal, and a template end consisting of '} } `'.
  107845. var templateStack = [];
  107846. var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate;
  107847. text = prefix + text;
  107848. var offset = prefix.length;
  107849. if (pushTemplate) {
  107850. templateStack.push(15 /* TemplateHead */);
  107851. }
  107852. scanner.setText(text);
  107853. var endOfLineState = 0 /* None */;
  107854. var spans = [];
  107855. // We can run into an unfortunate interaction between the lexical and syntactic classifier
  107856. // when the user is typing something generic. Consider the case where the user types:
  107857. //
  107858. // Foo<number
  107859. //
  107860. // From the lexical classifier's perspective, 'number' is a keyword, and so the word will
  107861. // be classified as such. However, from the syntactic classifier's tree-based perspective
  107862. // this is simply an expression with the identifier 'number' on the RHS of the less than
  107863. // token. So the classification will go back to being an identifier. The moment the user
  107864. // types again, number will become a keyword, then an identifier, etc. etc.
  107865. //
  107866. // To try to avoid this problem, we avoid classifying contextual keywords as keywords
  107867. // when the user is potentially typing something generic. We just can't do a good enough
  107868. // job at the lexical level, and so well leave it up to the syntactic classifier to make
  107869. // the determination.
  107870. //
  107871. // In order to determine if the user is potentially typing something generic, we use a
  107872. // weak heuristic where we track < and > tokens. It's a weak heuristic, but should
  107873. // work well enough in practice.
  107874. var angleBracketStack = 0;
  107875. do {
  107876. token = scanner.scan();
  107877. if (!ts.isTrivia(token)) {
  107878. handleToken();
  107879. lastNonTriviaToken = token;
  107880. }
  107881. var end = scanner.getTextPos();
  107882. pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans);
  107883. if (end >= text.length) {
  107884. var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack));
  107885. if (end_1 !== undefined) {
  107886. endOfLineState = end_1;
  107887. }
  107888. }
  107889. } while (token !== 1 /* EndOfFileToken */);
  107890. function handleToken() {
  107891. switch (token) {
  107892. case 43 /* SlashToken */:
  107893. case 67 /* SlashEqualsToken */:
  107894. if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
  107895. token = 13 /* RegularExpressionLiteral */;
  107896. }
  107897. break;
  107898. case 29 /* LessThanToken */:
  107899. if (lastNonTriviaToken === 75 /* Identifier */) {
  107900. // Could be the start of something generic. Keep track of that by bumping
  107901. // up the current count of generic contexts we may be in.
  107902. angleBracketStack++;
  107903. }
  107904. break;
  107905. case 31 /* GreaterThanToken */:
  107906. if (angleBracketStack > 0) {
  107907. // If we think we're currently in something generic, then mark that that
  107908. // generic entity is complete.
  107909. angleBracketStack--;
  107910. }
  107911. break;
  107912. case 125 /* AnyKeyword */:
  107913. case 143 /* StringKeyword */:
  107914. case 140 /* NumberKeyword */:
  107915. case 128 /* BooleanKeyword */:
  107916. case 144 /* SymbolKeyword */:
  107917. if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
  107918. // If it looks like we're could be in something generic, don't classify this
  107919. // as a keyword. We may just get overwritten by the syntactic classifier,
  107920. // causing a noisy experience for the user.
  107921. token = 75 /* Identifier */;
  107922. }
  107923. break;
  107924. case 15 /* TemplateHead */:
  107925. templateStack.push(token);
  107926. break;
  107927. case 18 /* OpenBraceToken */:
  107928. // If we don't have anything on the template stack,
  107929. // then we aren't trying to keep track of a previously scanned template head.
  107930. if (templateStack.length > 0) {
  107931. templateStack.push(token);
  107932. }
  107933. break;
  107934. case 19 /* CloseBraceToken */:
  107935. // If we don't have anything on the template stack,
  107936. // then we aren't trying to keep track of a previously scanned template head.
  107937. if (templateStack.length > 0) {
  107938. var lastTemplateStackToken = ts.lastOrUndefined(templateStack);
  107939. if (lastTemplateStackToken === 15 /* TemplateHead */) {
  107940. token = scanner.reScanTemplateToken();
  107941. // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us.
  107942. if (token === 17 /* TemplateTail */) {
  107943. templateStack.pop();
  107944. }
  107945. else {
  107946. ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle.");
  107947. }
  107948. }
  107949. else {
  107950. ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace");
  107951. templateStack.pop();
  107952. }
  107953. }
  107954. break;
  107955. default:
  107956. if (!ts.isKeyword(token)) {
  107957. break;
  107958. }
  107959. if (lastNonTriviaToken === 24 /* DotToken */) {
  107960. token = 75 /* Identifier */;
  107961. }
  107962. else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
  107963. // We have two keywords in a row. Only treat the second as a keyword if
  107964. // it's a sequence that could legally occur in the language. Otherwise
  107965. // treat it as an identifier. This way, if someone writes "private var"
  107966. // we recognize that 'var' is actually an identifier here.
  107967. token = 75 /* Identifier */;
  107968. }
  107969. }
  107970. }
  107971. return { endOfLineState: endOfLineState, spans: spans };
  107972. }
  107973. return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications };
  107974. }
  107975. ts.createClassifier = createClassifier;
  107976. /// We do not have a full parser support to know when we should parse a regex or not
  107977. /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
  107978. /// we have a series of divide operator. this list allows us to be more accurate by ruling out
  107979. /// locations where a regexp cannot exist.
  107980. var noRegexTable = ts.arrayToNumericMap([
  107981. 75 /* Identifier */,
  107982. 10 /* StringLiteral */,
  107983. 8 /* NumericLiteral */,
  107984. 9 /* BigIntLiteral */,
  107985. 13 /* RegularExpressionLiteral */,
  107986. 104 /* ThisKeyword */,
  107987. 45 /* PlusPlusToken */,
  107988. 46 /* MinusMinusToken */,
  107989. 21 /* CloseParenToken */,
  107990. 23 /* CloseBracketToken */,
  107991. 19 /* CloseBraceToken */,
  107992. 106 /* TrueKeyword */,
  107993. 91 /* FalseKeyword */,
  107994. ], function (token) { return token; }, function () { return true; });
  107995. function getNewEndOfLineState(scanner, token, lastOnTemplateStack) {
  107996. switch (token) {
  107997. case 10 /* StringLiteral */: {
  107998. // Check to see if we finished up on a multiline string literal.
  107999. if (!scanner.isUnterminated())
  108000. return undefined;
  108001. var tokenText = scanner.getTokenText();
  108002. var lastCharIndex = tokenText.length - 1;
  108003. var numBackslashes = 0;
  108004. while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) {
  108005. numBackslashes++;
  108006. }
  108007. // If we have an odd number of backslashes, then the multiline string is unclosed
  108008. if ((numBackslashes & 1) === 0)
  108009. return undefined;
  108010. return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */;
  108011. }
  108012. case 3 /* MultiLineCommentTrivia */:
  108013. // Check to see if the multiline comment was unclosed.
  108014. return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined;
  108015. default:
  108016. if (ts.isTemplateLiteralKind(token)) {
  108017. if (!scanner.isUnterminated()) {
  108018. return undefined;
  108019. }
  108020. switch (token) {
  108021. case 17 /* TemplateTail */:
  108022. return 5 /* InTemplateMiddleOrTail */;
  108023. case 14 /* NoSubstitutionTemplateLiteral */:
  108024. return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
  108025. default:
  108026. return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
  108027. }
  108028. }
  108029. return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
  108030. }
  108031. }
  108032. function pushEncodedClassification(start, end, offset, classification, result) {
  108033. if (classification === 8 /* whiteSpace */) {
  108034. // Don't bother with whitespace classifications. They're not needed.
  108035. return;
  108036. }
  108037. if (start === 0 && offset > 0) {
  108038. // We're classifying the first token, and this was a case where we prepended text.
  108039. // We should consider the start of this token to be at the start of the original text.
  108040. start += offset;
  108041. }
  108042. var length = end - start;
  108043. if (length > 0) {
  108044. // All our tokens are in relation to the augmented text. Move them back to be
  108045. // relative to the original text.
  108046. result.push(start - offset, length, classification);
  108047. }
  108048. }
  108049. function convertClassificationsToResult(classifications, text) {
  108050. var entries = [];
  108051. var dense = classifications.spans;
  108052. var lastEnd = 0;
  108053. for (var i = 0; i < dense.length; i += 3) {
  108054. var start = dense[i];
  108055. var length_1 = dense[i + 1];
  108056. var type = dense[i + 2];
  108057. // Make a whitespace entry between the last item and this one.
  108058. if (lastEnd >= 0) {
  108059. var whitespaceLength_1 = start - lastEnd;
  108060. if (whitespaceLength_1 > 0) {
  108061. entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
  108062. }
  108063. }
  108064. entries.push({ length: length_1, classification: convertClassification(type) });
  108065. lastEnd = start + length_1;
  108066. }
  108067. var whitespaceLength = text.length - lastEnd;
  108068. if (whitespaceLength > 0) {
  108069. entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace });
  108070. }
  108071. return { entries: entries, finalLexState: classifications.endOfLineState };
  108072. }
  108073. function convertClassification(type) {
  108074. switch (type) {
  108075. case 1 /* comment */: return ts.TokenClass.Comment;
  108076. case 3 /* keyword */: return ts.TokenClass.Keyword;
  108077. case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral;
  108078. case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral;
  108079. case 5 /* operator */: return ts.TokenClass.Operator;
  108080. case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral;
  108081. case 8 /* whiteSpace */: return ts.TokenClass.Whitespace;
  108082. case 10 /* punctuation */: return ts.TokenClass.Punctuation;
  108083. case 2 /* identifier */:
  108084. case 11 /* className */:
  108085. case 12 /* enumName */:
  108086. case 13 /* interfaceName */:
  108087. case 14 /* moduleName */:
  108088. case 15 /* typeParameterName */:
  108089. case 16 /* typeAliasName */:
  108090. case 9 /* text */:
  108091. case 17 /* parameterName */:
  108092. return ts.TokenClass.Identifier;
  108093. default:
  108094. return undefined; // TODO: GH#18217 Debug.assertNever(type);
  108095. }
  108096. }
  108097. /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
  108098. function canFollow(keyword1, keyword2) {
  108099. if (!ts.isAccessibilityModifier(keyword1)) {
  108100. // Assume any other keyword combination is legal.
  108101. // This can be refined in the future if there are more cases we want the classifier to be better at.
  108102. return true;
  108103. }
  108104. switch (keyword2) {
  108105. case 131 /* GetKeyword */:
  108106. case 142 /* SetKeyword */:
  108107. case 129 /* ConstructorKeyword */:
  108108. case 120 /* StaticKeyword */:
  108109. return true; // Allow things like "public get", "public constructor" and "public static".
  108110. default:
  108111. return false; // Any other keyword following "public" is actually an identifier, not a real keyword.
  108112. }
  108113. }
  108114. function getPrefixFromLexState(lexState) {
  108115. // If we're in a string literal, then prepend: "\
  108116. // (and a newline). That way when we lex we'll think we're still in a string literal.
  108117. //
  108118. // If we're in a multiline comment, then prepend: /*
  108119. // (and a newline). That way when we lex we'll think we're still in a multiline comment.
  108120. switch (lexState) {
  108121. case 3 /* InDoubleQuoteStringLiteral */:
  108122. return { prefix: "\"\\\n" };
  108123. case 2 /* InSingleQuoteStringLiteral */:
  108124. return { prefix: "'\\\n" };
  108125. case 1 /* InMultiLineCommentTrivia */:
  108126. return { prefix: "/*\n" };
  108127. case 4 /* InTemplateHeadOrNoSubstitutionTemplate */:
  108128. return { prefix: "`\n" };
  108129. case 5 /* InTemplateMiddleOrTail */:
  108130. return { prefix: "}\n", pushTemplate: true };
  108131. case 6 /* InTemplateSubstitutionPosition */:
  108132. return { prefix: "", pushTemplate: true };
  108133. case 0 /* None */:
  108134. return { prefix: "" };
  108135. default:
  108136. return ts.Debug.assertNever(lexState);
  108137. }
  108138. }
  108139. function isBinaryExpressionOperatorToken(token) {
  108140. switch (token) {
  108141. case 41 /* AsteriskToken */:
  108142. case 43 /* SlashToken */:
  108143. case 44 /* PercentToken */:
  108144. case 39 /* PlusToken */:
  108145. case 40 /* MinusToken */:
  108146. case 47 /* LessThanLessThanToken */:
  108147. case 48 /* GreaterThanGreaterThanToken */:
  108148. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  108149. case 29 /* LessThanToken */:
  108150. case 31 /* GreaterThanToken */:
  108151. case 32 /* LessThanEqualsToken */:
  108152. case 33 /* GreaterThanEqualsToken */:
  108153. case 98 /* InstanceOfKeyword */:
  108154. case 97 /* InKeyword */:
  108155. case 123 /* AsKeyword */:
  108156. case 34 /* EqualsEqualsToken */:
  108157. case 35 /* ExclamationEqualsToken */:
  108158. case 36 /* EqualsEqualsEqualsToken */:
  108159. case 37 /* ExclamationEqualsEqualsToken */:
  108160. case 50 /* AmpersandToken */:
  108161. case 52 /* CaretToken */:
  108162. case 51 /* BarToken */:
  108163. case 55 /* AmpersandAmpersandToken */:
  108164. case 56 /* BarBarToken */:
  108165. case 73 /* BarEqualsToken */:
  108166. case 72 /* AmpersandEqualsToken */:
  108167. case 74 /* CaretEqualsToken */:
  108168. case 69 /* LessThanLessThanEqualsToken */:
  108169. case 70 /* GreaterThanGreaterThanEqualsToken */:
  108170. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  108171. case 63 /* PlusEqualsToken */:
  108172. case 64 /* MinusEqualsToken */:
  108173. case 65 /* AsteriskEqualsToken */:
  108174. case 67 /* SlashEqualsToken */:
  108175. case 68 /* PercentEqualsToken */:
  108176. case 62 /* EqualsToken */:
  108177. case 27 /* CommaToken */:
  108178. case 60 /* QuestionQuestionToken */:
  108179. return true;
  108180. default:
  108181. return false;
  108182. }
  108183. }
  108184. function isPrefixUnaryExpressionOperatorToken(token) {
  108185. switch (token) {
  108186. case 39 /* PlusToken */:
  108187. case 40 /* MinusToken */:
  108188. case 54 /* TildeToken */:
  108189. case 53 /* ExclamationToken */:
  108190. case 45 /* PlusPlusToken */:
  108191. case 46 /* MinusMinusToken */:
  108192. return true;
  108193. default:
  108194. return false;
  108195. }
  108196. }
  108197. function classFromKind(token) {
  108198. if (ts.isKeyword(token)) {
  108199. return 3 /* keyword */;
  108200. }
  108201. else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
  108202. return 5 /* operator */;
  108203. }
  108204. else if (token >= 18 /* FirstPunctuation */ && token <= 74 /* LastPunctuation */) {
  108205. return 10 /* punctuation */;
  108206. }
  108207. switch (token) {
  108208. case 8 /* NumericLiteral */:
  108209. return 4 /* numericLiteral */;
  108210. case 9 /* BigIntLiteral */:
  108211. return 25 /* bigintLiteral */;
  108212. case 10 /* StringLiteral */:
  108213. return 6 /* stringLiteral */;
  108214. case 13 /* RegularExpressionLiteral */:
  108215. return 7 /* regularExpressionLiteral */;
  108216. case 7 /* ConflictMarkerTrivia */:
  108217. case 3 /* MultiLineCommentTrivia */:
  108218. case 2 /* SingleLineCommentTrivia */:
  108219. return 1 /* comment */;
  108220. case 5 /* WhitespaceTrivia */:
  108221. case 4 /* NewLineTrivia */:
  108222. return 8 /* whiteSpace */;
  108223. case 75 /* Identifier */:
  108224. default:
  108225. if (ts.isTemplateLiteralKind(token)) {
  108226. return 6 /* stringLiteral */;
  108227. }
  108228. return 2 /* identifier */;
  108229. }
  108230. }
  108231. /* @internal */
  108232. function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
  108233. return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
  108234. }
  108235. ts.getSemanticClassifications = getSemanticClassifications;
  108236. function checkForClassificationCancellation(cancellationToken, kind) {
  108237. // We don't want to actually call back into our host on every node to find out if we've
  108238. // been canceled. That would be an enormous amount of chattyness, along with the all
  108239. // the overhead of marshalling the data to/from the host. So instead we pick a few
  108240. // reasonable node kinds to bother checking on. These node kinds represent high level
  108241. // constructs that we would expect to see commonly, but just at a far less frequent
  108242. // interval.
  108243. //
  108244. // For example, in checker.ts (around 750k) we only have around 600 of these constructs.
  108245. // That means we're calling back into the host around every 1.2k of the file we process.
  108246. // Lib.d.ts has similar numbers.
  108247. switch (kind) {
  108248. case 249 /* ModuleDeclaration */:
  108249. case 245 /* ClassDeclaration */:
  108250. case 246 /* InterfaceDeclaration */:
  108251. case 244 /* FunctionDeclaration */:
  108252. cancellationToken.throwIfCancellationRequested();
  108253. }
  108254. }
  108255. /* @internal */
  108256. function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
  108257. var spans = [];
  108258. sourceFile.forEachChild(function cb(node) {
  108259. // Only walk into nodes that intersect the requested span.
  108260. if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
  108261. return;
  108262. }
  108263. checkForClassificationCancellation(cancellationToken, node.kind);
  108264. // Only bother calling into the typechecker if this is an identifier that
  108265. // could possibly resolve to a type name. This makes classification run
  108266. // in a third of the time it would normally take.
  108267. if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
  108268. var symbol = typeChecker.getSymbolAtLocation(node);
  108269. var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker);
  108270. if (type) {
  108271. pushClassification(node.getStart(sourceFile), node.getEnd(), type);
  108272. }
  108273. }
  108274. node.forEachChild(cb);
  108275. });
  108276. return { spans: spans, endOfLineState: 0 /* None */ };
  108277. function pushClassification(start, end, type) {
  108278. var length = end - start;
  108279. ts.Debug.assert(length > 0, "Classification had non-positive length of " + length);
  108280. spans.push(start);
  108281. spans.push(length);
  108282. spans.push(type);
  108283. }
  108284. }
  108285. ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications;
  108286. function classifySymbol(symbol, meaningAtPosition, checker) {
  108287. var flags = symbol.getFlags();
  108288. if ((flags & 2885600 /* Classifiable */) === 0 /* None */) {
  108289. return undefined;
  108290. }
  108291. else if (flags & 32 /* Class */) {
  108292. return 11 /* className */;
  108293. }
  108294. else if (flags & 384 /* Enum */) {
  108295. return 12 /* enumName */;
  108296. }
  108297. else if (flags & 524288 /* TypeAlias */) {
  108298. return 16 /* typeAliasName */;
  108299. }
  108300. else if (flags & 1536 /* Module */) {
  108301. // Only classify a module as such if
  108302. // - It appears in a namespace context.
  108303. // - There exists a module declaration which actually impacts the value side.
  108304. return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined;
  108305. }
  108306. else if (flags & 2097152 /* Alias */) {
  108307. return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
  108308. }
  108309. else if (meaningAtPosition & 2 /* Type */) {
  108310. return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined;
  108311. }
  108312. else {
  108313. return undefined;
  108314. }
  108315. }
  108316. /** Returns true if there exists a module that introduces entities on the value side. */
  108317. function hasValueSideModule(symbol) {
  108318. return ts.some(symbol.declarations, function (declaration) {
  108319. return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;
  108320. });
  108321. }
  108322. function getClassificationTypeName(type) {
  108323. switch (type) {
  108324. case 1 /* comment */: return "comment" /* comment */;
  108325. case 2 /* identifier */: return "identifier" /* identifier */;
  108326. case 3 /* keyword */: return "keyword" /* keyword */;
  108327. case 4 /* numericLiteral */: return "number" /* numericLiteral */;
  108328. case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */;
  108329. case 5 /* operator */: return "operator" /* operator */;
  108330. case 6 /* stringLiteral */: return "string" /* stringLiteral */;
  108331. case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */;
  108332. case 9 /* text */: return "text" /* text */;
  108333. case 10 /* punctuation */: return "punctuation" /* punctuation */;
  108334. case 11 /* className */: return "class name" /* className */;
  108335. case 12 /* enumName */: return "enum name" /* enumName */;
  108336. case 13 /* interfaceName */: return "interface name" /* interfaceName */;
  108337. case 14 /* moduleName */: return "module name" /* moduleName */;
  108338. case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */;
  108339. case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */;
  108340. case 17 /* parameterName */: return "parameter name" /* parameterName */;
  108341. case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */;
  108342. case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */;
  108343. case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */;
  108344. case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */;
  108345. case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */;
  108346. case 23 /* jsxText */: return "jsx text" /* jsxText */;
  108347. case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */;
  108348. default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type);
  108349. }
  108350. }
  108351. function convertClassificationsToSpans(classifications) {
  108352. ts.Debug.assert(classifications.spans.length % 3 === 0);
  108353. var dense = classifications.spans;
  108354. var result = [];
  108355. for (var i = 0; i < dense.length; i += 3) {
  108356. result.push({
  108357. textSpan: ts.createTextSpan(dense[i], dense[i + 1]),
  108358. classificationType: getClassificationTypeName(dense[i + 2])
  108359. });
  108360. }
  108361. return result;
  108362. }
  108363. /* @internal */
  108364. function getSyntacticClassifications(cancellationToken, sourceFile, span) {
  108365. return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
  108366. }
  108367. ts.getSyntacticClassifications = getSyntacticClassifications;
  108368. /* @internal */
  108369. function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
  108370. var spanStart = span.start;
  108371. var spanLength = span.length;
  108372. // Make a scanner we can get trivia from.
  108373. var triviaScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
  108374. var mergeConflictScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
  108375. var result = [];
  108376. processElement(sourceFile);
  108377. return { spans: result, endOfLineState: 0 /* None */ };
  108378. function pushClassification(start, length, type) {
  108379. result.push(start);
  108380. result.push(length);
  108381. result.push(type);
  108382. }
  108383. function classifyLeadingTriviaAndGetTokenStart(token) {
  108384. triviaScanner.setTextPos(token.pos);
  108385. while (true) {
  108386. var start = triviaScanner.getTextPos();
  108387. // only bother scanning if we have something that could be trivia.
  108388. if (!ts.couldStartTrivia(sourceFile.text, start)) {
  108389. return start;
  108390. }
  108391. var kind = triviaScanner.scan();
  108392. var end = triviaScanner.getTextPos();
  108393. var width = end - start;
  108394. // The moment we get something that isn't trivia, then stop processing.
  108395. if (!ts.isTrivia(kind)) {
  108396. return start;
  108397. }
  108398. switch (kind) {
  108399. case 4 /* NewLineTrivia */:
  108400. case 5 /* WhitespaceTrivia */:
  108401. // Don't bother with newlines/whitespace.
  108402. continue;
  108403. case 2 /* SingleLineCommentTrivia */:
  108404. case 3 /* MultiLineCommentTrivia */:
  108405. // Only bother with the trivia if it at least intersects the span of interest.
  108406. classifyComment(token, kind, start, width);
  108407. // Classifying a comment might cause us to reuse the trivia scanner
  108408. // (because of jsdoc comments). So after we classify the comment make
  108409. // sure we set the scanner position back to where it needs to be.
  108410. triviaScanner.setTextPos(end);
  108411. continue;
  108412. case 7 /* ConflictMarkerTrivia */:
  108413. var text = sourceFile.text;
  108414. var ch = text.charCodeAt(start);
  108415. // for the <<<<<<< and >>>>>>> markers, we just add them in as comments
  108416. // in the classification stream.
  108417. if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
  108418. pushClassification(start, width, 1 /* comment */);
  108419. continue;
  108420. }
  108421. // for the ||||||| and ======== markers, add a comment for the first line,
  108422. // and then lex all subsequent lines up until the end of the conflict marker.
  108423. ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
  108424. classifyDisabledMergeCode(text, start, end);
  108425. break;
  108426. case 6 /* ShebangTrivia */:
  108427. // TODO: Maybe we should classify these.
  108428. break;
  108429. default:
  108430. ts.Debug.assertNever(kind);
  108431. }
  108432. }
  108433. }
  108434. function classifyComment(token, kind, start, width) {
  108435. if (kind === 3 /* MultiLineCommentTrivia */) {
  108436. // See if this is a doc comment. If so, we'll classify certain portions of it
  108437. // specially.
  108438. var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width);
  108439. if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
  108440. // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]`
  108441. docCommentAndDiagnostics.jsDoc.parent = token;
  108442. classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
  108443. return;
  108444. }
  108445. }
  108446. else if (kind === 2 /* SingleLineCommentTrivia */) {
  108447. if (tryClassifyTripleSlashComment(start, width)) {
  108448. return;
  108449. }
  108450. }
  108451. // Simple comment. Just add as is.
  108452. pushCommentRange(start, width);
  108453. }
  108454. function pushCommentRange(start, width) {
  108455. pushClassification(start, width, 1 /* comment */);
  108456. }
  108457. function classifyJSDocComment(docComment) {
  108458. var pos = docComment.pos;
  108459. if (docComment.tags) {
  108460. for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) {
  108461. var tag = _a[_i];
  108462. // As we walk through each tag, classify the portion of text from the end of
  108463. // the last tag (or the start of the entire doc comment) as 'comment'.
  108464. if (tag.pos !== pos) {
  108465. pushCommentRange(pos, tag.pos - pos);
  108466. }
  108467. pushClassification(tag.pos, 1, 10 /* punctuation */); // "@"
  108468. pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
  108469. pos = tag.tagName.end;
  108470. switch (tag.kind) {
  108471. case 316 /* JSDocParameterTag */:
  108472. processJSDocParameterTag(tag);
  108473. break;
  108474. case 320 /* JSDocTemplateTag */:
  108475. processJSDocTemplateTag(tag);
  108476. pos = tag.end;
  108477. break;
  108478. case 319 /* JSDocTypeTag */:
  108479. processElement(tag.typeExpression);
  108480. pos = tag.end;
  108481. break;
  108482. case 317 /* JSDocReturnTag */:
  108483. processElement(tag.typeExpression);
  108484. pos = tag.end;
  108485. break;
  108486. }
  108487. }
  108488. }
  108489. if (pos !== docComment.end) {
  108490. pushCommentRange(pos, docComment.end - pos);
  108491. }
  108492. return;
  108493. function processJSDocParameterTag(tag) {
  108494. if (tag.isNameFirst) {
  108495. pushCommentRange(pos, tag.name.pos - pos);
  108496. pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
  108497. pos = tag.name.end;
  108498. }
  108499. if (tag.typeExpression) {
  108500. pushCommentRange(pos, tag.typeExpression.pos - pos);
  108501. processElement(tag.typeExpression);
  108502. pos = tag.typeExpression.end;
  108503. }
  108504. if (!tag.isNameFirst) {
  108505. pushCommentRange(pos, tag.name.pos - pos);
  108506. pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
  108507. pos = tag.name.end;
  108508. }
  108509. }
  108510. }
  108511. function tryClassifyTripleSlashComment(start, width) {
  108512. var tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im;
  108513. var attributeRegex = /(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img;
  108514. var text = sourceFile.text.substr(start, width);
  108515. var match = tripleSlashXMLCommentRegEx.exec(text);
  108516. if (!match) {
  108517. return false;
  108518. }
  108519. // Limiting classification to exactly the elements and attributes
  108520. // defined in `ts.commentPragmas` would be excessive, but we can avoid
  108521. // some obvious false positives (e.g. in XML-like doc comments) by
  108522. // checking the element name.
  108523. // eslint-disable-next-line no-in-operator
  108524. if (!match[3] || !(match[3] in ts.commentPragmas)) {
  108525. return false;
  108526. }
  108527. var pos = start;
  108528. pushCommentRange(pos, match[1].length); // ///
  108529. pos += match[1].length;
  108530. pushClassification(pos, match[2].length, 10 /* punctuation */); // <
  108531. pos += match[2].length;
  108532. pushClassification(pos, match[3].length, 21 /* jsxSelfClosingTagName */); // element name
  108533. pos += match[3].length;
  108534. var attrText = match[4];
  108535. var attrPos = pos;
  108536. while (true) {
  108537. var attrMatch = attributeRegex.exec(attrText);
  108538. if (!attrMatch) {
  108539. break;
  108540. }
  108541. var newAttrPos = pos + attrMatch.index;
  108542. if (newAttrPos > attrPos) {
  108543. pushCommentRange(attrPos, newAttrPos - attrPos);
  108544. attrPos = newAttrPos;
  108545. }
  108546. pushClassification(attrPos, attrMatch[1].length, 22 /* jsxAttribute */); // attribute name
  108547. attrPos += attrMatch[1].length;
  108548. if (attrMatch[2].length) {
  108549. pushCommentRange(attrPos, attrMatch[2].length); // whitespace
  108550. attrPos += attrMatch[2].length;
  108551. }
  108552. pushClassification(attrPos, attrMatch[3].length, 5 /* operator */); // =
  108553. attrPos += attrMatch[3].length;
  108554. if (attrMatch[4].length) {
  108555. pushCommentRange(attrPos, attrMatch[4].length); // whitespace
  108556. attrPos += attrMatch[4].length;
  108557. }
  108558. pushClassification(attrPos, attrMatch[5].length, 24 /* jsxAttributeStringLiteralValue */); // attribute value
  108559. attrPos += attrMatch[5].length;
  108560. }
  108561. pos += match[4].length;
  108562. if (pos > attrPos) {
  108563. pushCommentRange(attrPos, pos - attrPos);
  108564. }
  108565. if (match[5]) {
  108566. pushClassification(pos, match[5].length, 10 /* punctuation */); // />
  108567. pos += match[5].length;
  108568. }
  108569. var end = start + width;
  108570. if (pos < end) {
  108571. pushCommentRange(pos, end - pos);
  108572. }
  108573. return true;
  108574. }
  108575. function processJSDocTemplateTag(tag) {
  108576. for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) {
  108577. var child = _a[_i];
  108578. processElement(child);
  108579. }
  108580. }
  108581. function classifyDisabledMergeCode(text, start, end) {
  108582. // Classify the line that the ||||||| or ======= marker is on as a comment.
  108583. // Then just lex all further tokens and add them to the result.
  108584. var i;
  108585. for (i = start; i < end; i++) {
  108586. if (ts.isLineBreak(text.charCodeAt(i))) {
  108587. break;
  108588. }
  108589. }
  108590. pushClassification(start, i - start, 1 /* comment */);
  108591. mergeConflictScanner.setTextPos(i);
  108592. while (mergeConflictScanner.getTextPos() < end) {
  108593. classifyDisabledCodeToken();
  108594. }
  108595. }
  108596. function classifyDisabledCodeToken() {
  108597. var start = mergeConflictScanner.getTextPos();
  108598. var tokenKind = mergeConflictScanner.scan();
  108599. var end = mergeConflictScanner.getTextPos();
  108600. var type = classifyTokenType(tokenKind);
  108601. if (type) {
  108602. pushClassification(start, end - start, type);
  108603. }
  108604. }
  108605. /**
  108606. * Returns true if node should be treated as classified and no further processing is required.
  108607. * False will mean that node is not classified and traverse routine should recurse into node contents.
  108608. */
  108609. function tryClassifyNode(node) {
  108610. if (ts.isJSDoc(node)) {
  108611. return true;
  108612. }
  108613. if (ts.nodeIsMissing(node)) {
  108614. return true;
  108615. }
  108616. var classifiedElementName = tryClassifyJsxElementName(node);
  108617. if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) {
  108618. return false;
  108619. }
  108620. var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
  108621. var tokenWidth = node.end - tokenStart;
  108622. ts.Debug.assert(tokenWidth >= 0);
  108623. if (tokenWidth > 0) {
  108624. var type = classifiedElementName || classifyTokenType(node.kind, node);
  108625. if (type) {
  108626. pushClassification(tokenStart, tokenWidth, type);
  108627. }
  108628. }
  108629. return true;
  108630. }
  108631. function tryClassifyJsxElementName(token) {
  108632. switch (token.parent && token.parent.kind) {
  108633. case 268 /* JsxOpeningElement */:
  108634. if (token.parent.tagName === token) {
  108635. return 19 /* jsxOpenTagName */;
  108636. }
  108637. break;
  108638. case 269 /* JsxClosingElement */:
  108639. if (token.parent.tagName === token) {
  108640. return 20 /* jsxCloseTagName */;
  108641. }
  108642. break;
  108643. case 267 /* JsxSelfClosingElement */:
  108644. if (token.parent.tagName === token) {
  108645. return 21 /* jsxSelfClosingTagName */;
  108646. }
  108647. break;
  108648. case 273 /* JsxAttribute */:
  108649. if (token.parent.name === token) {
  108650. return 22 /* jsxAttribute */;
  108651. }
  108652. break;
  108653. }
  108654. return undefined;
  108655. }
  108656. // for accurate classification, the actual token should be passed in. however, for
  108657. // cases like 'disabled merge code' classification, we just get the token kind and
  108658. // classify based on that instead.
  108659. function classifyTokenType(tokenKind, token) {
  108660. if (ts.isKeyword(tokenKind)) {
  108661. return 3 /* keyword */;
  108662. }
  108663. // Special case `<` and `>`: If they appear in a generic context they are punctuation,
  108664. // not operators.
  108665. if (tokenKind === 29 /* LessThanToken */ || tokenKind === 31 /* GreaterThanToken */) {
  108666. // If the node owning the token has a type argument list or type parameter list, then
  108667. // we can effectively assume that a '<' and '>' belong to those lists.
  108668. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) {
  108669. return 10 /* punctuation */;
  108670. }
  108671. }
  108672. if (ts.isPunctuation(tokenKind)) {
  108673. if (token) {
  108674. var parent = token.parent;
  108675. if (tokenKind === 62 /* EqualsToken */) {
  108676. // the '=' in a variable declaration is special cased here.
  108677. if (parent.kind === 242 /* VariableDeclaration */ ||
  108678. parent.kind === 159 /* PropertyDeclaration */ ||
  108679. parent.kind === 156 /* Parameter */ ||
  108680. parent.kind === 273 /* JsxAttribute */) {
  108681. return 5 /* operator */;
  108682. }
  108683. }
  108684. if (parent.kind === 209 /* BinaryExpression */ ||
  108685. parent.kind === 207 /* PrefixUnaryExpression */ ||
  108686. parent.kind === 208 /* PostfixUnaryExpression */ ||
  108687. parent.kind === 210 /* ConditionalExpression */) {
  108688. return 5 /* operator */;
  108689. }
  108690. }
  108691. return 10 /* punctuation */;
  108692. }
  108693. else if (tokenKind === 8 /* NumericLiteral */) {
  108694. return 4 /* numericLiteral */;
  108695. }
  108696. else if (tokenKind === 9 /* BigIntLiteral */) {
  108697. return 25 /* bigintLiteral */;
  108698. }
  108699. else if (tokenKind === 10 /* StringLiteral */) {
  108700. return token && token.parent.kind === 273 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
  108701. }
  108702. else if (tokenKind === 13 /* RegularExpressionLiteral */) {
  108703. // TODO: we should get another classification type for these literals.
  108704. return 6 /* stringLiteral */;
  108705. }
  108706. else if (ts.isTemplateLiteralKind(tokenKind)) {
  108707. // TODO (drosen): we should *also* get another classification type for these literals.
  108708. return 6 /* stringLiteral */;
  108709. }
  108710. else if (tokenKind === 11 /* JsxText */) {
  108711. return 23 /* jsxText */;
  108712. }
  108713. else if (tokenKind === 75 /* Identifier */) {
  108714. if (token) {
  108715. switch (token.parent.kind) {
  108716. case 245 /* ClassDeclaration */:
  108717. if (token.parent.name === token) {
  108718. return 11 /* className */;
  108719. }
  108720. return;
  108721. case 155 /* TypeParameter */:
  108722. if (token.parent.name === token) {
  108723. return 15 /* typeParameterName */;
  108724. }
  108725. return;
  108726. case 246 /* InterfaceDeclaration */:
  108727. if (token.parent.name === token) {
  108728. return 13 /* interfaceName */;
  108729. }
  108730. return;
  108731. case 248 /* EnumDeclaration */:
  108732. if (token.parent.name === token) {
  108733. return 12 /* enumName */;
  108734. }
  108735. return;
  108736. case 249 /* ModuleDeclaration */:
  108737. if (token.parent.name === token) {
  108738. return 14 /* moduleName */;
  108739. }
  108740. return;
  108741. case 156 /* Parameter */:
  108742. if (token.parent.name === token) {
  108743. return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
  108744. }
  108745. return;
  108746. }
  108747. }
  108748. return 2 /* identifier */;
  108749. }
  108750. }
  108751. function processElement(element) {
  108752. if (!element) {
  108753. return;
  108754. }
  108755. // Ignore nodes that don't intersect the original span to classify.
  108756. if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
  108757. checkForClassificationCancellation(cancellationToken, element.kind);
  108758. for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) {
  108759. var child = _a[_i];
  108760. if (!tryClassifyNode(child)) {
  108761. // Recurse into our child nodes.
  108762. processElement(child);
  108763. }
  108764. }
  108765. }
  108766. }
  108767. }
  108768. ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications;
  108769. })(ts || (ts = {}));
  108770. /* @internal */
  108771. var ts;
  108772. (function (ts) {
  108773. var Completions;
  108774. (function (Completions) {
  108775. var StringCompletions;
  108776. (function (StringCompletions) {
  108777. function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) {
  108778. if (ts.isInReferenceComment(sourceFile, position)) {
  108779. var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host);
  108780. return entries && convertPathCompletions(entries);
  108781. }
  108782. if (ts.isInString(sourceFile, position, contextToken)) {
  108783. if (!contextToken || !ts.isStringLiteralLike(contextToken))
  108784. return undefined;
  108785. var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host);
  108786. return convertStringLiteralCompletions(entries, sourceFile, checker, log, preferences);
  108787. }
  108788. }
  108789. StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions;
  108790. function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) {
  108791. if (completion === undefined) {
  108792. return undefined;
  108793. }
  108794. switch (completion.kind) {
  108795. case 0 /* Paths */:
  108796. return convertPathCompletions(completion.paths);
  108797. case 1 /* Properties */: {
  108798. var entries = [];
  108799. Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
  108800. return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
  108801. }
  108802. case 2 /* Types */: {
  108803. var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); });
  108804. return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
  108805. }
  108806. default:
  108807. return ts.Debug.assertNever(completion);
  108808. }
  108809. }
  108810. function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) {
  108811. if (!contextToken || !ts.isStringLiteralLike(contextToken))
  108812. return undefined;
  108813. var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host);
  108814. return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken);
  108815. }
  108816. StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails;
  108817. function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
  108818. switch (completion.kind) {
  108819. case 0 /* Paths */: {
  108820. var match = ts.find(completion.paths, function (p) { return p.name === name; });
  108821. return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]);
  108822. }
  108823. case 1 /* Properties */: {
  108824. var match = ts.find(completion.symbols, function (s) { return s.name === name; });
  108825. return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
  108826. }
  108827. case 2 /* Types */:
  108828. return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined;
  108829. default:
  108830. return ts.Debug.assertNever(completion);
  108831. }
  108832. }
  108833. function convertPathCompletions(pathCompletions) {
  108834. var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
  108835. var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of.
  108836. var entries = pathCompletions.map(function (_a) {
  108837. var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension;
  108838. return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: Completions.SortText.LocationPriority, replacementSpan: span });
  108839. });
  108840. return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
  108841. }
  108842. function kindModifiersFromExtension(extension) {
  108843. switch (extension) {
  108844. case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */;
  108845. case ".js" /* Js */: return ".js" /* jsModifier */;
  108846. case ".json" /* Json */: return ".json" /* jsonModifier */;
  108847. case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
  108848. case ".ts" /* Ts */: return ".ts" /* tsModifier */;
  108849. case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
  108850. case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
  108851. case undefined: return "" /* none */;
  108852. default:
  108853. return ts.Debug.assertNever(extension);
  108854. }
  108855. }
  108856. var StringLiteralCompletionKind;
  108857. (function (StringLiteralCompletionKind) {
  108858. StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths";
  108859. StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties";
  108860. StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types";
  108861. })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {}));
  108862. function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) {
  108863. var parent = node.parent;
  108864. switch (parent.kind) {
  108865. case 187 /* LiteralType */:
  108866. switch (parent.parent.kind) {
  108867. case 169 /* TypeReference */:
  108868. return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false };
  108869. case 185 /* IndexedAccessType */:
  108870. // Get all apparent property names
  108871. // i.e. interface Foo {
  108872. // foo: string;
  108873. // bar: string;
  108874. // }
  108875. // let x: Foo["/*completion position*/"]
  108876. return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType));
  108877. case 188 /* ImportType */:
  108878. return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
  108879. case 178 /* UnionType */: {
  108880. if (!ts.isTypeReferenceNode(parent.parent.parent))
  108881. return undefined;
  108882. var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent);
  108883. var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); });
  108884. return { kind: 2 /* Types */, types: types, isNewIdentifier: false };
  108885. }
  108886. default:
  108887. return undefined;
  108888. }
  108889. case 281 /* PropertyAssignment */:
  108890. if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) {
  108891. // Get quoted name of properties of the object literal expression
  108892. // i.e. interface ConfigFiles {
  108893. // 'jspm:dev': string
  108894. // }
  108895. // let files: ConfigFiles = {
  108896. // '/*completion position*/'
  108897. // }
  108898. //
  108899. // function foo(c: ConfigFiles) {}
  108900. // foo({
  108901. // '/*completion position*/'
  108902. // });
  108903. return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
  108904. }
  108905. return fromContextualType();
  108906. case 195 /* ElementAccessExpression */: {
  108907. var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression;
  108908. if (node === argumentExpression) {
  108909. // Get all names of properties on the expression
  108910. // i.e. interface A {
  108911. // 'prop1': string
  108912. // }
  108913. // let a: A;
  108914. // a['/*completion position*/']
  108915. return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
  108916. }
  108917. return undefined;
  108918. }
  108919. case 196 /* CallExpression */:
  108920. case 197 /* NewExpression */:
  108921. if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) {
  108922. var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
  108923. // Get string literal completions from specialized signatures of the target
  108924. // i.e. declare function f(a: 'A');
  108925. // f("/*completion position*/")
  108926. return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType();
  108927. }
  108928. // falls through (is `require("")` or `import("")`)
  108929. case 254 /* ImportDeclaration */:
  108930. case 260 /* ExportDeclaration */:
  108931. case 265 /* ExternalModuleReference */:
  108932. // Get all known external module names or complete a path to a module
  108933. // i.e. import * as ns from "/*completion position*/";
  108934. // var y = import("/*completion position*/");
  108935. // import x = require("/*completion position*/");
  108936. // var y = require("/*completion position*/");
  108937. // export * from "/*completion position*/";
  108938. return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
  108939. default:
  108940. return fromContextualType();
  108941. }
  108942. function fromContextualType() {
  108943. // Get completion for string literal from string literal type
  108944. // i.e. var x: "hi" | "hello" = "/*completion position*/"
  108945. return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false };
  108946. }
  108947. }
  108948. function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
  108949. return ts.mapDefined(union.types, function (type) {
  108950. return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined;
  108951. });
  108952. }
  108953. function getStringLiteralCompletionsFromSignature(argumentInfo, checker) {
  108954. var isNewIdentifier = false;
  108955. var uniques = ts.createMap();
  108956. var candidates = [];
  108957. checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount);
  108958. var types = ts.flatMap(candidates, function (candidate) {
  108959. if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length)
  108960. return;
  108961. var type = checker.getParameterType(candidate, argumentInfo.argumentIndex);
  108962. isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */);
  108963. return getStringLiteralTypes(type, uniques);
  108964. });
  108965. return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier };
  108966. }
  108967. function stringLiteralCompletionsFromProperties(type) {
  108968. return type && {
  108969. kind: 1 /* Properties */,
  108970. symbols: type.getApparentProperties().filter(function (prop) { return !ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration); }),
  108971. hasIndexSignature: ts.hasIndexSignature(type)
  108972. };
  108973. }
  108974. function getStringLiteralTypes(type, uniques) {
  108975. if (uniques === void 0) { uniques = ts.createMap(); }
  108976. if (!type)
  108977. return ts.emptyArray;
  108978. type = ts.skipConstraint(type);
  108979. return type.isUnion() ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) :
  108980. type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) ? [type] : ts.emptyArray;
  108981. }
  108982. function nameAndKind(name, kind, extension) {
  108983. return { name: name, kind: kind, extension: extension };
  108984. }
  108985. function directoryResult(name) {
  108986. return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined);
  108987. }
  108988. function addReplacementSpans(text, textStart, names) {
  108989. var span = getDirectoryFragmentTextSpan(text, textStart);
  108990. return names.map(function (_a) {
  108991. var name = _a.name, kind = _a.kind, extension = _a.extension;
  108992. return ({ name: name, kind: kind, extension: extension, span: span });
  108993. });
  108994. }
  108995. function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) {
  108996. return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker));
  108997. }
  108998. function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) {
  108999. var literalValue = ts.normalizeSlashes(node.text);
  109000. var scriptPath = sourceFile.path;
  109001. var scriptDirectory = ts.getDirectoryPath(scriptPath);
  109002. return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue))
  109003. ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath)
  109004. : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
  109005. }
  109006. function getExtensionOptions(compilerOptions, includeExtensions) {
  109007. if (includeExtensions === void 0) { includeExtensions = false; }
  109008. return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions };
  109009. }
  109010. function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) {
  109011. var extensionOptions = getExtensionOptions(compilerOptions);
  109012. if (compilerOptions.rootDirs) {
  109013. return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath);
  109014. }
  109015. else {
  109016. return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath);
  109017. }
  109018. }
  109019. function getSupportedExtensionsForModuleResolution(compilerOptions) {
  109020. var extensions = ts.getSupportedExtensions(compilerOptions);
  109021. return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
  109022. extensions.concat(".json" /* Json */) :
  109023. extensions;
  109024. }
  109025. /**
  109026. * Takes a script path and returns paths for all potential folders that could be merged with its
  109027. * containing folder via the "rootDirs" compiler option
  109028. */
  109029. function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
  109030. // Make all paths absolute/normalized if they are not already
  109031. rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
  109032. // Determine the path to the directory containing the script relative to the root directory it is contained within
  109033. var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
  109034. return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
  109035. }); // TODO: GH#18217
  109036. // Now find a path for each potential directory that is to be merged with the one containing the script
  109037. return ts.deduplicate(__spreadArrays(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), [scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
  109038. }
  109039. function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
  109040. var basePath = compilerOptions.project || host.getCurrentDirectory();
  109041. var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
  109042. var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
  109043. return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
  109044. }
  109045. /**
  109046. * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
  109047. */
  109048. function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) {
  109049. var extensions = _a.extensions, includeExtensions = _a.includeExtensions;
  109050. if (result === void 0) { result = []; }
  109051. if (fragment === undefined) {
  109052. fragment = "";
  109053. }
  109054. fragment = ts.normalizeSlashes(fragment);
  109055. /**
  109056. * Remove the basename from the path. Note that we don't use the basename to filter completions;
  109057. * the client is responsible for refining completions.
  109058. */
  109059. if (!ts.hasTrailingDirectorySeparator(fragment)) {
  109060. fragment = ts.getDirectoryPath(fragment);
  109061. }
  109062. if (fragment === "") {
  109063. fragment = "." + ts.directorySeparator;
  109064. }
  109065. fragment = ts.ensureTrailingDirectorySeparator(fragment);
  109066. // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
  109067. var absolutePath = ts.resolvePath(scriptPath, fragment);
  109068. var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
  109069. var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
  109070. if (!ts.tryDirectoryExists(host, baseDirectory))
  109071. return result;
  109072. // Enumerate the available files if possible
  109073. var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]);
  109074. if (files) {
  109075. /**
  109076. * Multiple file entries might map to the same truncated name once we remove extensions
  109077. * (happens iff includeExtensions === false)so we use a set-like data structure. Eg:
  109078. *
  109079. * both foo.ts and foo.tsx become foo
  109080. */
  109081. var foundFiles = ts.createMap(); // maps file to its extension
  109082. for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
  109083. var filePath = files_1[_i];
  109084. filePath = ts.normalizePath(filePath);
  109085. if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
  109086. continue;
  109087. }
  109088. var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
  109089. foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath));
  109090. }
  109091. foundFiles.forEach(function (ext, foundFile) {
  109092. result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext));
  109093. });
  109094. }
  109095. // If possible, get folder completion as well
  109096. var directories = ts.tryGetDirectories(host, baseDirectory);
  109097. if (directories) {
  109098. for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) {
  109099. var directory = directories_1[_b];
  109100. var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
  109101. if (directoryName !== "@types") {
  109102. result.push(directoryResult(directoryName));
  109103. }
  109104. }
  109105. }
  109106. // check for a version redirect
  109107. var packageJsonPath = ts.findPackageJson(baseDirectory, host);
  109108. if (packageJsonPath) {
  109109. var packageJson = ts.readJson(packageJsonPath, host);
  109110. var typesVersions = packageJson.typesVersions;
  109111. if (typeof typesVersions === "object") {
  109112. var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions);
  109113. var versionPaths = versionResult && versionResult.paths;
  109114. var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length);
  109115. if (versionPaths) {
  109116. addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host);
  109117. }
  109118. }
  109119. }
  109120. return result;
  109121. }
  109122. function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) {
  109123. for (var path in paths) {
  109124. if (!ts.hasProperty(paths, path))
  109125. continue;
  109126. var patterns = paths[path];
  109127. if (patterns) {
  109128. var _loop_1 = function (name, kind, extension) {
  109129. // Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
  109130. if (!result.some(function (entry) { return entry.name === name; })) {
  109131. result.push(nameAndKind(name, kind, extension));
  109132. }
  109133. };
  109134. for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
  109135. var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
  109136. _loop_1(name, kind, extension);
  109137. }
  109138. }
  109139. }
  109140. }
  109141. /**
  109142. * Check all of the declared modules and those in node modules. Possible sources of modules:
  109143. * Modules that are found by the type checker
  109144. * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option)
  109145. * Modules from node_modules (i.e. those listed in package.json)
  109146. * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
  109147. */
  109148. function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
  109149. var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
  109150. var result = [];
  109151. var extensionOptions = getExtensionOptions(compilerOptions);
  109152. if (baseUrl) {
  109153. var projectDir = compilerOptions.project || host.getCurrentDirectory();
  109154. var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl));
  109155. getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result);
  109156. if (paths) {
  109157. addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host);
  109158. }
  109159. }
  109160. var fragmentDirectory = getFragmentDirectory(fragment);
  109161. for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) {
  109162. var ambientName = _a[_i];
  109163. result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined));
  109164. }
  109165. getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result);
  109166. if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) {
  109167. // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies.
  109168. // (But do if we didn't find anything, e.g. 'package.json' missing.)
  109169. var foundGlobal = false;
  109170. if (fragmentDirectory === undefined) {
  109171. var _loop_2 = function (moduleName) {
  109172. if (!result.some(function (entry) { return entry.name === moduleName; })) {
  109173. foundGlobal = true;
  109174. result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
  109175. }
  109176. };
  109177. for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
  109178. var moduleName = _c[_b];
  109179. _loop_2(moduleName);
  109180. }
  109181. }
  109182. if (!foundGlobal) {
  109183. ts.forEachAncestorDirectory(scriptPath, function (ancestor) {
  109184. var nodeModules = ts.combinePaths(ancestor, "node_modules");
  109185. if (ts.tryDirectoryExists(host, nodeModules)) {
  109186. getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result);
  109187. }
  109188. });
  109189. }
  109190. }
  109191. return result;
  109192. }
  109193. function getFragmentDirectory(fragment) {
  109194. return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
  109195. }
  109196. function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) {
  109197. if (!ts.endsWith(path, "*")) {
  109198. // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
  109199. return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray;
  109200. }
  109201. var pathPrefix = path.slice(0, path.length - 1);
  109202. var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix);
  109203. return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) {
  109204. return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host);
  109205. });
  109206. function justPathMappingName(name) {
  109207. return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray;
  109208. }
  109209. }
  109210. function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) {
  109211. if (!host.readDirectory) {
  109212. return undefined;
  109213. }
  109214. var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined;
  109215. if (!parsed) {
  109216. return undefined;
  109217. }
  109218. // The prefix has two effective parts: the directory path and the base component after the filepath that is not a
  109219. // full directory component. For example: directory/path/of/prefix/base*
  109220. var normalizedPrefix = ts.resolvePath(parsed.prefix);
  109221. var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
  109222. var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
  109223. var fragmentHasPath = containsSlash(fragment);
  109224. var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
  109225. // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
  109226. var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
  109227. var normalizedSuffix = ts.normalizePath(parsed.suffix);
  109228. // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
  109229. var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
  109230. var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase;
  109231. // If we have a suffix, then we need to read the directory all the way down. We could create a glob
  109232. // that encodes the suffix, but we would have to escape the character "?" which readDirectory
  109233. // doesn't support. For now, this is safer but slower
  109234. var includeGlob = normalizedSuffix ? "**/*" : "./*";
  109235. var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) {
  109236. var extension = ts.tryGetExtensionFromPath(match);
  109237. var name = trimPrefixAndSuffix(match);
  109238. return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension);
  109239. });
  109240. var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) {
  109241. var name = trimPrefixAndSuffix(dir);
  109242. return name === undefined ? undefined : directoryResult(name);
  109243. });
  109244. return __spreadArrays(matches, directories);
  109245. function trimPrefixAndSuffix(path) {
  109246. var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix);
  109247. return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner);
  109248. }
  109249. }
  109250. function withoutStartAndEnd(s, start, end) {
  109251. return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined;
  109252. }
  109253. function removeLeadingDirectorySeparator(path) {
  109254. return path[0] === ts.directorySeparator ? path.slice(1) : path;
  109255. }
  109256. function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) {
  109257. // Get modules that the type checker picked up
  109258. var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); });
  109259. var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); });
  109260. // Nested modules of the form "module-name/sub" need to be adjusted to only return the string
  109261. // after the last '/' that appears in the fragment because that's where the replacement span
  109262. // starts
  109263. if (fragmentDirectory !== undefined) {
  109264. var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory);
  109265. return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); });
  109266. }
  109267. return nonRelativeModuleNames;
  109268. }
  109269. function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
  109270. var token = ts.getTokenAtPosition(sourceFile, position);
  109271. var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
  109272. var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; });
  109273. if (!range) {
  109274. return undefined;
  109275. }
  109276. var text = sourceFile.text.slice(range.pos, position);
  109277. var match = tripleSlashDirectiveFragmentRegex.exec(text);
  109278. if (!match) {
  109279. return undefined;
  109280. }
  109281. var prefix = match[1], kind = match[2], toComplete = match[3];
  109282. var scriptPath = ts.getDirectoryPath(sourceFile.path);
  109283. var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path)
  109284. : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions))
  109285. : ts.Debug.fail();
  109286. return addReplacementSpans(toComplete, range.pos + prefix.length, names);
  109287. }
  109288. function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) {
  109289. if (result === void 0) { result = []; }
  109290. // Check for typings specified in compiler options
  109291. var seen = ts.createMap();
  109292. var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
  109293. for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
  109294. var root = typeRoots_1[_i];
  109295. getCompletionEntriesFromDirectories(root);
  109296. }
  109297. // Also get all @types typings installed in visible node_modules directories
  109298. for (var _a = 0, _b = ts.findPackageJsons(scriptPath, host); _a < _b.length; _a++) {
  109299. var packageJson = _b[_a];
  109300. var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types");
  109301. getCompletionEntriesFromDirectories(typesDir);
  109302. }
  109303. return result;
  109304. function getCompletionEntriesFromDirectories(directory) {
  109305. if (!ts.tryDirectoryExists(host, directory))
  109306. return;
  109307. for (var _i = 0, _a = ts.tryGetDirectories(host, directory); _i < _a.length; _i++) {
  109308. var typeDirectoryName = _a[_i];
  109309. var packageName = ts.unmangleScopedPackageName(typeDirectoryName);
  109310. if (options.types && !ts.contains(options.types, packageName))
  109311. continue;
  109312. if (fragmentDirectory === undefined) {
  109313. if (!seen.has(packageName)) {
  109314. result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined));
  109315. seen.set(packageName, true);
  109316. }
  109317. }
  109318. else {
  109319. var baseDirectory = ts.combinePaths(directory, typeDirectoryName);
  109320. var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host));
  109321. if (remainingFragment !== undefined) {
  109322. getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result);
  109323. }
  109324. }
  109325. }
  109326. }
  109327. }
  109328. function enumerateNodeModulesVisibleToScript(host, scriptPath) {
  109329. if (!host.readFile || !host.fileExists)
  109330. return ts.emptyArray;
  109331. var result = [];
  109332. for (var _i = 0, _a = ts.findPackageJsons(scriptPath, host); _i < _a.length; _i++) {
  109333. var packageJson = _a[_i];
  109334. var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined
  109335. // Provide completions for all non @types dependencies
  109336. for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) {
  109337. var key = nodeModulesDependencyKeys_1[_b];
  109338. var dependencies = contents[key];
  109339. if (!dependencies)
  109340. continue;
  109341. for (var dep in dependencies) {
  109342. if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) {
  109343. result.push(dep);
  109344. }
  109345. }
  109346. }
  109347. }
  109348. return result;
  109349. }
  109350. // Replace everything after the last directory separator that appears
  109351. function getDirectoryFragmentTextSpan(text, textStart) {
  109352. var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\"));
  109353. var offset = index !== -1 ? index + 1 : 0;
  109354. // If the range is an identifier, span is unnecessary.
  109355. var length = text.length - offset;
  109356. return length === 0 || ts.isIdentifierText(text.substr(offset, length), 99 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
  109357. }
  109358. // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
  109359. function isPathRelativeToScript(path) {
  109360. if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) {
  109361. var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1;
  109362. var slashCharCode = path.charCodeAt(slashIndex);
  109363. return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */;
  109364. }
  109365. return false;
  109366. }
  109367. /**
  109368. * Matches a triple slash reference directive with an incomplete string literal for its path. Used
  109369. * to determine if the caret is currently within the string literal and capture the literal fragment
  109370. * for completions.
  109371. * For example, this matches
  109372. *
  109373. * /// <reference path="fragment
  109374. *
  109375. * but not
  109376. *
  109377. * /// <reference path="fragment"
  109378. */
  109379. var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
  109380. var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
  109381. function containsSlash(fragment) {
  109382. return ts.stringContains(fragment, ts.directorySeparator);
  109383. }
  109384. })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {}));
  109385. })(Completions = ts.Completions || (ts.Completions = {}));
  109386. })(ts || (ts = {}));
  109387. /* @internal */
  109388. var ts;
  109389. (function (ts) {
  109390. var Completions;
  109391. (function (Completions) {
  109392. var SortText;
  109393. (function (SortText) {
  109394. SortText["LocationPriority"] = "0";
  109395. SortText["OptionalMember"] = "1";
  109396. SortText["MemberDeclaredBySpreadAssignment"] = "2";
  109397. SortText["SuggestedClassMembers"] = "3";
  109398. SortText["GlobalsOrKeywords"] = "4";
  109399. SortText["AutoImportSuggestions"] = "5";
  109400. SortText["JavascriptIdentifiers"] = "6";
  109401. })(SortText = Completions.SortText || (Completions.SortText = {}));
  109402. var SymbolOriginInfoKind;
  109403. (function (SymbolOriginInfoKind) {
  109404. SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType";
  109405. SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMember"] = 2] = "SymbolMember";
  109406. SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export";
  109407. SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise";
  109408. SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable";
  109409. SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport";
  109410. SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport";
  109411. })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {}));
  109412. function originIsThisType(origin) {
  109413. return !!(origin.kind & 1 /* ThisType */);
  109414. }
  109415. function originIsSymbolMember(origin) {
  109416. return !!(origin.kind & 2 /* SymbolMember */);
  109417. }
  109418. function originIsExport(origin) {
  109419. return !!(origin.kind & 4 /* Export */);
  109420. }
  109421. function originIsPromise(origin) {
  109422. return !!(origin.kind & 8 /* Promise */);
  109423. }
  109424. function originIsNullableMember(origin) {
  109425. return !!(origin.kind & 16 /* Nullable */);
  109426. }
  109427. var KeywordCompletionFilters;
  109428. (function (KeywordCompletionFilters) {
  109429. KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None";
  109430. KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All";
  109431. KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords";
  109432. KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords";
  109433. KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
  109434. KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
  109435. KeywordCompletionFilters[KeywordCompletionFilters["TypeAssertionKeywords"] = 6] = "TypeAssertionKeywords";
  109436. KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 7] = "TypeKeywords";
  109437. KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 7] = "Last";
  109438. })(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
  109439. var GlobalsSearch;
  109440. (function (GlobalsSearch) {
  109441. GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue";
  109442. GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success";
  109443. GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail";
  109444. })(GlobalsSearch || (GlobalsSearch = {}));
  109445. function createImportSuggestionsForFileCache() {
  109446. var cache;
  109447. var projectVersion;
  109448. var fileName;
  109449. return {
  109450. isEmpty: function () {
  109451. return !cache;
  109452. },
  109453. clear: function () {
  109454. cache = undefined;
  109455. fileName = undefined;
  109456. projectVersion = undefined;
  109457. },
  109458. set: function (file, suggestions, version) {
  109459. cache = suggestions;
  109460. fileName = file;
  109461. if (version) {
  109462. projectVersion = version;
  109463. }
  109464. },
  109465. get: function (file, checker, version) {
  109466. if (file !== fileName) {
  109467. return undefined;
  109468. }
  109469. if (version) {
  109470. return projectVersion === version ? cache : undefined;
  109471. }
  109472. ts.forEach(cache, function (suggestion) {
  109473. var _a, _b, _c;
  109474. // If the symbol/moduleSymbol was a merged symbol, it will have a new identity
  109475. // in the checker, even though the symbols to merge are the same (guaranteed by
  109476. // cache invalidation in synchronizeHostData).
  109477. if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) {
  109478. suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport
  109479. ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol : suggestion.symbol.declarations[0].symbol);
  109480. }
  109481. if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) {
  109482. suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol);
  109483. }
  109484. });
  109485. return cache;
  109486. },
  109487. };
  109488. }
  109489. Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache;
  109490. function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) {
  109491. var typeChecker = program.getTypeChecker();
  109492. var compilerOptions = program.getCompilerOptions();
  109493. var contextToken = ts.findPrecedingToken(position, sourceFile);
  109494. if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) {
  109495. return undefined;
  109496. }
  109497. var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences);
  109498. if (stringCompletions) {
  109499. return stringCompletions;
  109500. }
  109501. if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent)
  109502. && (contextToken.kind === 77 /* BreakKeyword */ || contextToken.kind === 82 /* ContinueKeyword */ || contextToken.kind === 75 /* Identifier */)) {
  109503. return getLabelCompletionAtPosition(contextToken.parent);
  109504. }
  109505. var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined, host);
  109506. if (!completionData) {
  109507. return undefined;
  109508. }
  109509. switch (completionData.kind) {
  109510. case 0 /* Data */:
  109511. return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences);
  109512. case 1 /* JsDocTagName */:
  109513. // If the current position is a jsDoc tag name, only tag names should be provided for completion
  109514. return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions());
  109515. case 2 /* JsDocTag */:
  109516. // If the current position is a jsDoc tag, only tags should be provided for completion
  109517. return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions());
  109518. case 3 /* JsDocParameterName */:
  109519. return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
  109520. default:
  109521. return ts.Debug.assertNever(completionData);
  109522. }
  109523. }
  109524. Completions.getCompletionsAtPosition = getCompletionsAtPosition;
  109525. function jsdocCompletionInfo(entries) {
  109526. return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
  109527. }
  109528. function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) {
  109529. var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap;
  109530. if (location && location.parent && ts.isJsxClosingElement(location.parent)) {
  109531. // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
  109532. // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
  109533. // For example:
  109534. // var x = <div> </ /*1*/
  109535. // The completion list at "1" will contain "div>" with type any
  109536. // And at `<div> </ /*1*/ >` (with a closing `>`), the completion list will contain "div".
  109537. var tagName = location.parent.parent.openingElement.tagName;
  109538. var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile);
  109539. var entry = {
  109540. name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"),
  109541. kind: "class" /* classElement */,
  109542. kindModifiers: undefined,
  109543. sortText: SortText.LocationPriority,
  109544. };
  109545. return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] };
  109546. }
  109547. var entries = [];
  109548. if (isUncheckedFile(sourceFile, compilerOptions)) {
  109549. var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap);
  109550. getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217
  109551. }
  109552. else {
  109553. if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) {
  109554. return undefined;
  109555. }
  109556. getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap);
  109557. }
  109558. if (keywordFilters !== 0 /* None */) {
  109559. var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
  109560. for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
  109561. var keywordEntry = _a[_i];
  109562. if (!entryNames.has(keywordEntry.name)) {
  109563. entries.push(keywordEntry);
  109564. }
  109565. }
  109566. }
  109567. for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) {
  109568. var literal = literals_1[_b];
  109569. entries.push(createCompletionEntryForLiteral(literal));
  109570. }
  109571. return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
  109572. }
  109573. function isUncheckedFile(sourceFile, compilerOptions) {
  109574. return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions);
  109575. }
  109576. function isMemberCompletionKind(kind) {
  109577. switch (kind) {
  109578. case 0 /* ObjectPropertyDeclaration */:
  109579. case 3 /* MemberLike */:
  109580. case 2 /* PropertyAccess */:
  109581. return true;
  109582. default:
  109583. return false;
  109584. }
  109585. }
  109586. function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) {
  109587. ts.getNameTable(sourceFile).forEach(function (pos, name) {
  109588. // Skip identifiers produced only from the current location
  109589. if (pos === position) {
  109590. return;
  109591. }
  109592. var realName = ts.unescapeLeadingUnderscores(name);
  109593. if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) {
  109594. entries.push({
  109595. name: realName,
  109596. kind: "warning" /* warning */,
  109597. kindModifiers: "",
  109598. sortText: SortText.JavascriptIdentifiers,
  109599. isFromUncheckedFile: true
  109600. });
  109601. }
  109602. });
  109603. }
  109604. var completionNameForLiteral = function (literal) {
  109605. return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal);
  109606. };
  109607. function createCompletionEntryForLiteral(literal) {
  109608. return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority };
  109609. }
  109610. function createCompletionEntry(symbol, sortText, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) {
  109611. var insertText;
  109612. var replacementSpan;
  109613. var insertQuestionDot = origin && originIsNullableMember(origin);
  109614. var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
  109615. if (origin && originIsThisType(origin)) {
  109616. insertText = needsConvertPropertyAccess
  109617. ? "this" + (insertQuestionDot ? "?." : "") + "[" + ts.quote(name, preferences) + "]"
  109618. : "this" + (insertQuestionDot ? "?." : ".") + name;
  109619. }
  109620. // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790.
  109621. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro.
  109622. else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) {
  109623. insertText = useBraces ? needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]" : name;
  109624. if (insertQuestionDot || propertyAccessToConvert.questionDotToken) {
  109625. insertText = "?." + insertText;
  109626. }
  109627. var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile) ||
  109628. ts.findChildOfKind(propertyAccessToConvert, 28 /* QuestionDotToken */, sourceFile);
  109629. if (!dot) {
  109630. return undefined;
  109631. }
  109632. // If the text after the '.' starts with this name, write over it. Else, add new text.
  109633. var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end;
  109634. replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end);
  109635. }
  109636. if (isJsxInitializer) {
  109637. if (insertText === undefined)
  109638. insertText = name;
  109639. insertText = "{" + insertText + "}";
  109640. if (typeof isJsxInitializer !== "boolean") {
  109641. replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile);
  109642. }
  109643. }
  109644. if (origin && originIsPromise(origin) && propertyAccessToConvert) {
  109645. if (insertText === undefined)
  109646. insertText = name;
  109647. var precedingToken = ts.findPrecedingToken(propertyAccessToConvert.pos, sourceFile);
  109648. var awaitText = "";
  109649. if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
  109650. awaitText = ";";
  109651. }
  109652. awaitText += "(await " + propertyAccessToConvert.expression.getText() + ")";
  109653. insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText;
  109654. replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end);
  109655. }
  109656. if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) {
  109657. return undefined;
  109658. }
  109659. // TODO(drosen): Right now we just permit *all* semantic meanings when calling
  109660. // 'getSymbolKind' which is permissible given that it is backwards compatible; but
  109661. // really we should consider passing the meaning for the node so that we don't report
  109662. // that a suggestion for a value is an interface. We COULD also just do what
  109663. // 'getSymbolModifiers' does, which is to use the first declaration.
  109664. // Use a 'sortText' of 0' so that all symbol completion entries come before any other
  109665. // entries (like JavaScript identifier entries).
  109666. return {
  109667. name: name,
  109668. kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
  109669. kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
  109670. sortText: sortText,
  109671. source: getSourceFromOrigin(origin),
  109672. hasAction: origin && originIsExport(origin) || undefined,
  109673. isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined,
  109674. insertText: insertText,
  109675. replacementSpan: replacementSpan,
  109676. };
  109677. }
  109678. function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) {
  109679. return localSymbol === recommendedCompletion ||
  109680. !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion;
  109681. }
  109682. function getSourceFromOrigin(origin) {
  109683. return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined;
  109684. }
  109685. function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) {
  109686. var start = ts.timestamp();
  109687. // Tracks unique names.
  109688. // We don't set this for global variables or completions from external module exports, because we can have multiple of those.
  109689. // Based on the order we add things we will always see locals first, then globals, then module exports.
  109690. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
  109691. var uniques = ts.createMap();
  109692. for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
  109693. var symbol = symbols_1[_i];
  109694. var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
  109695. var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind);
  109696. if (!info) {
  109697. continue;
  109698. }
  109699. var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess;
  109700. if (uniques.has(name)) {
  109701. continue;
  109702. }
  109703. var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
  109704. if (!entry) {
  109705. continue;
  109706. }
  109707. // Latter case tests whether this is a global variable.
  109708. if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217
  109709. uniques.set(name, true);
  109710. }
  109711. entries.push(entry);
  109712. }
  109713. log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start));
  109714. return uniques;
  109715. }
  109716. Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols;
  109717. function getLabelCompletionAtPosition(node) {
  109718. var entries = getLabelStatementCompletions(node);
  109719. if (entries.length) {
  109720. return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
  109721. }
  109722. }
  109723. function getLabelStatementCompletions(node) {
  109724. var entries = [];
  109725. var uniques = ts.createMap();
  109726. var current = node;
  109727. while (current) {
  109728. if (ts.isFunctionLike(current)) {
  109729. break;
  109730. }
  109731. if (ts.isLabeledStatement(current)) {
  109732. var name = current.label.text;
  109733. if (!uniques.has(name)) {
  109734. uniques.set(name, true);
  109735. entries.push({
  109736. name: name,
  109737. kindModifiers: "" /* none */,
  109738. kind: "label" /* label */,
  109739. sortText: SortText.LocationPriority
  109740. });
  109741. }
  109742. }
  109743. current = current.parent;
  109744. }
  109745. return entries;
  109746. }
  109747. function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host) {
  109748. var compilerOptions = program.getCompilerOptions();
  109749. var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host);
  109750. if (!completionData) {
  109751. return { type: "none" };
  109752. }
  109753. if (completionData.kind !== 0 /* Data */) {
  109754. return { type: "request", request: completionData };
  109755. }
  109756. var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation;
  109757. var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; });
  109758. if (literal !== undefined)
  109759. return { type: "literal", literal: literal };
  109760. // Find the symbol with the matching entry name.
  109761. // We don't need to perform character checks here because we're only comparing the
  109762. // name against 'entryName' (which is known to be good), not building a new
  109763. // completion entry.
  109764. return ts.firstDefined(symbols, function (symbol) {
  109765. var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
  109766. var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind);
  109767. return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source
  109768. ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation }
  109769. : undefined;
  109770. }) || { type: "none" };
  109771. }
  109772. function getSymbolName(symbol, origin, target) {
  109773. return origin && originIsExport(origin) && ((origin.isDefaultExport && symbol.escapedName === "default" /* Default */) ||
  109774. (symbol.escapedName === "export=" /* ExportEquals */))
  109775. // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
  109776. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; })
  109777. || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target)
  109778. : symbol.name;
  109779. }
  109780. function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
  109781. var typeChecker = program.getTypeChecker();
  109782. var compilerOptions = program.getCompilerOptions();
  109783. var name = entryId.name;
  109784. var contextToken = ts.findPrecedingToken(position, sourceFile);
  109785. if (ts.isInString(sourceFile, position, contextToken)) {
  109786. return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken);
  109787. }
  109788. // Compute all the completion symbols again.
  109789. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host);
  109790. switch (symbolCompletion.type) {
  109791. case "request": {
  109792. var request = symbolCompletion.request;
  109793. switch (request.kind) {
  109794. case 1 /* JsDocTagName */:
  109795. return ts.JsDoc.getJSDocTagNameCompletionDetails(name);
  109796. case 2 /* JsDocTag */:
  109797. return ts.JsDoc.getJSDocTagCompletionDetails(name);
  109798. case 3 /* JsDocParameterName */:
  109799. return ts.JsDoc.getJSDocParameterNameCompletionDetails(name);
  109800. default:
  109801. return ts.Debug.assertNever(request);
  109802. }
  109803. }
  109804. case "symbol": {
  109805. var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken;
  109806. var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay;
  109807. return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
  109808. }
  109809. case "literal": {
  109810. var literal = symbolCompletion.literal;
  109811. return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral);
  109812. }
  109813. case "none":
  109814. // Didn't find a symbol with this name. See if we can find a keyword instead.
  109815. return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined;
  109816. default:
  109817. ts.Debug.assertNever(symbolCompletion);
  109818. }
  109819. }
  109820. Completions.getCompletionEntryDetails = getCompletionEntryDetails;
  109821. function createSimpleDetails(name, kind, kind2) {
  109822. return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]);
  109823. }
  109824. function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) {
  109825. var _a = checker.runWithCancellationToken(cancellationToken, function (checker) {
  109826. return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */);
  109827. }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags;
  109828. return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
  109829. }
  109830. Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol;
  109831. function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
  109832. return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source };
  109833. }
  109834. Completions.createCompletionDetails = createCompletionDetails;
  109835. function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) {
  109836. var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
  109837. if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) {
  109838. return { codeActions: undefined, sourceDisplay: undefined };
  109839. }
  109840. var moduleSymbol = symbolOriginInfo.moduleSymbol;
  109841. var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker));
  109842. var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction;
  109843. return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] };
  109844. }
  109845. function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host) {
  109846. var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host);
  109847. return completion.type === "symbol" ? completion.symbol : undefined;
  109848. }
  109849. Completions.getCompletionEntrySymbol = getCompletionEntrySymbol;
  109850. var CompletionDataKind;
  109851. (function (CompletionDataKind) {
  109852. CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data";
  109853. CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName";
  109854. CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag";
  109855. CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName";
  109856. })(CompletionDataKind || (CompletionDataKind = {}));
  109857. var CompletionKind;
  109858. (function (CompletionKind) {
  109859. CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
  109860. CompletionKind[CompletionKind["Global"] = 1] = "Global";
  109861. CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
  109862. CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
  109863. CompletionKind[CompletionKind["String"] = 4] = "String";
  109864. CompletionKind[CompletionKind["None"] = 5] = "None";
  109865. })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {}));
  109866. function getRecommendedCompletion(previousToken, contextualType, checker) {
  109867. // For a union, return the first one with a recommended completion.
  109868. return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) {
  109869. var symbol = type && type.symbol;
  109870. // Don't include make a recommended completion for an abstract class
  109871. return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol))
  109872. ? getFirstSymbolInChain(symbol, previousToken, checker)
  109873. : undefined;
  109874. });
  109875. }
  109876. function getContextualType(previousToken, position, sourceFile, checker) {
  109877. var parent = previousToken.parent;
  109878. switch (previousToken.kind) {
  109879. case 75 /* Identifier */:
  109880. return ts.getContextualTypeFromParent(previousToken, checker);
  109881. case 62 /* EqualsToken */:
  109882. switch (parent.kind) {
  109883. case 242 /* VariableDeclaration */:
  109884. return checker.getContextualType(parent.initializer); // TODO: GH#18217
  109885. case 209 /* BinaryExpression */:
  109886. return checker.getTypeAtLocation(parent.left);
  109887. case 273 /* JsxAttribute */:
  109888. return checker.getContextualTypeForJsxAttribute(parent);
  109889. default:
  109890. return undefined;
  109891. }
  109892. case 99 /* NewKeyword */:
  109893. return checker.getContextualType(parent);
  109894. case 78 /* CaseKeyword */:
  109895. return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker);
  109896. case 18 /* OpenBraceToken */:
  109897. return ts.isJsxExpression(parent) && parent.parent.kind !== 266 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined;
  109898. default:
  109899. var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile);
  109900. return argInfo ?
  109901. // At `,`, treat this as the next argument after the comma.
  109902. checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) :
  109903. ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) ?
  109904. // completion at `x ===/**/` should be for the right side
  109905. checker.getTypeAtLocation(parent.left) :
  109906. checker.getContextualType(previousToken);
  109907. }
  109908. }
  109909. function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) {
  109910. var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false);
  109911. if (chain)
  109912. return ts.first(chain);
  109913. return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
  109914. }
  109915. function isModuleSymbol(symbol) {
  109916. return symbol.declarations.some(function (d) { return d.kind === 290 /* SourceFile */; });
  109917. }
  109918. function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) {
  109919. var typeChecker = program.getTypeChecker();
  109920. var start = ts.timestamp();
  109921. var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853
  109922. // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
  109923. log("getCompletionData: Get current token: " + (ts.timestamp() - start));
  109924. start = ts.timestamp();
  109925. var insideComment = ts.isInComment(sourceFile, position, currentToken);
  109926. log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
  109927. var insideJsDocTagTypeExpression = false;
  109928. var isInSnippetScope = false;
  109929. if (insideComment) {
  109930. if (ts.hasDocComment(sourceFile, position)) {
  109931. if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
  109932. // The current position is next to the '@' sign, when no tag name being provided yet.
  109933. // Provide a full list of tag names
  109934. return { kind: 1 /* JsDocTagName */ };
  109935. }
  109936. else {
  109937. // When completion is requested without "@", we will have check to make sure that
  109938. // there are no comments prefix the request position. We will only allow "*" and space.
  109939. // e.g
  109940. // /** |c| /*
  109941. //
  109942. // /**
  109943. // |c|
  109944. // */
  109945. //
  109946. // /**
  109947. // * |c|
  109948. // */
  109949. //
  109950. // /**
  109951. // * |c|
  109952. // */
  109953. var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
  109954. if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) {
  109955. return { kind: 2 /* JsDocTag */ };
  109956. }
  109957. }
  109958. }
  109959. // Completion should work inside certain JsDoc tags. For example:
  109960. // /** @type {number | string} */
  109961. // Completion should work in the brackets
  109962. var tag = getJsDocTagAtPosition(currentToken, position);
  109963. if (tag) {
  109964. if (tag.tagName.pos <= position && position <= tag.tagName.end) {
  109965. return { kind: 1 /* JsDocTagName */ };
  109966. }
  109967. if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
  109968. currentToken = ts.getTokenAtPosition(sourceFile, position);
  109969. if (!currentToken ||
  109970. (!ts.isDeclarationName(currentToken) &&
  109971. (currentToken.parent.kind !== 322 /* JSDocPropertyTag */ ||
  109972. currentToken.parent.name !== currentToken))) {
  109973. // Use as type location if inside tag's type expression
  109974. insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
  109975. }
  109976. }
  109977. if (!insideJsDocTagTypeExpression && ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
  109978. return { kind: 3 /* JsDocParameterName */, tag: tag };
  109979. }
  109980. }
  109981. if (!insideJsDocTagTypeExpression) {
  109982. // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal
  109983. // comment or the plain text part of a jsDoc comment, so no completion should be available
  109984. log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
  109985. return undefined;
  109986. }
  109987. }
  109988. start = ts.timestamp();
  109989. var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217
  109990. log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start));
  109991. // The decision to provide completion depends on the contextToken, which is determined through the previousToken.
  109992. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file
  109993. var contextToken = previousToken;
  109994. // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
  109995. // Skip this partial identifier and adjust the contextToken to the token that precedes it.
  109996. if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
  109997. var start_1 = ts.timestamp();
  109998. contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
  109999. log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
  110000. }
  110001. // Find the node where completion is requested on.
  110002. // Also determine whether we are trying to complete with members of that node
  110003. // or attributes of a JSX tag.
  110004. var node = currentToken;
  110005. var propertyAccessToConvert;
  110006. var isRightOfDot = false;
  110007. var isRightOfQuestionDot = false;
  110008. var isRightOfOpenTag = false;
  110009. var isStartingCloseTag = false;
  110010. var isJsxInitializer = false;
  110011. var location = ts.getTouchingPropertyName(sourceFile, position);
  110012. if (contextToken) {
  110013. // Bail out if this is a known invalid completion location
  110014. if (isCompletionListBlocker(contextToken)) {
  110015. log("Returning an empty list because completion was requested in an invalid position.");
  110016. return undefined;
  110017. }
  110018. var parent = contextToken.parent;
  110019. if (contextToken.kind === 24 /* DotToken */ || contextToken.kind === 28 /* QuestionDotToken */) {
  110020. isRightOfDot = contextToken.kind === 24 /* DotToken */;
  110021. isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */;
  110022. switch (parent.kind) {
  110023. case 194 /* PropertyAccessExpression */:
  110024. propertyAccessToConvert = parent;
  110025. node = propertyAccessToConvert.expression;
  110026. if (node.end === contextToken.pos &&
  110027. ts.isCallExpression(node) &&
  110028. node.getChildCount(sourceFile) &&
  110029. ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
  110030. // This is likely dot from incorrectly parsed call expression and user is starting to write spread
  110031. // eg: Math.min(./**/)
  110032. return undefined;
  110033. }
  110034. break;
  110035. case 153 /* QualifiedName */:
  110036. node = parent.left;
  110037. break;
  110038. case 249 /* ModuleDeclaration */:
  110039. node = parent.name;
  110040. break;
  110041. case 188 /* ImportType */:
  110042. case 219 /* MetaProperty */:
  110043. node = parent;
  110044. break;
  110045. default:
  110046. // There is nothing that precedes the dot, so this likely just a stray character
  110047. // or leading into a '...' token. Just bail out instead.
  110048. return undefined;
  110049. }
  110050. }
  110051. else if (sourceFile.languageVariant === 1 /* JSX */) {
  110052. // <UI.Test /* completion position */ />
  110053. // If the tagname is a property access expression, we will then walk up to the top most of property access expression.
  110054. // Then, try to get a JSX container and its associated attributes type.
  110055. if (parent && parent.kind === 194 /* PropertyAccessExpression */) {
  110056. contextToken = parent;
  110057. parent = parent.parent;
  110058. }
  110059. // Fix location
  110060. if (currentToken.parent === location) {
  110061. switch (currentToken.kind) {
  110062. case 31 /* GreaterThanToken */:
  110063. if (currentToken.parent.kind === 266 /* JsxElement */ || currentToken.parent.kind === 268 /* JsxOpeningElement */) {
  110064. location = currentToken;
  110065. }
  110066. break;
  110067. case 43 /* SlashToken */:
  110068. if (currentToken.parent.kind === 267 /* JsxSelfClosingElement */) {
  110069. location = currentToken;
  110070. }
  110071. break;
  110072. }
  110073. }
  110074. switch (parent.kind) {
  110075. case 269 /* JsxClosingElement */:
  110076. if (contextToken.kind === 43 /* SlashToken */) {
  110077. isStartingCloseTag = true;
  110078. location = contextToken;
  110079. }
  110080. break;
  110081. case 209 /* BinaryExpression */:
  110082. if (!binaryExpressionMayBeOpenTag(parent)) {
  110083. break;
  110084. }
  110085. // falls through
  110086. case 267 /* JsxSelfClosingElement */:
  110087. case 266 /* JsxElement */:
  110088. case 268 /* JsxOpeningElement */:
  110089. if (contextToken.kind === 29 /* LessThanToken */) {
  110090. isRightOfOpenTag = true;
  110091. location = contextToken;
  110092. }
  110093. break;
  110094. case 273 /* JsxAttribute */:
  110095. switch (previousToken.kind) {
  110096. case 62 /* EqualsToken */:
  110097. isJsxInitializer = true;
  110098. break;
  110099. case 75 /* Identifier */:
  110100. // For `<div x=[|f/**/|]`, `parent` will be `x` and `previousToken.parent` will be `f` (which is its own JsxAttribute)
  110101. // Note for `<div someBool f>` we don't want to treat this as a jsx inializer, instead it's the attribute name.
  110102. if (parent !== previousToken.parent &&
  110103. !parent.initializer &&
  110104. ts.findChildOfKind(parent, 62 /* EqualsToken */, sourceFile)) {
  110105. isJsxInitializer = previousToken;
  110106. }
  110107. }
  110108. break;
  110109. }
  110110. }
  110111. }
  110112. var semanticStart = ts.timestamp();
  110113. var completionKind = 5 /* None */;
  110114. var isNewIdentifierLocation = false;
  110115. var keywordFilters = 0 /* None */;
  110116. // This also gets mutated in nested-functions after the return
  110117. var symbols = [];
  110118. var symbolToOriginInfoMap = [];
  110119. var symbolToSortTextMap = [];
  110120. var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache();
  110121. var isTypeOnly = isTypeOnlyCompletion();
  110122. if (isRightOfDot || isRightOfQuestionDot) {
  110123. getTypeScriptMemberSymbols();
  110124. }
  110125. else if (isRightOfOpenTag) {
  110126. var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
  110127. tryGetGlobalSymbols();
  110128. symbols = tagSymbols.concat(symbols);
  110129. completionKind = 3 /* MemberLike */;
  110130. keywordFilters = 0 /* None */;
  110131. }
  110132. else if (isStartingCloseTag) {
  110133. var tagName = contextToken.parent.parent.openingElement.tagName;
  110134. var tagSymbol = typeChecker.getSymbolAtLocation(tagName);
  110135. if (tagSymbol) {
  110136. symbols = [tagSymbol];
  110137. }
  110138. completionKind = 3 /* MemberLike */;
  110139. keywordFilters = 0 /* None */;
  110140. }
  110141. else {
  110142. // For JavaScript or TypeScript, if we're not after a dot, then just try to get the
  110143. // global symbols in scope. These results should be valid for either language as
  110144. // the set of symbols that can be referenced from this location.
  110145. if (!tryGetGlobalSymbols()) {
  110146. return undefined;
  110147. }
  110148. }
  110149. log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
  110150. var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
  110151. var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
  110152. var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
  110153. return {
  110154. kind: 0 /* Data */,
  110155. symbols: symbols,
  110156. completionKind: completionKind,
  110157. isInSnippetScope: isInSnippetScope,
  110158. propertyAccessToConvert: propertyAccessToConvert,
  110159. isNewIdentifierLocation: isNewIdentifierLocation,
  110160. location: location,
  110161. keywordFilters: keywordFilters,
  110162. literals: literals,
  110163. symbolToOriginInfoMap: symbolToOriginInfoMap,
  110164. recommendedCompletion: recommendedCompletion,
  110165. previousToken: previousToken,
  110166. isJsxInitializer: isJsxInitializer,
  110167. insideJsDocTagTypeExpression: insideJsDocTagTypeExpression,
  110168. symbolToSortTextMap: symbolToSortTextMap,
  110169. isTypeOnlyLocation: isTypeOnly
  110170. };
  110171. function isTagWithTypeExpression(tag) {
  110172. switch (tag.kind) {
  110173. case 316 /* JSDocParameterTag */:
  110174. case 322 /* JSDocPropertyTag */:
  110175. case 317 /* JSDocReturnTag */:
  110176. case 319 /* JSDocTypeTag */:
  110177. case 321 /* JSDocTypedefTag */:
  110178. return true;
  110179. default:
  110180. return false;
  110181. }
  110182. }
  110183. function getTypeScriptMemberSymbols() {
  110184. // Right of dot member completion list
  110185. completionKind = 2 /* PropertyAccess */;
  110186. // Since this is qualified name check it's a type node location
  110187. var isImportType = ts.isLiteralImportTypeNode(node);
  110188. var isTypeLocation = insideJsDocTagTypeExpression
  110189. || (isImportType && !node.isTypeOf)
  110190. || ts.isPartOfTypeNode(node.parent)
  110191. || ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
  110192. var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node);
  110193. if (ts.isEntityName(node) || isImportType) {
  110194. var isNamespaceName = ts.isModuleDeclaration(node.parent);
  110195. if (isNamespaceName)
  110196. isNewIdentifierLocation = true;
  110197. var symbol = typeChecker.getSymbolAtLocation(node);
  110198. if (symbol) {
  110199. symbol = ts.skipAlias(symbol, typeChecker);
  110200. if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) {
  110201. // Extract module or enum members
  110202. var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined");
  110203. var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); };
  110204. var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); };
  110205. var isValidAccess = isNamespaceName
  110206. // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion.
  110207. ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); }
  110208. : isRhsOfImportDeclaration ?
  110209. // Any kind is allowed when dotting off namespace in internal import equals declaration
  110210. function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } :
  110211. isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1;
  110212. for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) {
  110213. var exportedSymbol = exportedSymbols_1[_i];
  110214. if (isValidAccess(exportedSymbol)) {
  110215. symbols.push(exportedSymbol);
  110216. }
  110217. }
  110218. // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
  110219. if (!isTypeLocation &&
  110220. symbol.declarations &&
  110221. symbol.declarations.some(function (d) { return d.kind !== 290 /* SourceFile */ && d.kind !== 249 /* ModuleDeclaration */ && d.kind !== 248 /* EnumDeclaration */; })) {
  110222. var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType();
  110223. var insertQuestionDot = false;
  110224. if (type.isNullableType()) {
  110225. var canCorrectToQuestionDot = isRightOfDot &&
  110226. !isRightOfQuestionDot &&
  110227. preferences.includeAutomaticOptionalChainCompletions !== false;
  110228. if (canCorrectToQuestionDot || isRightOfQuestionDot) {
  110229. type = type.getNonNullableType();
  110230. if (canCorrectToQuestionDot) {
  110231. insertQuestionDot = true;
  110232. }
  110233. }
  110234. }
  110235. addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
  110236. }
  110237. return;
  110238. }
  110239. }
  110240. }
  110241. if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) {
  110242. var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta";
  110243. symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion)));
  110244. return;
  110245. }
  110246. if (!isTypeLocation) {
  110247. var type = typeChecker.getTypeAtLocation(node).getNonOptionalType();
  110248. var insertQuestionDot = false;
  110249. if (type.isNullableType()) {
  110250. var canCorrectToQuestionDot = isRightOfDot &&
  110251. !isRightOfQuestionDot &&
  110252. preferences.includeAutomaticOptionalChainCompletions !== false;
  110253. if (canCorrectToQuestionDot || isRightOfQuestionDot) {
  110254. type = type.getNonNullableType();
  110255. if (canCorrectToQuestionDot) {
  110256. insertQuestionDot = true;
  110257. }
  110258. }
  110259. }
  110260. addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
  110261. }
  110262. }
  110263. function addTypeProperties(type, insertAwait, insertQuestionDot) {
  110264. isNewIdentifierLocation = !!type.getStringIndexType();
  110265. if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) {
  110266. isNewIdentifierLocation = true;
  110267. }
  110268. var propertyAccess = node.kind === 188 /* ImportType */ ? node : node.parent;
  110269. if (isUncheckedFile) {
  110270. // In javascript files, for union types, we don't just get the members that
  110271. // the individual types have in common, we also include all the members that
  110272. // each individual type has. This is because we're going to add all identifiers
  110273. // anyways. So we might as well elevate the members that were at least part
  110274. // of the individual types to a higher status since we know what they are.
  110275. symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker));
  110276. }
  110277. else {
  110278. for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) {
  110279. var symbol = _a[_i];
  110280. if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
  110281. addPropertySymbol(symbol, /*insertAwait*/ false, insertQuestionDot);
  110282. }
  110283. }
  110284. }
  110285. if (insertAwait && preferences.includeCompletionsWithInsertText) {
  110286. var promiseType = typeChecker.getPromisedTypeOfPromise(type);
  110287. if (promiseType) {
  110288. for (var _b = 0, _c = promiseType.getApparentProperties(); _b < _c.length; _b++) {
  110289. var symbol = _c[_b];
  110290. if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) {
  110291. addPropertySymbol(symbol, /* insertAwait */ true, insertQuestionDot);
  110292. }
  110293. }
  110294. }
  110295. }
  110296. }
  110297. function addPropertySymbol(symbol, insertAwait, insertQuestionDot) {
  110298. // For a computed property with an accessible name like `Symbol.iterator`,
  110299. // we'll add a completion for the *name* `Symbol` instead of for the property.
  110300. // If this is e.g. [Symbol.iterator], add a completion for `Symbol`.
  110301. var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); });
  110302. if (computedPropertyName) {
  110303. var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`.
  110304. var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
  110305. // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`.
  110306. var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
  110307. if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) {
  110308. symbols.push(firstAccessibleSymbol);
  110309. var moduleSymbol = firstAccessibleSymbol.parent;
  110310. symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] =
  110311. !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)
  110312. ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }
  110313. : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false };
  110314. }
  110315. else if (preferences.includeCompletionsWithInsertText) {
  110316. addSymbolOriginInfo(symbol);
  110317. symbols.push(symbol);
  110318. }
  110319. }
  110320. else {
  110321. addSymbolOriginInfo(symbol);
  110322. symbols.push(symbol);
  110323. }
  110324. function addSymbolOriginInfo(symbol) {
  110325. if (preferences.includeCompletionsWithInsertText) {
  110326. if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) {
  110327. symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) };
  110328. }
  110329. else if (insertQuestionDot) {
  110330. symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ };
  110331. }
  110332. }
  110333. }
  110334. function getNullableSymbolOriginInfoKind(kind) {
  110335. return insertQuestionDot ? kind | 16 /* Nullable */ : kind;
  110336. }
  110337. }
  110338. /** Given 'a.b.c', returns 'a'. */
  110339. function getLeftMostName(e) {
  110340. return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined;
  110341. }
  110342. function tryGetGlobalSymbols() {
  110343. var result = tryGetObjectLikeCompletionSymbols()
  110344. || tryGetImportOrExportClauseCompletionSymbols()
  110345. || tryGetConstructorCompletion()
  110346. || tryGetClassLikeCompletionSymbols()
  110347. || tryGetJsxCompletionSymbols()
  110348. || (getGlobalCompletions(), 1 /* Success */);
  110349. return result === 1 /* Success */;
  110350. }
  110351. function tryGetConstructorCompletion() {
  110352. if (!tryGetConstructorLikeCompletionContainer(contextToken))
  110353. return 0 /* Continue */;
  110354. // no members, only keywords
  110355. completionKind = 5 /* None */;
  110356. // Declaring new property/method/accessor
  110357. isNewIdentifierLocation = true;
  110358. // Has keywords for constructor parameter
  110359. keywordFilters = 4 /* ConstructorParameterKeywords */;
  110360. return 1 /* Success */;
  110361. }
  110362. function tryGetJsxCompletionSymbols() {
  110363. var jsxContainer = tryGetContainingJsxElement(contextToken);
  110364. // Cursor is inside a JSX self-closing element or opening element
  110365. var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes);
  110366. if (!attrsType)
  110367. return 0 /* Continue */;
  110368. var completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */);
  110369. symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties);
  110370. setSortTextToOptionalMember();
  110371. completionKind = 3 /* MemberLike */;
  110372. isNewIdentifierLocation = false;
  110373. return 1 /* Success */;
  110374. }
  110375. function getGlobalCompletions() {
  110376. keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
  110377. // Get all entities in the current scope.
  110378. completionKind = 1 /* Global */;
  110379. isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
  110380. if (previousToken !== contextToken) {
  110381. ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
  110382. }
  110383. // We need to find the node that will give us an appropriate scope to begin
  110384. // aggregating completion candidates. This is achieved in 'getScopeNode'
  110385. // by finding the first node that encompasses a position, accounting for whether a node
  110386. // is "complete" to decide whether a position belongs to the node.
  110387. //
  110388. // However, at the end of an identifier, we are interested in the scope of the identifier
  110389. // itself, but fall outside of the identifier. For instance:
  110390. //
  110391. // xyz => x$
  110392. //
  110393. // the cursor is outside of both the 'x' and the arrow function 'xyz => x',
  110394. // so 'xyz' is not returned in our results.
  110395. //
  110396. // We define 'adjustedPosition' so that we may appropriately account for
  110397. // being at the end of an identifier. The intention is that if requesting completion
  110398. // at the end of an identifier, it should be effectively equivalent to requesting completion
  110399. // anywhere inside/at the beginning of the identifier. So in the previous case, the
  110400. // 'adjustedPosition' will work as if requesting completion in the following:
  110401. //
  110402. // xyz => $x
  110403. //
  110404. // If previousToken !== contextToken, then
  110405. // - 'contextToken' was adjusted to the token prior to 'previousToken'
  110406. // because we were at the end of an identifier.
  110407. // - 'previousToken' is defined.
  110408. var adjustedPosition = previousToken !== contextToken ?
  110409. previousToken.getStart() :
  110410. position;
  110411. var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
  110412. isInSnippetScope = isSnippetScope(scopeNode);
  110413. var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
  110414. symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
  110415. for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
  110416. var symbol = symbols_2[_i];
  110417. if (!typeChecker.isArgumentsSymbol(symbol) &&
  110418. !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) {
  110419. symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
  110420. }
  110421. }
  110422. // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
  110423. if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) {
  110424. var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
  110425. if (thisType) {
  110426. for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) {
  110427. var symbol = _b[_a];
  110428. symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ };
  110429. symbols.push(symbol);
  110430. symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers;
  110431. }
  110432. }
  110433. }
  110434. if (shouldOfferImportCompletions()) {
  110435. var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : "";
  110436. var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host);
  110437. if (!detailsEntryId && importSuggestionsCache) {
  110438. importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion());
  110439. }
  110440. autoImportSuggestions.forEach(function (_a) {
  110441. var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin;
  110442. if (detailsEntryId) {
  110443. if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) {
  110444. return;
  110445. }
  110446. }
  110447. else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) {
  110448. return;
  110449. }
  110450. var symbolId = ts.getSymbolId(symbol);
  110451. symbols.push(symbol);
  110452. symbolToOriginInfoMap[symbolId] = origin;
  110453. symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions;
  110454. });
  110455. }
  110456. filterGlobalCompletion(symbols);
  110457. }
  110458. function shouldOfferImportCompletions() {
  110459. // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs)
  110460. if (!preferences.includeCompletionsForModuleExports)
  110461. return false;
  110462. // If already using ES6 modules, OK to continue using them.
  110463. if (sourceFile.externalModuleIndicator)
  110464. return true;
  110465. // If already using commonjs, don't introduce ES6.
  110466. if (sourceFile.commonJsModuleIndicator)
  110467. return false;
  110468. // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK.
  110469. if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))
  110470. return true;
  110471. // If some file is using ES6 modules, assume that it's OK to add more.
  110472. return ts.programContainsEs6Modules(program);
  110473. }
  110474. function isSnippetScope(scopeNode) {
  110475. switch (scopeNode.kind) {
  110476. case 290 /* SourceFile */:
  110477. case 211 /* TemplateExpression */:
  110478. case 276 /* JsxExpression */:
  110479. case 223 /* Block */:
  110480. return true;
  110481. default:
  110482. return ts.isStatement(scopeNode);
  110483. }
  110484. }
  110485. function filterGlobalCompletion(symbols) {
  110486. var isTypeOnly = isTypeOnlyCompletion();
  110487. if (isTypeOnly) {
  110488. keywordFilters = isTypeAssertion()
  110489. ? 6 /* TypeAssertionKeywords */
  110490. : 7 /* TypeKeywords */;
  110491. }
  110492. ts.filterMutate(symbols, function (symbol) {
  110493. if (!ts.isSourceFile(location)) {
  110494. // export = /**/ here we want to get all meanings, so any symbol is ok
  110495. if (ts.isExportAssignment(location.parent)) {
  110496. return true;
  110497. }
  110498. symbol = ts.skipAlias(symbol, typeChecker);
  110499. // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace)
  110500. if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) {
  110501. return !!(symbol.flags & 1920 /* Namespace */);
  110502. }
  110503. if (isTypeOnly) {
  110504. // It's a type, but you can reach it by namespace.type as well
  110505. return symbolCanBeReferencedAtTypeLocation(symbol);
  110506. }
  110507. }
  110508. // expressions are value space (which includes the value namespaces)
  110509. return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */);
  110510. });
  110511. }
  110512. function isTypeAssertion() {
  110513. return ts.isAssertionExpression(contextToken.parent);
  110514. }
  110515. function isTypeOnlyCompletion() {
  110516. return insideJsDocTagTypeExpression
  110517. || !isContextTokenValueLocation(contextToken) &&
  110518. (ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)
  110519. || ts.isPartOfTypeNode(location)
  110520. || isContextTokenTypeLocation(contextToken));
  110521. }
  110522. function isContextTokenValueLocation(contextToken) {
  110523. return contextToken &&
  110524. contextToken.kind === 108 /* TypeOfKeyword */ &&
  110525. (contextToken.parent.kind === 172 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent));
  110526. }
  110527. function isContextTokenTypeLocation(contextToken) {
  110528. if (contextToken) {
  110529. var parentKind = contextToken.parent.kind;
  110530. switch (contextToken.kind) {
  110531. case 58 /* ColonToken */:
  110532. return parentKind === 159 /* PropertyDeclaration */ ||
  110533. parentKind === 158 /* PropertySignature */ ||
  110534. parentKind === 156 /* Parameter */ ||
  110535. parentKind === 242 /* VariableDeclaration */ ||
  110536. ts.isFunctionLikeKind(parentKind);
  110537. case 62 /* EqualsToken */:
  110538. return parentKind === 247 /* TypeAliasDeclaration */;
  110539. case 123 /* AsKeyword */:
  110540. return parentKind === 217 /* AsExpression */;
  110541. case 29 /* LessThanToken */:
  110542. return parentKind === 169 /* TypeReference */ ||
  110543. parentKind === 199 /* TypeAssertionExpression */;
  110544. case 90 /* ExtendsKeyword */:
  110545. return parentKind === 155 /* TypeParameter */;
  110546. }
  110547. }
  110548. return false;
  110549. }
  110550. /** True if symbol is a type or a module containing at least one type. */
  110551. function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) {
  110552. if (seenModules === void 0) { seenModules = ts.createMap(); }
  110553. var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker);
  110554. return !!(sym.flags & 788968 /* Type */) ||
  110555. !!(sym.flags & 1536 /* Module */) &&
  110556. ts.addToSeen(seenModules, ts.getSymbolId(sym)) &&
  110557. typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); });
  110558. }
  110559. /**
  110560. * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates"
  110561. * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but
  110562. * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out,
  110563. * if and only if the the first can be imported (it may be excluded due to package.json filtering in
  110564. * `codefix.forEachExternalModuleToImportFrom`).
  110565. *
  110566. * Example. Imagine a chain of node_modules re-exporting one original symbol:
  110567. *
  110568. * ```js
  110569. * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js
  110570. * +-----------------------+ +--------------------------+ +--------------------------+
  110571. * | | | | | |
  110572. * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; |
  110573. * | | | | | |
  110574. * +-----------------------+ +--------------------------+ +--------------------------+
  110575. * ```
  110576. *
  110577. * Also imagine three buckets, which we’ll reference soon:
  110578. *
  110579. * ```md
  110580. * | | | | | |
  110581. * | **Bucket A** | | **Bucket B** | | **Bucket C** |
  110582. * | Symbols to | | Aliases to symbols | | Symbols to return |
  110583. * | definitely | | in Buckets A or C | | if nothing better |
  110584. * | return | | (don’t return these) | | comes along |
  110585. * |__________________| |______________________| |___________________|
  110586. * ```
  110587. *
  110588. * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it
  110589. * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not
  110590. * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we
  110591. * may not be sure whether or not it should go in the list. So, we’ll take the following steps:
  110592. *
  110593. * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is
  110594. * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B
  110595. * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C.
  110596. * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'.
  110597. * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z'
  110598. * should never be returned in the final list, so put it in Bucket B.
  110599. * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so
  110600. * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out.
  110601. * Put this symbol in Bucket A.
  110602. * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t
  110603. * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move
  110604. * everything from Bucket C to Bucket A.
  110605. */
  110606. function getSymbolsFromOtherSourceFileExports(target, host) {
  110607. var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined);
  110608. if (cached) {
  110609. log("getSymbolsFromOtherSourceFileExports: Using cached list");
  110610. return cached;
  110611. }
  110612. var startTime = ts.timestamp();
  110613. log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : ""));
  110614. var seenResolvedModules = ts.createMap();
  110615. /** Bucket B */
  110616. var aliasesToAlreadyIncludedSymbols = ts.createMap();
  110617. /** Bucket C */
  110618. var aliasesToReturnIfOriginalsAreMissing = ts.createMap();
  110619. /** Bucket A */
  110620. var results = [];
  110621. /** Ids present in `results` for faster lookup */
  110622. var resultSymbolIds = ts.createMap();
  110623. ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, function (moduleSymbol) {
  110624. // Perf -- ignore other modules if this is a request for details
  110625. if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) {
  110626. return;
  110627. }
  110628. var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol);
  110629. // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one.
  110630. if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) {
  110631. return;
  110632. }
  110633. // Don't add another completion for `export =` of a symbol that's already global.
  110634. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`.
  110635. if (resolvedModuleSymbol !== moduleSymbol &&
  110636. ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) {
  110637. pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true);
  110638. }
  110639. for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) {
  110640. var symbol = _a[_i];
  110641. // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion.
  110642. if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) {
  110643. continue;
  110644. }
  110645. var symbolId = ts.getSymbolId(symbol).toString();
  110646. // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols.
  110647. var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol;
  110648. // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check).
  110649. if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) {
  110650. // Walk the export chain back one module (step 1 or 2 in diagrammed example).
  110651. // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that.
  110652. var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol);
  110653. if (!nearestExportSymbol)
  110654. continue;
  110655. var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString();
  110656. var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId);
  110657. if (!symbolHasBeenSeen) {
  110658. aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol });
  110659. aliasesToAlreadyIncludedSymbols.set(symbolId, true);
  110660. }
  110661. else {
  110662. // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here
  110663. // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id.
  110664. ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId);
  110665. }
  110666. }
  110667. else {
  110668. // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example)
  110669. aliasesToReturnIfOriginalsAreMissing.delete(symbolId);
  110670. pushSymbol(symbol, moduleSymbol);
  110671. }
  110672. }
  110673. });
  110674. // By this point, any potential duplicates that were actually duplicates have been
  110675. // removed, so the rest need to be added. (Step 4 in diagrammed example)
  110676. aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) {
  110677. var alias = _a.alias, moduleSymbol = _a.moduleSymbol;
  110678. return pushSymbol(alias, moduleSymbol);
  110679. });
  110680. log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime));
  110681. return results;
  110682. function pushSymbol(symbol, moduleSymbol, skipFilter) {
  110683. if (skipFilter === void 0) { skipFilter = false; }
  110684. var isDefaultExport = symbol.escapedName === "default" /* Default */;
  110685. if (isDefaultExport) {
  110686. symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol;
  110687. }
  110688. if (typeChecker.isUndefinedSymbol(symbol)) {
  110689. return;
  110690. }
  110691. ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol));
  110692. var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport };
  110693. results.push({
  110694. symbol: symbol,
  110695. symbolName: getSymbolName(symbol, origin, target),
  110696. origin: origin,
  110697. skipFilter: skipFilter,
  110698. });
  110699. }
  110700. }
  110701. function getNearestExportSymbol(fromSymbol) {
  110702. return findAlias(typeChecker, fromSymbol, function (alias) {
  110703. return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; });
  110704. });
  110705. }
  110706. /**
  110707. * True if you could remove some characters in `a` to get `b`.
  110708. * E.g., true for "abcdef" and "bdf".
  110709. * But not true for "abcdef" and "dbf".
  110710. */
  110711. function stringContainsCharactersInOrder(str, characters) {
  110712. if (characters.length === 0) {
  110713. return true;
  110714. }
  110715. var characterIndex = 0;
  110716. for (var strIndex = 0; strIndex < str.length; strIndex++) {
  110717. if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) {
  110718. characterIndex++;
  110719. if (characterIndex === characters.length) {
  110720. return true;
  110721. }
  110722. }
  110723. }
  110724. // Did not find all characters
  110725. return false;
  110726. }
  110727. /**
  110728. * Finds the first node that "embraces" the position, so that one may
  110729. * accurately aggregate locals from the closest containing scope.
  110730. */
  110731. function getScopeNode(initialToken, position, sourceFile) {
  110732. var scope = initialToken;
  110733. while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {
  110734. scope = scope.parent;
  110735. }
  110736. return scope;
  110737. }
  110738. function isCompletionListBlocker(contextToken) {
  110739. var start = ts.timestamp();
  110740. var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
  110741. isSolelyIdentifierDefinitionLocation(contextToken) ||
  110742. isDotOfNumericLiteral(contextToken) ||
  110743. isInJsxText(contextToken);
  110744. log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start));
  110745. return result;
  110746. }
  110747. function isInJsxText(contextToken) {
  110748. if (contextToken.kind === 11 /* JsxText */) {
  110749. return true;
  110750. }
  110751. if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) {
  110752. if (contextToken.parent.kind === 268 /* JsxOpeningElement */) {
  110753. // Two possibilities:
  110754. // 1. <div>/**/
  110755. // - contextToken: GreaterThanToken (before cursor)
  110756. // - location: JSXElement
  110757. // - different parents (JSXOpeningElement, JSXElement)
  110758. // 2. <Component<string> /**/>
  110759. // - contextToken: GreaterThanToken (before cursor)
  110760. // - location: GreaterThanToken (after cursor)
  110761. // - same parent (JSXOpeningElement)
  110762. return location.parent.kind !== 268 /* JsxOpeningElement */;
  110763. }
  110764. if (contextToken.parent.kind === 269 /* JsxClosingElement */ || contextToken.parent.kind === 267 /* JsxSelfClosingElement */) {
  110765. return !!contextToken.parent.parent && contextToken.parent.parent.kind === 266 /* JsxElement */;
  110766. }
  110767. }
  110768. return false;
  110769. }
  110770. function isNewIdentifierDefinitionLocation(previousToken) {
  110771. if (previousToken) {
  110772. var containingNodeKind = previousToken.parent.kind;
  110773. // Previous token may have been a keyword that was converted to an identifier.
  110774. switch (keywordForNode(previousToken)) {
  110775. case 27 /* CommaToken */:
  110776. return containingNodeKind === 196 /* CallExpression */ // func( a, |
  110777. || containingNodeKind === 162 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
  110778. || containingNodeKind === 197 /* NewExpression */ // new C(a, |
  110779. || containingNodeKind === 192 /* ArrayLiteralExpression */ // [a, |
  110780. || containingNodeKind === 209 /* BinaryExpression */ // const x = (a, |
  110781. || containingNodeKind === 170 /* FunctionType */; // var x: (s: string, list|
  110782. case 20 /* OpenParenToken */:
  110783. return containingNodeKind === 196 /* CallExpression */ // func( |
  110784. || containingNodeKind === 162 /* Constructor */ // constructor( |
  110785. || containingNodeKind === 197 /* NewExpression */ // new C(a|
  110786. || containingNodeKind === 200 /* ParenthesizedExpression */ // const x = (a|
  110787. || containingNodeKind === 182 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
  110788. case 22 /* OpenBracketToken */:
  110789. return containingNodeKind === 192 /* ArrayLiteralExpression */ // [ |
  110790. || containingNodeKind === 167 /* IndexSignature */ // [ | : string ]
  110791. || containingNodeKind === 154 /* ComputedPropertyName */; // [ | /* this can become an index signature */
  110792. case 135 /* ModuleKeyword */: // module |
  110793. case 136 /* NamespaceKeyword */: // namespace |
  110794. return true;
  110795. case 24 /* DotToken */:
  110796. return containingNodeKind === 249 /* ModuleDeclaration */; // module A.|
  110797. case 18 /* OpenBraceToken */:
  110798. return containingNodeKind === 245 /* ClassDeclaration */; // class A{ |
  110799. case 62 /* EqualsToken */:
  110800. return containingNodeKind === 242 /* VariableDeclaration */ // const x = a|
  110801. || containingNodeKind === 209 /* BinaryExpression */; // x = a|
  110802. case 15 /* TemplateHead */:
  110803. return containingNodeKind === 211 /* TemplateExpression */; // `aa ${|
  110804. case 16 /* TemplateMiddle */:
  110805. return containingNodeKind === 221 /* TemplateSpan */; // `aa ${10} dd ${|
  110806. case 119 /* PublicKeyword */:
  110807. case 117 /* PrivateKeyword */:
  110808. case 118 /* ProtectedKeyword */:
  110809. return containingNodeKind === 159 /* PropertyDeclaration */; // class A{ public |
  110810. }
  110811. }
  110812. return false;
  110813. }
  110814. function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) {
  110815. // To be "in" one of these literals, the position has to be:
  110816. // 1. entirely within the token text.
  110817. // 2. at the end position of an unterminated token.
  110818. // 3. at the end of a regular expression (due to trailing flags like '/foo/g').
  110819. return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) ||
  110820. position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken)));
  110821. }
  110822. /**
  110823. * Aggregates relevant symbols for completion in object literals and object binding patterns.
  110824. * Relevant symbols are stored in the captured 'symbols' variable.
  110825. *
  110826. * @returns true if 'symbols' was successfully populated; false otherwise.
  110827. */
  110828. function tryGetObjectLikeCompletionSymbols() {
  110829. var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
  110830. if (!objectLikeContainer)
  110831. return 0 /* Continue */;
  110832. // We're looking up possible property names from contextual/inferred/declared type.
  110833. completionKind = 0 /* ObjectPropertyDeclaration */;
  110834. var typeMembers;
  110835. var existingMembers;
  110836. if (objectLikeContainer.kind === 193 /* ObjectLiteralExpression */) {
  110837. var instantiatedType = typeChecker.getContextualType(objectLikeContainer);
  110838. var completionsType = instantiatedType && typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */);
  110839. if (!instantiatedType || !completionsType)
  110840. return 2 /* Fail */;
  110841. isNewIdentifierLocation = ts.hasIndexSignature(instantiatedType || completionsType);
  110842. typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker);
  110843. existingMembers = objectLikeContainer.properties;
  110844. }
  110845. else {
  110846. ts.Debug.assert(objectLikeContainer.kind === 189 /* ObjectBindingPattern */);
  110847. // We are *only* completing on properties from the type being destructured.
  110848. isNewIdentifierLocation = false;
  110849. var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
  110850. if (!ts.isVariableLike(rootDeclaration))
  110851. return ts.Debug.fail("Root declaration is not variable-like.");
  110852. // We don't want to complete using the type acquired by the shape
  110853. // of the binding pattern; we are only interested in types acquired
  110854. // through type declaration or inference.
  110855. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed -
  110856. // type of parameter will flow in from the contextual type of the function
  110857. var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 232 /* ForOfStatement */;
  110858. if (!canGetType && rootDeclaration.kind === 156 /* Parameter */) {
  110859. if (ts.isExpression(rootDeclaration.parent)) {
  110860. canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
  110861. }
  110862. else if (rootDeclaration.parent.kind === 161 /* MethodDeclaration */ || rootDeclaration.parent.kind === 164 /* SetAccessor */) {
  110863. canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
  110864. }
  110865. }
  110866. if (canGetType) {
  110867. var typeForObject_1 = typeChecker.getTypeAtLocation(objectLikeContainer);
  110868. if (!typeForObject_1)
  110869. return 2 /* Fail */;
  110870. // In a binding pattern, get only known properties (unless in the same scope).
  110871. // Everywhere else we will get all possible properties.
  110872. var containerClass_1 = ts.getContainingClass(objectLikeContainer);
  110873. typeMembers = typeChecker.getPropertiesOfType(typeForObject_1).filter(function (symbol) {
  110874. // either public
  110875. return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */)
  110876. // or we're in it
  110877. || containerClass_1 && ts.contains(typeForObject_1.symbol.declarations, containerClass_1);
  110878. });
  110879. existingMembers = objectLikeContainer.elements;
  110880. }
  110881. }
  110882. if (typeMembers && typeMembers.length > 0) {
  110883. // Add filtered items to the completion list
  110884. symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers));
  110885. }
  110886. setSortTextToOptionalMember();
  110887. return 1 /* Success */;
  110888. }
  110889. /**
  110890. * Aggregates relevant symbols for completion in import clauses and export clauses
  110891. * whose declarations have a module specifier; for instance, symbols will be aggregated for
  110892. *
  110893. * import { | } from "moduleName";
  110894. * export { a as foo, | } from "moduleName";
  110895. *
  110896. * but not for
  110897. *
  110898. * export { | };
  110899. *
  110900. * Relevant symbols are stored in the captured 'symbols' variable.
  110901. *
  110902. * @returns true if 'symbols' was successfully populated; false otherwise.
  110903. */
  110904. function tryGetImportOrExportClauseCompletionSymbols() {
  110905. // `import { |` or `import { a as 0, | }`
  110906. var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */)
  110907. ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined;
  110908. if (!namedImportsOrExports)
  110909. return 0 /* Continue */;
  110910. // cursor is in an import clause
  110911. // try to show exported member for imported module
  110912. var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier;
  110913. var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217
  110914. if (!moduleSpecifierSymbol)
  110915. return 2 /* Fail */;
  110916. completionKind = 3 /* MemberLike */;
  110917. isNewIdentifierLocation = false;
  110918. var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
  110919. var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; });
  110920. symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); });
  110921. return 1 /* Success */;
  110922. }
  110923. /**
  110924. * Aggregates relevant symbols for completion in class declaration
  110925. * Relevant symbols are stored in the captured 'symbols' variable.
  110926. */
  110927. function tryGetClassLikeCompletionSymbols() {
  110928. var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position);
  110929. if (!decl)
  110930. return 0 /* Continue */;
  110931. // We're looking up possible property names from parent type.
  110932. completionKind = 3 /* MemberLike */;
  110933. // Declaring new property/method/accessor
  110934. isNewIdentifierLocation = true;
  110935. keywordFilters = contextToken.kind === 41 /* AsteriskToken */ ? 0 /* None */ :
  110936. ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
  110937. // If you're in an interface you don't want to repeat things from super-interface. So just stop here.
  110938. if (!ts.isClassLike(decl))
  110939. return 1 /* Success */;
  110940. var classElement = contextToken.kind === 26 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent;
  110941. var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */;
  110942. // If this is context token is not something we are editing now, consider if this would lead to be modifier
  110943. if (contextToken.kind === 75 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) {
  110944. switch (contextToken.getText()) {
  110945. case "private":
  110946. classElementModifierFlags = classElementModifierFlags | 8 /* Private */;
  110947. break;
  110948. case "static":
  110949. classElementModifierFlags = classElementModifierFlags | 32 /* Static */;
  110950. break;
  110951. }
  110952. }
  110953. // No member list for private methods
  110954. if (!(classElementModifierFlags & 8 /* Private */)) {
  110955. // List of property symbols of base type that are not private and already implemented
  110956. var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) {
  110957. var type = typeChecker.getTypeAtLocation(baseTypeNode);
  110958. return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type);
  110959. });
  110960. symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags);
  110961. }
  110962. return 1 /* Success */;
  110963. }
  110964. /**
  110965. * Returns the immediate owning object literal or binding pattern of a context token,
  110966. * on the condition that one exists and that the context implies completion should be given.
  110967. */
  110968. function tryGetObjectLikeCompletionContainer(contextToken) {
  110969. if (contextToken) {
  110970. var parent = contextToken.parent;
  110971. switch (contextToken.kind) {
  110972. case 18 /* OpenBraceToken */: // const x = { |
  110973. case 27 /* CommaToken */: // const x = { a: 0, |
  110974. if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
  110975. return parent;
  110976. }
  110977. break;
  110978. case 41 /* AsteriskToken */:
  110979. return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined;
  110980. case 75 /* Identifier */:
  110981. return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent)
  110982. ? contextToken.parent.parent : undefined;
  110983. }
  110984. }
  110985. return undefined;
  110986. }
  110987. function isConstructorParameterCompletion(node) {
  110988. return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent)
  110989. && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node));
  110990. }
  110991. /**
  110992. * Returns the immediate owning class declaration of a context token,
  110993. * on the condition that one exists and that the context implies completion should be given.
  110994. */
  110995. function tryGetConstructorLikeCompletionContainer(contextToken) {
  110996. if (contextToken) {
  110997. var parent = contextToken.parent;
  110998. switch (contextToken.kind) {
  110999. case 20 /* OpenParenToken */:
  111000. case 27 /* CommaToken */:
  111001. return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined;
  111002. default:
  111003. if (isConstructorParameterCompletion(contextToken)) {
  111004. return parent.parent;
  111005. }
  111006. }
  111007. }
  111008. return undefined;
  111009. }
  111010. function tryGetFunctionLikeBodyCompletionContainer(contextToken) {
  111011. if (contextToken) {
  111012. var prev_1;
  111013. var container = ts.findAncestor(contextToken.parent, function (node) {
  111014. if (ts.isClassLike(node)) {
  111015. return "quit";
  111016. }
  111017. if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) {
  111018. return true;
  111019. }
  111020. prev_1 = node;
  111021. return false;
  111022. });
  111023. return container && container;
  111024. }
  111025. }
  111026. function tryGetContainingJsxElement(contextToken) {
  111027. if (contextToken) {
  111028. var parent = contextToken.parent;
  111029. switch (contextToken.kind) {
  111030. case 31 /* GreaterThanToken */: // End of a type argument list
  111031. case 30 /* LessThanSlashToken */:
  111032. case 43 /* SlashToken */:
  111033. case 75 /* Identifier */:
  111034. case 194 /* PropertyAccessExpression */:
  111035. case 274 /* JsxAttributes */:
  111036. case 273 /* JsxAttribute */:
  111037. case 275 /* JsxSpreadAttribute */:
  111038. if (parent && (parent.kind === 267 /* JsxSelfClosingElement */ || parent.kind === 268 /* JsxOpeningElement */)) {
  111039. if (contextToken.kind === 31 /* GreaterThanToken */) {
  111040. var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
  111041. if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */))
  111042. break;
  111043. }
  111044. return parent;
  111045. }
  111046. else if (parent.kind === 273 /* JsxAttribute */) {
  111047. // Currently we parse JsxOpeningLikeElement as:
  111048. // JsxOpeningLikeElement
  111049. // attributes: JsxAttributes
  111050. // properties: NodeArray<JsxAttributeLike>
  111051. return parent.parent.parent;
  111052. }
  111053. break;
  111054. // The context token is the closing } or " of an attribute, which means
  111055. // its parent is a JsxExpression, whose parent is a JsxAttribute,
  111056. // whose parent is a JsxOpeningLikeElement
  111057. case 10 /* StringLiteral */:
  111058. if (parent && ((parent.kind === 273 /* JsxAttribute */) || (parent.kind === 275 /* JsxSpreadAttribute */))) {
  111059. // Currently we parse JsxOpeningLikeElement as:
  111060. // JsxOpeningLikeElement
  111061. // attributes: JsxAttributes
  111062. // properties: NodeArray<JsxAttributeLike>
  111063. return parent.parent.parent;
  111064. }
  111065. break;
  111066. case 19 /* CloseBraceToken */:
  111067. if (parent &&
  111068. parent.kind === 276 /* JsxExpression */ &&
  111069. parent.parent && parent.parent.kind === 273 /* JsxAttribute */) {
  111070. // Currently we parse JsxOpeningLikeElement as:
  111071. // JsxOpeningLikeElement
  111072. // attributes: JsxAttributes
  111073. // properties: NodeArray<JsxAttributeLike>
  111074. // each JsxAttribute can have initializer as JsxExpression
  111075. return parent.parent.parent.parent;
  111076. }
  111077. if (parent && parent.kind === 275 /* JsxSpreadAttribute */) {
  111078. // Currently we parse JsxOpeningLikeElement as:
  111079. // JsxOpeningLikeElement
  111080. // attributes: JsxAttributes
  111081. // properties: NodeArray<JsxAttributeLike>
  111082. return parent.parent.parent;
  111083. }
  111084. break;
  111085. }
  111086. }
  111087. return undefined;
  111088. }
  111089. /**
  111090. * @returns true if we are certain that the currently edited location must define a new location; false otherwise.
  111091. */
  111092. function isSolelyIdentifierDefinitionLocation(contextToken) {
  111093. var parent = contextToken.parent;
  111094. var containingNodeKind = parent.kind;
  111095. switch (contextToken.kind) {
  111096. case 27 /* CommaToken */:
  111097. return containingNodeKind === 242 /* VariableDeclaration */ ||
  111098. isVariableDeclarationListButNotTypeArgument(contextToken) ||
  111099. containingNodeKind === 225 /* VariableStatement */ ||
  111100. containingNodeKind === 248 /* EnumDeclaration */ || // enum a { foo, |
  111101. isFunctionLikeButNotConstructor(containingNodeKind) ||
  111102. containingNodeKind === 246 /* InterfaceDeclaration */ || // interface A<T, |
  111103. containingNodeKind === 190 /* ArrayBindingPattern */ || // var [x, y|
  111104. containingNodeKind === 247 /* TypeAliasDeclaration */ || // type Map, K, |
  111105. // class A<T, |
  111106. // var C = class D<T, |
  111107. (ts.isClassLike(parent) &&
  111108. !!parent.typeParameters &&
  111109. parent.typeParameters.end >= contextToken.pos);
  111110. case 24 /* DotToken */:
  111111. return containingNodeKind === 190 /* ArrayBindingPattern */; // var [.|
  111112. case 58 /* ColonToken */:
  111113. return containingNodeKind === 191 /* BindingElement */; // var {x :html|
  111114. case 22 /* OpenBracketToken */:
  111115. return containingNodeKind === 190 /* ArrayBindingPattern */; // var [x|
  111116. case 20 /* OpenParenToken */:
  111117. return containingNodeKind === 280 /* CatchClause */ ||
  111118. isFunctionLikeButNotConstructor(containingNodeKind);
  111119. case 18 /* OpenBraceToken */:
  111120. return containingNodeKind === 248 /* EnumDeclaration */; // enum a { |
  111121. case 29 /* LessThanToken */:
  111122. return containingNodeKind === 245 /* ClassDeclaration */ || // class A< |
  111123. containingNodeKind === 214 /* ClassExpression */ || // var C = class D< |
  111124. containingNodeKind === 246 /* InterfaceDeclaration */ || // interface A< |
  111125. containingNodeKind === 247 /* TypeAliasDeclaration */ || // type List< |
  111126. ts.isFunctionLikeKind(containingNodeKind);
  111127. case 120 /* StaticKeyword */:
  111128. return containingNodeKind === 159 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent);
  111129. case 25 /* DotDotDotToken */:
  111130. return containingNodeKind === 156 /* Parameter */ ||
  111131. (!!parent.parent && parent.parent.kind === 190 /* ArrayBindingPattern */); // var [...z|
  111132. case 119 /* PublicKeyword */:
  111133. case 117 /* PrivateKeyword */:
  111134. case 118 /* ProtectedKeyword */:
  111135. return containingNodeKind === 156 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent);
  111136. case 123 /* AsKeyword */:
  111137. return containingNodeKind === 258 /* ImportSpecifier */ ||
  111138. containingNodeKind === 263 /* ExportSpecifier */ ||
  111139. containingNodeKind === 256 /* NamespaceImport */;
  111140. case 131 /* GetKeyword */:
  111141. case 142 /* SetKeyword */:
  111142. return !isFromObjectTypeDeclaration(contextToken);
  111143. case 80 /* ClassKeyword */:
  111144. case 88 /* EnumKeyword */:
  111145. case 114 /* InterfaceKeyword */:
  111146. case 94 /* FunctionKeyword */:
  111147. case 109 /* VarKeyword */:
  111148. case 96 /* ImportKeyword */:
  111149. case 115 /* LetKeyword */:
  111150. case 81 /* ConstKeyword */:
  111151. case 121 /* YieldKeyword */:
  111152. case 145 /* TypeKeyword */: // type htm|
  111153. return true;
  111154. case 41 /* AsteriskToken */:
  111155. return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent);
  111156. }
  111157. // If the previous token is keyword correspoding to class member completion keyword
  111158. // there will be completion available here
  111159. if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) {
  111160. return false;
  111161. }
  111162. if (isConstructorParameterCompletion(contextToken)) {
  111163. // constructor parameter completion is available only if
  111164. // - its modifier of the constructor parameter or
  111165. // - its name of the parameter and not being edited
  111166. // eg. constructor(a |<- this shouldnt show completion
  111167. if (!ts.isIdentifier(contextToken) ||
  111168. ts.isParameterPropertyModifier(keywordForNode(contextToken)) ||
  111169. isCurrentlyEditingNode(contextToken)) {
  111170. return false;
  111171. }
  111172. }
  111173. // Previous token may have been a keyword that was converted to an identifier.
  111174. switch (keywordForNode(contextToken)) {
  111175. case 122 /* AbstractKeyword */:
  111176. case 80 /* ClassKeyword */:
  111177. case 81 /* ConstKeyword */:
  111178. case 130 /* DeclareKeyword */:
  111179. case 88 /* EnumKeyword */:
  111180. case 94 /* FunctionKeyword */:
  111181. case 114 /* InterfaceKeyword */:
  111182. case 115 /* LetKeyword */:
  111183. case 117 /* PrivateKeyword */:
  111184. case 118 /* ProtectedKeyword */:
  111185. case 119 /* PublicKeyword */:
  111186. case 120 /* StaticKeyword */:
  111187. case 109 /* VarKeyword */:
  111188. case 121 /* YieldKeyword */:
  111189. return true;
  111190. case 126 /* AsyncKeyword */:
  111191. return ts.isPropertyDeclaration(contextToken.parent);
  111192. }
  111193. return ts.isDeclarationName(contextToken)
  111194. && !ts.isJsxAttribute(contextToken.parent)
  111195. // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`.
  111196. // If `contextToken !== previousToken`, this is `class C ex/**/`.
  111197. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end));
  111198. }
  111199. function isFunctionLikeButNotConstructor(kind) {
  111200. return ts.isFunctionLikeKind(kind) && kind !== 162 /* Constructor */;
  111201. }
  111202. function isDotOfNumericLiteral(contextToken) {
  111203. if (contextToken.kind === 8 /* NumericLiteral */) {
  111204. var text = contextToken.getFullText();
  111205. return text.charAt(text.length - 1) === ".";
  111206. }
  111207. return false;
  111208. }
  111209. function isVariableDeclarationListButNotTypeArgument(node) {
  111210. return node.parent.kind === 243 /* VariableDeclarationList */
  111211. && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker);
  111212. }
  111213. /**
  111214. * Filters out completion suggestions for named imports or exports.
  111215. *
  111216. * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
  111217. * do not occur at the current position and have not otherwise been typed.
  111218. */
  111219. function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
  111220. if (existingMembers.length === 0) {
  111221. return contextualMemberSymbols;
  111222. }
  111223. var membersDeclaredBySpreadAssignment = ts.createMap();
  111224. var existingMemberNames = ts.createUnderscoreEscapedMap();
  111225. for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
  111226. var m = existingMembers_1[_i];
  111227. // Ignore omitted expressions for missing members
  111228. if (m.kind !== 281 /* PropertyAssignment */ &&
  111229. m.kind !== 282 /* ShorthandPropertyAssignment */ &&
  111230. m.kind !== 191 /* BindingElement */ &&
  111231. m.kind !== 161 /* MethodDeclaration */ &&
  111232. m.kind !== 163 /* GetAccessor */ &&
  111233. m.kind !== 164 /* SetAccessor */ &&
  111234. m.kind !== 283 /* SpreadAssignment */) {
  111235. continue;
  111236. }
  111237. // If this is the current item we are editing right now, do not filter it out
  111238. if (isCurrentlyEditingNode(m)) {
  111239. continue;
  111240. }
  111241. var existingName = void 0;
  111242. if (ts.isSpreadAssignment(m)) {
  111243. setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment);
  111244. }
  111245. else if (ts.isBindingElement(m) && m.propertyName) {
  111246. // include only identifiers in completion list
  111247. if (m.propertyName.kind === 75 /* Identifier */) {
  111248. existingName = m.propertyName.escapedText;
  111249. }
  111250. }
  111251. else {
  111252. // TODO: Account for computed property name
  111253. // NOTE: if one only performs this step when m.name is an identifier,
  111254. // things like '__proto__' are not filtered out.
  111255. var name = ts.getNameOfDeclaration(m);
  111256. existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
  111257. }
  111258. existingMemberNames.set(existingName, true); // TODO: GH#18217
  111259. }
  111260. var filteredSymbols = contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); });
  111261. setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
  111262. return filteredSymbols;
  111263. }
  111264. function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) {
  111265. var expression = declaration.expression;
  111266. var symbol = typeChecker.getSymbolAtLocation(expression);
  111267. var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression);
  111268. var properties = type && type.properties;
  111269. if (properties) {
  111270. properties.forEach(function (property) {
  111271. membersDeclaredBySpreadAssignment.set(property.name, true);
  111272. });
  111273. }
  111274. }
  111275. // Set SortText to OptionalMember if it is an optinoal member
  111276. function setSortTextToOptionalMember() {
  111277. symbols.forEach(function (m) {
  111278. if (m.flags & 16777216 /* Optional */) {
  111279. symbolToSortTextMap[ts.getSymbolId(m)] = symbolToSortTextMap[ts.getSymbolId(m)] || SortText.OptionalMember;
  111280. }
  111281. });
  111282. }
  111283. // Set SortText to MemberDeclaredBySpreadAssignment if it is fulfilled by spread assignment
  111284. function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) {
  111285. if (membersDeclaredBySpreadAssignment.size === 0) {
  111286. return;
  111287. }
  111288. for (var _i = 0, contextualMemberSymbols_1 = contextualMemberSymbols; _i < contextualMemberSymbols_1.length; _i++) {
  111289. var contextualMemberSymbol = contextualMemberSymbols_1[_i];
  111290. if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) {
  111291. symbolToSortTextMap[ts.getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment;
  111292. }
  111293. }
  111294. }
  111295. /**
  111296. * Filters out completion suggestions for class elements.
  111297. *
  111298. * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags
  111299. */
  111300. function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) {
  111301. var existingMemberNames = ts.createUnderscoreEscapedMap();
  111302. for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) {
  111303. var m = existingMembers_2[_i];
  111304. // Ignore omitted expressions for missing members
  111305. if (m.kind !== 159 /* PropertyDeclaration */ &&
  111306. m.kind !== 161 /* MethodDeclaration */ &&
  111307. m.kind !== 163 /* GetAccessor */ &&
  111308. m.kind !== 164 /* SetAccessor */) {
  111309. continue;
  111310. }
  111311. // If this is the current item we are editing right now, do not filter it out
  111312. if (isCurrentlyEditingNode(m)) {
  111313. continue;
  111314. }
  111315. // Dont filter member even if the name matches if it is declared private in the list
  111316. if (ts.hasModifier(m, 8 /* Private */)) {
  111317. continue;
  111318. }
  111319. // do not filter it out if the static presence doesnt match
  111320. if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) {
  111321. continue;
  111322. }
  111323. var existingName = ts.getPropertyNameForPropertyNameNode(m.name);
  111324. if (existingName) {
  111325. existingMemberNames.set(existingName, true);
  111326. }
  111327. }
  111328. return baseSymbols.filter(function (propertySymbol) {
  111329. return !existingMemberNames.has(propertySymbol.escapedName) &&
  111330. !!propertySymbol.declarations &&
  111331. !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */);
  111332. });
  111333. }
  111334. /**
  111335. * Filters out completion suggestions from 'symbols' according to existing JSX attributes.
  111336. *
  111337. * @returns Symbols to be suggested in a JSX element, barring those whose attributes
  111338. * do not occur at the current position and have not otherwise been typed.
  111339. */
  111340. function filterJsxAttributes(symbols, attributes) {
  111341. var seenNames = ts.createUnderscoreEscapedMap();
  111342. var membersDeclaredBySpreadAssignment = ts.createMap();
  111343. for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
  111344. var attr = attributes_1[_i];
  111345. // If this is the current item we are editing right now, do not filter it out
  111346. if (isCurrentlyEditingNode(attr)) {
  111347. continue;
  111348. }
  111349. if (attr.kind === 273 /* JsxAttribute */) {
  111350. seenNames.set(attr.name.escapedText, true);
  111351. }
  111352. else if (ts.isJsxSpreadAttribute(attr)) {
  111353. setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment);
  111354. }
  111355. }
  111356. var filteredSymbols = symbols.filter(function (a) { return !seenNames.get(a.escapedName); });
  111357. setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
  111358. return filteredSymbols;
  111359. }
  111360. function isCurrentlyEditingNode(node) {
  111361. return node.getStart(sourceFile) <= position && position <= node.getEnd();
  111362. }
  111363. }
  111364. function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) {
  111365. var name = getSymbolName(symbol, origin, target);
  111366. if (name === undefined
  111367. // If the symbol is external module, don't show it in the completion list
  111368. // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there)
  111369. || symbol.flags & 1536 /* Module */ && ts.isSingleOrDoubleQuote(name.charCodeAt(0))
  111370. // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@"
  111371. || ts.isKnownSymbol(symbol)) {
  111372. return undefined;
  111373. }
  111374. var validNameResult = { name: name, needsConvertPropertyAccess: false };
  111375. if (ts.isIdentifierText(name, target) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
  111376. return validNameResult;
  111377. }
  111378. switch (kind) {
  111379. case 3 /* MemberLike */:
  111380. return undefined;
  111381. case 0 /* ObjectPropertyDeclaration */:
  111382. // TODO: GH#18169
  111383. return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
  111384. case 2 /* PropertyAccess */:
  111385. case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name.
  111386. // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
  111387. return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
  111388. case 5 /* None */:
  111389. case 4 /* String */:
  111390. return validNameResult;
  111391. default:
  111392. ts.Debug.assertNever(kind);
  111393. }
  111394. }
  111395. // A cache of completion entries for keywords, these do not change between sessions
  111396. var _keywordCompletions = [];
  111397. var allKeywordsCompletions = ts.memoize(function () {
  111398. var res = [];
  111399. for (var i = 77 /* FirstKeyword */; i <= 152 /* LastKeyword */; i++) {
  111400. res.push({
  111401. name: ts.tokenToString(i),
  111402. kind: "keyword" /* keyword */,
  111403. kindModifiers: "" /* none */,
  111404. sortText: SortText.GlobalsOrKeywords
  111405. });
  111406. }
  111407. return res;
  111408. });
  111409. function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
  111410. if (!filterOutTsOnlyKeywords)
  111411. return getTypescriptKeywordCompletions(keywordFilter);
  111412. var index = keywordFilter + 7 /* Last */ + 1;
  111413. return _keywordCompletions[index] ||
  111414. (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
  111415. .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
  111416. }
  111417. function getTypescriptKeywordCompletions(keywordFilter) {
  111418. return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
  111419. var kind = ts.stringToToken(entry.name);
  111420. switch (keywordFilter) {
  111421. case 0 /* None */:
  111422. return false;
  111423. case 1 /* All */:
  111424. return isFunctionLikeBodyKeyword(kind)
  111425. || kind === 130 /* DeclareKeyword */
  111426. || kind === 135 /* ModuleKeyword */
  111427. || kind === 145 /* TypeKeyword */
  111428. || kind === 136 /* NamespaceKeyword */
  111429. || kind === 123 /* AsKeyword */
  111430. || ts.isTypeKeyword(kind) && kind !== 146 /* UndefinedKeyword */;
  111431. case 5 /* FunctionLikeBodyKeywords */:
  111432. return isFunctionLikeBodyKeyword(kind);
  111433. case 2 /* ClassElementKeywords */:
  111434. return isClassMemberCompletionKeyword(kind);
  111435. case 3 /* InterfaceElementKeywords */:
  111436. return isInterfaceOrTypeLiteralCompletionKeyword(kind);
  111437. case 4 /* ConstructorParameterKeywords */:
  111438. return ts.isParameterPropertyModifier(kind);
  111439. case 6 /* TypeAssertionKeywords */:
  111440. return ts.isTypeKeyword(kind) || kind === 81 /* ConstKeyword */;
  111441. case 7 /* TypeKeywords */:
  111442. return ts.isTypeKeyword(kind);
  111443. default:
  111444. return ts.Debug.assertNever(keywordFilter);
  111445. }
  111446. }));
  111447. }
  111448. function isTypeScriptOnlyKeyword(kind) {
  111449. switch (kind) {
  111450. case 122 /* AbstractKeyword */:
  111451. case 125 /* AnyKeyword */:
  111452. case 151 /* BigIntKeyword */:
  111453. case 128 /* BooleanKeyword */:
  111454. case 130 /* DeclareKeyword */:
  111455. case 88 /* EnumKeyword */:
  111456. case 150 /* GlobalKeyword */:
  111457. case 113 /* ImplementsKeyword */:
  111458. case 132 /* InferKeyword */:
  111459. case 114 /* InterfaceKeyword */:
  111460. case 133 /* IsKeyword */:
  111461. case 134 /* KeyOfKeyword */:
  111462. case 135 /* ModuleKeyword */:
  111463. case 136 /* NamespaceKeyword */:
  111464. case 137 /* NeverKeyword */:
  111465. case 140 /* NumberKeyword */:
  111466. case 141 /* ObjectKeyword */:
  111467. case 117 /* PrivateKeyword */:
  111468. case 118 /* ProtectedKeyword */:
  111469. case 119 /* PublicKeyword */:
  111470. case 138 /* ReadonlyKeyword */:
  111471. case 143 /* StringKeyword */:
  111472. case 144 /* SymbolKeyword */:
  111473. case 145 /* TypeKeyword */:
  111474. case 147 /* UniqueKeyword */:
  111475. case 148 /* UnknownKeyword */:
  111476. return true;
  111477. default:
  111478. return false;
  111479. }
  111480. }
  111481. function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
  111482. return kind === 138 /* ReadonlyKeyword */;
  111483. }
  111484. function isClassMemberCompletionKeyword(kind) {
  111485. switch (kind) {
  111486. case 122 /* AbstractKeyword */:
  111487. case 129 /* ConstructorKeyword */:
  111488. case 131 /* GetKeyword */:
  111489. case 142 /* SetKeyword */:
  111490. case 126 /* AsyncKeyword */:
  111491. case 130 /* DeclareKeyword */:
  111492. return true;
  111493. default:
  111494. return ts.isClassMemberModifier(kind);
  111495. }
  111496. }
  111497. function isFunctionLikeBodyKeyword(kind) {
  111498. return kind === 126 /* AsyncKeyword */
  111499. || kind === 127 /* AwaitKeyword */
  111500. || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
  111501. }
  111502. function keywordForNode(node) {
  111503. return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind;
  111504. }
  111505. /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */
  111506. function getJsDocTagAtPosition(node, position) {
  111507. var jsdoc = ts.findAncestor(node, ts.isJSDoc);
  111508. return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined);
  111509. }
  111510. function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) {
  111511. var hasCompletionsType = completionsType && completionsType !== contextualType;
  111512. var type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */)
  111513. ? checker.getUnionType([contextualType, completionsType])
  111514. : contextualType;
  111515. var properties = type.isUnion()
  111516. ? checker.getAllPossiblePropertiesOfTypes(type.types.filter(function (memberType) {
  111517. // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
  111518. return !(memberType.flags & 131068 /* Primitive */ ||
  111519. checker.isArrayLikeType(memberType) ||
  111520. ts.typeHasCallOrConstructSignatures(memberType, checker) ||
  111521. checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj));
  111522. }))
  111523. : type.getApparentProperties();
  111524. return hasCompletionsType ? properties.filter(hasDeclarationOtherThanSelf) : properties;
  111525. // Filter out members whose only declaration is the object literal itself to avoid
  111526. // self-fulfilling completions like:
  111527. //
  111528. // function f<T>(x: T) {}
  111529. // f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself
  111530. function hasDeclarationOtherThanSelf(member) {
  111531. return ts.some(member.declarations, function (decl) { return decl.parent !== obj; });
  111532. }
  111533. }
  111534. /**
  111535. * Gets all properties on a type, but if that type is a union of several types,
  111536. * excludes array-like types or callable/constructable types.
  111537. */
  111538. function getPropertiesForCompletion(type, checker) {
  111539. return type.isUnion()
  111540. ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
  111541. : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
  111542. }
  111543. /**
  111544. * Returns the immediate owning class declaration of a context token,
  111545. * on the condition that one exists and that the context implies completion should be given.
  111546. */
  111547. function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) {
  111548. // class c { method() { } | method2() { } }
  111549. switch (location.kind) {
  111550. case 323 /* SyntaxList */:
  111551. return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
  111552. case 1 /* EndOfFileToken */:
  111553. var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
  111554. if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) {
  111555. return cls;
  111556. }
  111557. break;
  111558. case 75 /* Identifier */: // class c extends React.Component { a: () => 1\n compon| }
  111559. if (isFromObjectTypeDeclaration(location)) {
  111560. return ts.findAncestor(location, ts.isObjectTypeDeclaration);
  111561. }
  111562. }
  111563. if (!contextToken)
  111564. return undefined;
  111565. switch (contextToken.kind) {
  111566. case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ }
  111567. return undefined;
  111568. case 26 /* SemicolonToken */: // class c {getValue(): number; | }
  111569. case 19 /* CloseBraceToken */: // class c { method() { } | }
  111570. // class c { method() { } b| }
  111571. return isFromObjectTypeDeclaration(location) && location.parent.name === location
  111572. ? location.parent.parent
  111573. : ts.tryCast(location, ts.isObjectTypeDeclaration);
  111574. case 18 /* OpenBraceToken */: // class c { |
  111575. case 27 /* CommaToken */: // class c {getValue(): number, | }
  111576. return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration);
  111577. default:
  111578. if (!isFromObjectTypeDeclaration(contextToken)) {
  111579. // class c extends React.Component { a: () => 1\n| }
  111580. if (ts.getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== ts.getLineAndCharacterOfPosition(sourceFile, position).line && ts.isObjectTypeDeclaration(location)) {
  111581. return location;
  111582. }
  111583. return undefined;
  111584. }
  111585. var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
  111586. return (isValidKeyword(contextToken.kind) || contextToken.kind === 41 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217
  111587. ? contextToken.parent.parent : undefined;
  111588. }
  111589. }
  111590. // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes
  111591. function isFromObjectTypeDeclaration(node) {
  111592. return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent);
  111593. }
  111594. function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
  111595. switch (triggerCharacter) {
  111596. case ".":
  111597. case "@":
  111598. return true;
  111599. case '"':
  111600. case "'":
  111601. case "`":
  111602. // Only automatically bring up completions if this is an opening quote.
  111603. return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
  111604. case "#":
  111605. return !!contextToken && ts.isPrivateIdentifier(contextToken) && !!ts.getContainingClass(contextToken);
  111606. case "<":
  111607. // Opening JSX tag
  111608. return !!contextToken && contextToken.kind === 29 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
  111609. case "/":
  111610. return !!contextToken && (ts.isStringLiteralLike(contextToken)
  111611. ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
  111612. : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent));
  111613. default:
  111614. return ts.Debug.assertNever(triggerCharacter);
  111615. }
  111616. }
  111617. function binaryExpressionMayBeOpenTag(_a) {
  111618. var left = _a.left;
  111619. return ts.nodeIsMissing(left);
  111620. }
  111621. function findAlias(typeChecker, symbol, predicate) {
  111622. var currentAlias = symbol;
  111623. while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) {
  111624. if (predicate(currentAlias)) {
  111625. return currentAlias;
  111626. }
  111627. }
  111628. }
  111629. })(Completions = ts.Completions || (ts.Completions = {}));
  111630. })(ts || (ts = {}));
  111631. var ts;
  111632. (function (ts) {
  111633. /* @internal */
  111634. var DocumentHighlights;
  111635. (function (DocumentHighlights) {
  111636. function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) {
  111637. var node = ts.getTouchingPropertyName(sourceFile, position);
  111638. if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) {
  111639. // For a JSX element, just highlight the matching tag, not all references.
  111640. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
  111641. var highlightSpans = [openingElement, closingElement].map(function (_a) {
  111642. var tagName = _a.tagName;
  111643. return getHighlightSpanForNode(tagName, sourceFile);
  111644. });
  111645. return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
  111646. }
  111647. return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
  111648. }
  111649. DocumentHighlights.getDocumentHighlights = getDocumentHighlights;
  111650. function getHighlightSpanForNode(node, sourceFile) {
  111651. return {
  111652. fileName: sourceFile.fileName,
  111653. textSpan: ts.createTextSpanFromNode(node, sourceFile),
  111654. kind: "none" /* none */
  111655. };
  111656. }
  111657. function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
  111658. var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; });
  111659. var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet);
  111660. if (!referenceEntries)
  111661. return undefined;
  111662. var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; });
  111663. return ts.arrayFrom(map.entries(), function (_a) {
  111664. var fileName = _a[0], highlightSpans = _a[1];
  111665. if (!sourceFilesSet.has(fileName)) {
  111666. ts.Debug.assert(program.redirectTargetsMap.has(fileName));
  111667. var redirectTarget_1 = program.getSourceFile(fileName);
  111668. var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; });
  111669. fileName = redirect.fileName;
  111670. ts.Debug.assert(sourceFilesSet.has(fileName));
  111671. }
  111672. return { fileName: fileName, highlightSpans: highlightSpans };
  111673. });
  111674. }
  111675. function getSyntacticDocumentHighlights(node, sourceFile) {
  111676. var highlightSpans = getHighlightSpans(node, sourceFile);
  111677. return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
  111678. }
  111679. function getHighlightSpans(node, sourceFile) {
  111680. switch (node.kind) {
  111681. case 95 /* IfKeyword */:
  111682. case 87 /* ElseKeyword */:
  111683. return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined;
  111684. case 101 /* ReturnKeyword */:
  111685. return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences);
  111686. case 105 /* ThrowKeyword */:
  111687. return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences);
  111688. case 107 /* TryKeyword */:
  111689. case 79 /* CatchKeyword */:
  111690. case 92 /* FinallyKeyword */:
  111691. var tryStatement = node.kind === 79 /* CatchKeyword */ ? node.parent.parent : node.parent;
  111692. return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences);
  111693. case 103 /* SwitchKeyword */:
  111694. return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
  111695. case 78 /* CaseKeyword */:
  111696. case 84 /* DefaultKeyword */: {
  111697. if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) {
  111698. return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
  111699. }
  111700. return undefined;
  111701. }
  111702. case 77 /* BreakKeyword */:
  111703. case 82 /* ContinueKeyword */:
  111704. return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
  111705. case 93 /* ForKeyword */:
  111706. case 111 /* WhileKeyword */:
  111707. case 86 /* DoKeyword */:
  111708. return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences);
  111709. case 129 /* ConstructorKeyword */:
  111710. return getFromAllDeclarations(ts.isConstructorDeclaration, [129 /* ConstructorKeyword */]);
  111711. case 131 /* GetKeyword */:
  111712. case 142 /* SetKeyword */:
  111713. return getFromAllDeclarations(ts.isAccessor, [131 /* GetKeyword */, 142 /* SetKeyword */]);
  111714. case 127 /* AwaitKeyword */:
  111715. return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
  111716. case 126 /* AsyncKeyword */:
  111717. return highlightSpans(getAsyncAndAwaitOccurrences(node));
  111718. case 121 /* YieldKeyword */:
  111719. return highlightSpans(getYieldOccurrences(node));
  111720. default:
  111721. return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
  111722. ? highlightSpans(getModifierOccurrences(node.kind, node.parent))
  111723. : undefined;
  111724. }
  111725. function getFromAllDeclarations(nodeTest, keywords) {
  111726. return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) {
  111727. return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined;
  111728. }); });
  111729. }
  111730. function useParent(node, nodeTest, getNodes) {
  111731. return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined;
  111732. }
  111733. function highlightSpans(nodes) {
  111734. return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); });
  111735. }
  111736. }
  111737. /**
  111738. * Aggregates all throw-statements within this node *without* crossing
  111739. * into function boundaries and try-blocks with catch-clauses.
  111740. */
  111741. function aggregateOwnedThrowStatements(node) {
  111742. if (ts.isThrowStatement(node)) {
  111743. return [node];
  111744. }
  111745. else if (ts.isTryStatement(node)) {
  111746. // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context.
  111747. return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock));
  111748. }
  111749. // Do not cross function boundaries.
  111750. return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements);
  111751. }
  111752. /**
  111753. * For lack of a better name, this function takes a throw statement and returns the
  111754. * nearest ancestor that is a try-block (whose try statement has a catch clause),
  111755. * function-block, or source file.
  111756. */
  111757. function getThrowStatementOwner(throwStatement) {
  111758. var child = throwStatement;
  111759. while (child.parent) {
  111760. var parent = child.parent;
  111761. if (ts.isFunctionBlock(parent) || parent.kind === 290 /* SourceFile */) {
  111762. return parent;
  111763. }
  111764. // A throw-statement is only owned by a try-statement if the try-statement has
  111765. // a catch clause, and if the throw-statement occurs within the try block.
  111766. if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
  111767. return child;
  111768. }
  111769. child = parent;
  111770. }
  111771. return undefined;
  111772. }
  111773. function aggregateAllBreakAndContinueStatements(node) {
  111774. return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
  111775. }
  111776. function flatMapChildren(node, cb) {
  111777. var result = [];
  111778. node.forEachChild(function (child) {
  111779. var value = cb(child);
  111780. if (value !== undefined) {
  111781. result.push.apply(result, ts.toArray(value));
  111782. }
  111783. });
  111784. return result;
  111785. }
  111786. function ownsBreakOrContinueStatement(owner, statement) {
  111787. var actualOwner = getBreakOrContinueOwner(statement);
  111788. return !!actualOwner && actualOwner === owner;
  111789. }
  111790. function getBreakOrContinueOwner(statement) {
  111791. return ts.findAncestor(statement, function (node) {
  111792. switch (node.kind) {
  111793. case 237 /* SwitchStatement */:
  111794. if (statement.kind === 233 /* ContinueStatement */) {
  111795. return false;
  111796. }
  111797. // falls through
  111798. case 230 /* ForStatement */:
  111799. case 231 /* ForInStatement */:
  111800. case 232 /* ForOfStatement */:
  111801. case 229 /* WhileStatement */:
  111802. case 228 /* DoStatement */:
  111803. return !statement.label || isLabeledBy(node, statement.label.escapedText);
  111804. default:
  111805. // Don't cross function boundaries.
  111806. // TODO: GH#20090
  111807. return ts.isFunctionLike(node) && "quit";
  111808. }
  111809. });
  111810. }
  111811. function getModifierOccurrences(modifier, declaration) {
  111812. return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); });
  111813. }
  111814. function getNodesToSearchForModifier(declaration, modifierFlag) {
  111815. // Types of node whose children might have modifiers.
  111816. var container = declaration.parent;
  111817. switch (container.kind) {
  111818. case 250 /* ModuleBlock */:
  111819. case 290 /* SourceFile */:
  111820. case 223 /* Block */:
  111821. case 277 /* CaseClause */:
  111822. case 278 /* DefaultClause */:
  111823. // Container is either a class declaration or the declaration is a classDeclaration
  111824. if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) {
  111825. return __spreadArrays(declaration.members, [declaration]);
  111826. }
  111827. else {
  111828. return container.statements;
  111829. }
  111830. case 162 /* Constructor */:
  111831. case 161 /* MethodDeclaration */:
  111832. case 244 /* FunctionDeclaration */:
  111833. return __spreadArrays(container.parameters, (ts.isClassLike(container.parent) ? container.parent.members : []));
  111834. case 245 /* ClassDeclaration */:
  111835. case 214 /* ClassExpression */:
  111836. case 246 /* InterfaceDeclaration */:
  111837. case 173 /* TypeLiteral */:
  111838. var nodes = container.members;
  111839. // If we're an accessibility modifier, we're in an instance member and should search
  111840. // the constructor's parameter list for instance members as well.
  111841. if (modifierFlag & (28 /* AccessibilityModifier */ | 64 /* Readonly */)) {
  111842. var constructor = ts.find(container.members, ts.isConstructorDeclaration);
  111843. if (constructor) {
  111844. return __spreadArrays(nodes, constructor.parameters);
  111845. }
  111846. }
  111847. else if (modifierFlag & 128 /* Abstract */) {
  111848. return __spreadArrays(nodes, [container]);
  111849. }
  111850. return nodes;
  111851. default:
  111852. ts.Debug.assertNever(container, "Invalid container kind.");
  111853. }
  111854. }
  111855. function pushKeywordIf(keywordList, token) {
  111856. var expected = [];
  111857. for (var _i = 2; _i < arguments.length; _i++) {
  111858. expected[_i - 2] = arguments[_i];
  111859. }
  111860. if (token && ts.contains(expected, token.kind)) {
  111861. keywordList.push(token);
  111862. return true;
  111863. }
  111864. return false;
  111865. }
  111866. function getLoopBreakContinueOccurrences(loopNode) {
  111867. var keywords = [];
  111868. if (pushKeywordIf(keywords, loopNode.getFirstToken(), 93 /* ForKeyword */, 111 /* WhileKeyword */, 86 /* DoKeyword */)) {
  111869. // If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
  111870. if (loopNode.kind === 228 /* DoStatement */) {
  111871. var loopTokens = loopNode.getChildren();
  111872. for (var i = loopTokens.length - 1; i >= 0; i--) {
  111873. if (pushKeywordIf(keywords, loopTokens[i], 111 /* WhileKeyword */)) {
  111874. break;
  111875. }
  111876. }
  111877. }
  111878. }
  111879. ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) {
  111880. if (ownsBreakOrContinueStatement(loopNode, statement)) {
  111881. pushKeywordIf(keywords, statement.getFirstToken(), 77 /* BreakKeyword */, 82 /* ContinueKeyword */);
  111882. }
  111883. });
  111884. return keywords;
  111885. }
  111886. function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
  111887. var owner = getBreakOrContinueOwner(breakOrContinueStatement);
  111888. if (owner) {
  111889. switch (owner.kind) {
  111890. case 230 /* ForStatement */:
  111891. case 231 /* ForInStatement */:
  111892. case 232 /* ForOfStatement */:
  111893. case 228 /* DoStatement */:
  111894. case 229 /* WhileStatement */:
  111895. return getLoopBreakContinueOccurrences(owner);
  111896. case 237 /* SwitchStatement */:
  111897. return getSwitchCaseDefaultOccurrences(owner);
  111898. }
  111899. }
  111900. return undefined;
  111901. }
  111902. function getSwitchCaseDefaultOccurrences(switchStatement) {
  111903. var keywords = [];
  111904. pushKeywordIf(keywords, switchStatement.getFirstToken(), 103 /* SwitchKeyword */);
  111905. // Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
  111906. ts.forEach(switchStatement.caseBlock.clauses, function (clause) {
  111907. pushKeywordIf(keywords, clause.getFirstToken(), 78 /* CaseKeyword */, 84 /* DefaultKeyword */);
  111908. ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) {
  111909. if (ownsBreakOrContinueStatement(switchStatement, statement)) {
  111910. pushKeywordIf(keywords, statement.getFirstToken(), 77 /* BreakKeyword */);
  111911. }
  111912. });
  111913. });
  111914. return keywords;
  111915. }
  111916. function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
  111917. var keywords = [];
  111918. pushKeywordIf(keywords, tryStatement.getFirstToken(), 107 /* TryKeyword */);
  111919. if (tryStatement.catchClause) {
  111920. pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 79 /* CatchKeyword */);
  111921. }
  111922. if (tryStatement.finallyBlock) {
  111923. var finallyKeyword = ts.findChildOfKind(tryStatement, 92 /* FinallyKeyword */, sourceFile);
  111924. pushKeywordIf(keywords, finallyKeyword, 92 /* FinallyKeyword */);
  111925. }
  111926. return keywords;
  111927. }
  111928. function getThrowOccurrences(throwStatement, sourceFile) {
  111929. var owner = getThrowStatementOwner(throwStatement);
  111930. if (!owner) {
  111931. return undefined;
  111932. }
  111933. var keywords = [];
  111934. ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) {
  111935. keywords.push(ts.findChildOfKind(throwStatement, 105 /* ThrowKeyword */, sourceFile));
  111936. });
  111937. // If the "owner" is a function, then we equate 'return' and 'throw' statements in their
  111938. // ability to "jump out" of the function, and include occurrences for both.
  111939. if (ts.isFunctionBlock(owner)) {
  111940. ts.forEachReturnStatement(owner, function (returnStatement) {
  111941. keywords.push(ts.findChildOfKind(returnStatement, 101 /* ReturnKeyword */, sourceFile));
  111942. });
  111943. }
  111944. return keywords;
  111945. }
  111946. function getReturnOccurrences(returnStatement, sourceFile) {
  111947. var func = ts.getContainingFunction(returnStatement);
  111948. if (!func) {
  111949. return undefined;
  111950. }
  111951. var keywords = [];
  111952. ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) {
  111953. keywords.push(ts.findChildOfKind(returnStatement, 101 /* ReturnKeyword */, sourceFile));
  111954. });
  111955. // Include 'throw' statements that do not occur within a try block.
  111956. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) {
  111957. keywords.push(ts.findChildOfKind(throwStatement, 105 /* ThrowKeyword */, sourceFile));
  111958. });
  111959. return keywords;
  111960. }
  111961. function getAsyncAndAwaitOccurrences(node) {
  111962. var func = ts.getContainingFunction(node);
  111963. if (!func) {
  111964. return undefined;
  111965. }
  111966. var keywords = [];
  111967. if (func.modifiers) {
  111968. func.modifiers.forEach(function (modifier) {
  111969. pushKeywordIf(keywords, modifier, 126 /* AsyncKeyword */);
  111970. });
  111971. }
  111972. ts.forEachChild(func, function (child) {
  111973. traverseWithoutCrossingFunction(child, function (node) {
  111974. if (ts.isAwaitExpression(node)) {
  111975. pushKeywordIf(keywords, node.getFirstToken(), 127 /* AwaitKeyword */);
  111976. }
  111977. });
  111978. });
  111979. return keywords;
  111980. }
  111981. function getYieldOccurrences(node) {
  111982. var func = ts.getContainingFunction(node);
  111983. if (!func) {
  111984. return undefined;
  111985. }
  111986. var keywords = [];
  111987. ts.forEachChild(func, function (child) {
  111988. traverseWithoutCrossingFunction(child, function (node) {
  111989. if (ts.isYieldExpression(node)) {
  111990. pushKeywordIf(keywords, node.getFirstToken(), 121 /* YieldKeyword */);
  111991. }
  111992. });
  111993. });
  111994. return keywords;
  111995. }
  111996. // Do not cross function/class/interface/module/type boundaries.
  111997. function traverseWithoutCrossingFunction(node, cb) {
  111998. cb(node);
  111999. if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
  112000. ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); });
  112001. }
  112002. }
  112003. function getIfElseOccurrences(ifStatement, sourceFile) {
  112004. var keywords = getIfElseKeywords(ifStatement, sourceFile);
  112005. var result = [];
  112006. // We'd like to highlight else/ifs together if they are only separated by whitespace
  112007. // (i.e. the keywords are separated by no comments, no newlines).
  112008. for (var i = 0; i < keywords.length; i++) {
  112009. if (keywords[i].kind === 87 /* ElseKeyword */ && i < keywords.length - 1) {
  112010. var elseKeyword = keywords[i];
  112011. var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
  112012. var shouldCombineElseAndIf = true;
  112013. // Avoid recalculating getStart() by iterating backwards.
  112014. for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
  112015. if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
  112016. shouldCombineElseAndIf = false;
  112017. break;
  112018. }
  112019. }
  112020. if (shouldCombineElseAndIf) {
  112021. result.push({
  112022. fileName: sourceFile.fileName,
  112023. textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
  112024. kind: "reference" /* reference */
  112025. });
  112026. i++; // skip the next keyword
  112027. continue;
  112028. }
  112029. }
  112030. // Ordinary case: just highlight the keyword.
  112031. result.push(getHighlightSpanForNode(keywords[i], sourceFile));
  112032. }
  112033. return result;
  112034. }
  112035. function getIfElseKeywords(ifStatement, sourceFile) {
  112036. var keywords = [];
  112037. // Traverse upwards through all parent if-statements linked by their else-branches.
  112038. while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
  112039. ifStatement = ifStatement.parent;
  112040. }
  112041. // Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
  112042. while (true) {
  112043. var children = ifStatement.getChildren(sourceFile);
  112044. pushKeywordIf(keywords, children[0], 95 /* IfKeyword */);
  112045. // Generally the 'else' keyword is second-to-last, so we traverse backwards.
  112046. for (var i = children.length - 1; i >= 0; i--) {
  112047. if (pushKeywordIf(keywords, children[i], 87 /* ElseKeyword */)) {
  112048. break;
  112049. }
  112050. }
  112051. if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) {
  112052. break;
  112053. }
  112054. ifStatement = ifStatement.elseStatement;
  112055. }
  112056. return keywords;
  112057. }
  112058. /**
  112059. * Whether or not a 'node' is preceded by a label of the given string.
  112060. * Note: 'node' cannot be a SourceFile.
  112061. */
  112062. function isLabeledBy(node, labelName) {
  112063. return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; });
  112064. }
  112065. })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {}));
  112066. })(ts || (ts = {}));
  112067. var ts;
  112068. (function (ts) {
  112069. function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) {
  112070. return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory);
  112071. }
  112072. ts.createDocumentRegistry = createDocumentRegistry;
  112073. /*@internal*/
  112074. function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) {
  112075. if (currentDirectory === void 0) { currentDirectory = ""; }
  112076. // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
  112077. // for those settings.
  112078. var buckets = ts.createMap();
  112079. var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames);
  112080. function reportStats() {
  112081. var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) {
  112082. var entries = buckets.get(name);
  112083. var sourceFiles = [];
  112084. entries.forEach(function (entry, name) {
  112085. sourceFiles.push({
  112086. name: name,
  112087. refCount: entry.languageServiceRefCount
  112088. });
  112089. });
  112090. sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; });
  112091. return {
  112092. bucket: name,
  112093. sourceFiles: sourceFiles
  112094. };
  112095. });
  112096. return JSON.stringify(bucketInfoArray, undefined, 2);
  112097. }
  112098. function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
  112099. var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  112100. var key = getKeyForCompilationSettings(compilationSettings);
  112101. return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
  112102. }
  112103. function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
  112104. return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind);
  112105. }
  112106. function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
  112107. var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  112108. var key = getKeyForCompilationSettings(compilationSettings);
  112109. return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
  112110. }
  112111. function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
  112112. return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind);
  112113. }
  112114. function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
  112115. var bucket = ts.getOrUpdate(buckets, key, ts.createMap);
  112116. var entry = bucket.get(path);
  112117. var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */;
  112118. if (!entry && externalCache) {
  112119. var sourceFile = externalCache.getDocument(key, path);
  112120. if (sourceFile) {
  112121. ts.Debug.assert(acquiring);
  112122. entry = {
  112123. sourceFile: sourceFile,
  112124. languageServiceRefCount: 0
  112125. };
  112126. bucket.set(path, entry);
  112127. }
  112128. }
  112129. if (!entry) {
  112130. // Have never seen this file with these settings. Create a new source file for it.
  112131. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
  112132. if (externalCache) {
  112133. externalCache.setDocument(key, path, sourceFile);
  112134. }
  112135. entry = {
  112136. sourceFile: sourceFile,
  112137. languageServiceRefCount: 1,
  112138. };
  112139. bucket.set(path, entry);
  112140. }
  112141. else {
  112142. // We have an entry for this file. However, it may be for a different version of
  112143. // the script snapshot. If so, update it appropriately. Otherwise, we can just
  112144. // return it as is.
  112145. if (entry.sourceFile.version !== version) {
  112146. entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217
  112147. if (externalCache) {
  112148. externalCache.setDocument(key, path, entry.sourceFile);
  112149. }
  112150. }
  112151. // If we're acquiring, then this is the first time this LS is asking for this document.
  112152. // Increase our ref count so we know there's another LS using the document. If we're
  112153. // not acquiring, then that means the LS is 'updating' the file instead, and that means
  112154. // it has already acquired the document previously. As such, we do not need to increase
  112155. // the ref count.
  112156. if (acquiring) {
  112157. entry.languageServiceRefCount++;
  112158. }
  112159. }
  112160. ts.Debug.assert(entry.languageServiceRefCount !== 0);
  112161. return entry.sourceFile;
  112162. }
  112163. function releaseDocument(fileName, compilationSettings) {
  112164. var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  112165. var key = getKeyForCompilationSettings(compilationSettings);
  112166. return releaseDocumentWithKey(path, key);
  112167. }
  112168. function releaseDocumentWithKey(path, key) {
  112169. var bucket = ts.Debug.assertDefined(buckets.get(key));
  112170. var entry = bucket.get(path);
  112171. entry.languageServiceRefCount--;
  112172. ts.Debug.assert(entry.languageServiceRefCount >= 0);
  112173. if (entry.languageServiceRefCount === 0) {
  112174. bucket.delete(path);
  112175. }
  112176. }
  112177. function getLanguageServiceRefCounts(path) {
  112178. return ts.arrayFrom(buckets.entries(), function (_a) {
  112179. var key = _a[0], bucket = _a[1];
  112180. var entry = bucket.get(path);
  112181. return [key, entry && entry.languageServiceRefCount];
  112182. });
  112183. }
  112184. return {
  112185. acquireDocument: acquireDocument,
  112186. acquireDocumentWithKey: acquireDocumentWithKey,
  112187. updateDocument: updateDocument,
  112188. updateDocumentWithKey: updateDocumentWithKey,
  112189. releaseDocument: releaseDocument,
  112190. releaseDocumentWithKey: releaseDocumentWithKey,
  112191. getLanguageServiceRefCounts: getLanguageServiceRefCounts,
  112192. reportStats: reportStats,
  112193. getKeyForCompilationSettings: getKeyForCompilationSettings
  112194. };
  112195. }
  112196. ts.createDocumentRegistryInternal = createDocumentRegistryInternal;
  112197. function getKeyForCompilationSettings(settings) {
  112198. return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|");
  112199. }
  112200. })(ts || (ts = {}));
  112201. /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */
  112202. /* @internal */
  112203. var ts;
  112204. (function (ts) {
  112205. var FindAllReferences;
  112206. (function (FindAllReferences) {
  112207. /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */
  112208. function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) {
  112209. var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
  112210. return function (exportSymbol, exportInfo, isForRename) {
  112211. var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers;
  112212. return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename));
  112213. };
  112214. }
  112215. FindAllReferences.createImportTracker = createImportTracker;
  112216. var ExportKind;
  112217. (function (ExportKind) {
  112218. ExportKind[ExportKind["Named"] = 0] = "Named";
  112219. ExportKind[ExportKind["Default"] = 1] = "Default";
  112220. ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals";
  112221. })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {}));
  112222. var ImportExport;
  112223. (function (ImportExport) {
  112224. ImportExport[ImportExport["Import"] = 0] = "Import";
  112225. ImportExport[ImportExport["Export"] = 1] = "Export";
  112226. })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {}));
  112227. /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */
  112228. function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) {
  112229. var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind;
  112230. var markSeenDirectImport = ts.nodeSeenTracker();
  112231. var markSeenIndirectUser = ts.nodeSeenTracker();
  112232. var directImports = [];
  112233. var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
  112234. var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : [];
  112235. handleDirectImports(exportingModuleSymbol);
  112236. return { directImports: directImports, indirectUsers: getIndirectUsers() };
  112237. function getIndirectUsers() {
  112238. if (isAvailableThroughGlobal) {
  112239. // It has `export as namespace`, so anything could potentially use it.
  112240. return sourceFiles;
  112241. }
  112242. // Module augmentations may use this module's exports without importing it.
  112243. for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) {
  112244. var decl = _a[_i];
  112245. if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
  112246. addIndirectUser(decl);
  112247. }
  112248. }
  112249. // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that.
  112250. return indirectUserDeclarations.map(ts.getSourceFileOfNode);
  112251. }
  112252. function handleDirectImports(exportingModuleSymbol) {
  112253. var theseDirectImports = getDirectImports(exportingModuleSymbol);
  112254. if (theseDirectImports) {
  112255. for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) {
  112256. var direct = theseDirectImports_1[_i];
  112257. if (!markSeenDirectImport(direct)) {
  112258. continue;
  112259. }
  112260. if (cancellationToken)
  112261. cancellationToken.throwIfCancellationRequested();
  112262. switch (direct.kind) {
  112263. case 196 /* CallExpression */:
  112264. if (!isAvailableThroughGlobal) {
  112265. var parent = direct.parent;
  112266. if (exportKind === 2 /* ExportEquals */ && parent.kind === 242 /* VariableDeclaration */) {
  112267. var name = parent.name;
  112268. if (name.kind === 75 /* Identifier */) {
  112269. directImports.push(name);
  112270. break;
  112271. }
  112272. }
  112273. // Don't support re-exporting 'require()' calls, so just add a single indirect user.
  112274. addIndirectUser(direct.getSourceFile());
  112275. }
  112276. break;
  112277. case 75 /* Identifier */: // for 'const x = require("y");
  112278. break; // TODO: GH#23879
  112279. case 253 /* ImportEqualsDeclaration */:
  112280. handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false);
  112281. break;
  112282. case 254 /* ImportDeclaration */:
  112283. directImports.push(direct);
  112284. var namedBindings = direct.importClause && direct.importClause.namedBindings;
  112285. if (namedBindings && namedBindings.kind === 256 /* NamespaceImport */) {
  112286. handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true);
  112287. }
  112288. else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) {
  112289. addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports
  112290. }
  112291. break;
  112292. case 260 /* ExportDeclaration */:
  112293. if (!direct.exportClause) {
  112294. // This is `export * from "foo"`, so imports of this module may import the export too.
  112295. handleDirectImports(getContainingModuleSymbol(direct, checker));
  112296. }
  112297. else {
  112298. // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports.
  112299. directImports.push(direct);
  112300. }
  112301. break;
  112302. case 188 /* ImportType */:
  112303. directImports.push(direct);
  112304. break;
  112305. default:
  112306. ts.Debug.failBadSyntaxKind(direct, "Unexpected import kind.");
  112307. }
  112308. }
  112309. }
  112310. }
  112311. function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
  112312. if (exportKind === 2 /* ExportEquals */) {
  112313. // This is a direct import, not import-as-namespace.
  112314. if (!alreadyAddedDirect)
  112315. directImports.push(importDeclaration);
  112316. }
  112317. else if (!isAvailableThroughGlobal) {
  112318. var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
  112319. ts.Debug.assert(sourceFileLike.kind === 290 /* SourceFile */ || sourceFileLike.kind === 249 /* ModuleDeclaration */);
  112320. if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
  112321. addIndirectUsers(sourceFileLike);
  112322. }
  112323. else {
  112324. addIndirectUser(sourceFileLike);
  112325. }
  112326. }
  112327. }
  112328. function addIndirectUser(sourceFileLike) {
  112329. ts.Debug.assert(!isAvailableThroughGlobal);
  112330. var isNew = markSeenIndirectUser(sourceFileLike);
  112331. if (isNew) {
  112332. indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217
  112333. }
  112334. return isNew;
  112335. }
  112336. /** Adds a module and all of its transitive dependencies as possible indirect users. */
  112337. function addIndirectUsers(sourceFileLike) {
  112338. if (!addIndirectUser(sourceFileLike)) {
  112339. return;
  112340. }
  112341. var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
  112342. ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
  112343. var directImports = getDirectImports(moduleSymbol);
  112344. if (directImports) {
  112345. for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) {
  112346. var directImport = directImports_1[_i];
  112347. if (!ts.isImportTypeNode(directImport)) {
  112348. addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport));
  112349. }
  112350. }
  112351. }
  112352. }
  112353. function getDirectImports(moduleSymbol) {
  112354. return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString());
  112355. }
  112356. }
  112357. /**
  112358. * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol.
  112359. * The returned `importSearches` will result in the entire source file being searched.
  112360. * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced.
  112361. */
  112362. function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
  112363. var importSearches = [];
  112364. var singleReferences = [];
  112365. function addSearch(location, symbol) {
  112366. importSearches.push([location, symbol]);
  112367. }
  112368. if (directImports) {
  112369. for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) {
  112370. var decl = directImports_2[_i];
  112371. handleImport(decl);
  112372. }
  112373. }
  112374. return { importSearches: importSearches, singleReferences: singleReferences };
  112375. function handleImport(decl) {
  112376. if (decl.kind === 253 /* ImportEqualsDeclaration */) {
  112377. if (isExternalModuleImportEquals(decl)) {
  112378. handleNamespaceImportLike(decl.name);
  112379. }
  112380. return;
  112381. }
  112382. if (decl.kind === 75 /* Identifier */) {
  112383. handleNamespaceImportLike(decl);
  112384. return;
  112385. }
  112386. if (decl.kind === 188 /* ImportType */) {
  112387. if (decl.qualifier) {
  112388. var firstIdentifier = ts.getFirstIdentifier(decl.qualifier);
  112389. if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) {
  112390. singleReferences.push(firstIdentifier);
  112391. }
  112392. }
  112393. else if (exportKind === 2 /* ExportEquals */) {
  112394. singleReferences.push(decl.argument.literal);
  112395. }
  112396. return;
  112397. }
  112398. // Ignore if there's a grammar error
  112399. if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) {
  112400. return;
  112401. }
  112402. if (decl.kind === 260 /* ExportDeclaration */) {
  112403. if (decl.exportClause && ts.isNamedExports(decl.exportClause)) {
  112404. searchForNamedImport(decl.exportClause);
  112405. }
  112406. return;
  112407. }
  112408. var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings;
  112409. if (namedBindings) {
  112410. switch (namedBindings.kind) {
  112411. case 256 /* NamespaceImport */:
  112412. handleNamespaceImportLike(namedBindings.name);
  112413. break;
  112414. case 257 /* NamedImports */:
  112415. // 'default' might be accessed as a named import `{ default as foo }`.
  112416. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
  112417. searchForNamedImport(namedBindings);
  112418. }
  112419. break;
  112420. default:
  112421. ts.Debug.assertNever(namedBindings);
  112422. }
  112423. }
  112424. // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals.
  112425. // If a default import has the same name as the default export, allow to rename it.
  112426. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
  112427. if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
  112428. var defaultImportAlias = checker.getSymbolAtLocation(name);
  112429. addSearch(name, defaultImportAlias);
  112430. }
  112431. }
  112432. /**
  112433. * `import x = require("./x")` or `import * as x from "./x"`.
  112434. * An `export =` may be imported by this syntax, so it may be a direct import.
  112435. * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
  112436. */
  112437. function handleNamespaceImportLike(importName) {
  112438. // Don't rename an import that already has a different name than the export.
  112439. if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) {
  112440. addSearch(importName, checker.getSymbolAtLocation(importName));
  112441. }
  112442. }
  112443. function searchForNamedImport(namedBindings) {
  112444. if (!namedBindings) {
  112445. return;
  112446. }
  112447. for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
  112448. var element = _a[_i];
  112449. var name = element.name, propertyName = element.propertyName;
  112450. if (!isNameMatch((propertyName || name).escapedText)) {
  112451. continue;
  112452. }
  112453. if (propertyName) {
  112454. // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
  112455. singleReferences.push(propertyName);
  112456. // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`.
  112457. // But do rename `foo` in ` { default as foo }` if that's the original export name.
  112458. if (!isForRename || name.escapedText === exportSymbol.escapedName) {
  112459. // Search locally for `bar`.
  112460. addSearch(name, checker.getSymbolAtLocation(name));
  112461. }
  112462. }
  112463. else {
  112464. var localSymbol = element.kind === 263 /* ExportSpecifier */ && element.propertyName
  112465. ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
  112466. : checker.getSymbolAtLocation(name);
  112467. addSearch(name, localSymbol);
  112468. }
  112469. }
  112470. }
  112471. function isNameMatch(name) {
  112472. // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports
  112473. return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */;
  112474. }
  112475. }
  112476. /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */
  112477. function findNamespaceReExports(sourceFileLike, name, checker) {
  112478. var namespaceImportSymbol = checker.getSymbolAtLocation(name);
  112479. return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
  112480. if (!ts.isExportDeclaration(statement))
  112481. return;
  112482. var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
  112483. return !moduleSpecifier && exportClause && ts.isNamedExports(exportClause) &&
  112484. exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
  112485. });
  112486. }
  112487. function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
  112488. var refs = [];
  112489. var checker = program.getTypeChecker();
  112490. for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
  112491. var referencingFile = sourceFiles_1[_i];
  112492. var searchSourceFile = searchModuleSymbol.valueDeclaration;
  112493. if (searchSourceFile.kind === 290 /* SourceFile */) {
  112494. for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
  112495. var ref = _b[_a];
  112496. if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
  112497. refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
  112498. }
  112499. }
  112500. for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) {
  112501. var ref = _d[_c];
  112502. var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName);
  112503. if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) {
  112504. refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
  112505. }
  112506. }
  112507. }
  112508. forEachImport(referencingFile, function (_importDecl, moduleSpecifier) {
  112509. var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
  112510. if (moduleSymbol === searchModuleSymbol) {
  112511. refs.push({ kind: "import", literal: moduleSpecifier });
  112512. }
  112513. });
  112514. }
  112515. return refs;
  112516. }
  112517. FindAllReferences.findModuleReferences = findModuleReferences;
  112518. /** Returns a map from a module symbol Id to all import statements that directly reference the module. */
  112519. function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
  112520. var map = ts.createMap();
  112521. for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
  112522. var sourceFile = sourceFiles_2[_i];
  112523. if (cancellationToken)
  112524. cancellationToken.throwIfCancellationRequested();
  112525. forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
  112526. var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
  112527. if (moduleSymbol) {
  112528. var id = ts.getSymbolId(moduleSymbol).toString();
  112529. var imports = map.get(id);
  112530. if (!imports) {
  112531. map.set(id, imports = []);
  112532. }
  112533. imports.push(importDecl);
  112534. }
  112535. });
  112536. }
  112537. return map;
  112538. }
  112539. /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
  112540. function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
  112541. return ts.forEach(sourceFileLike.kind === 290 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
  112542. return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
  112543. });
  112544. }
  112545. /** Calls `action` for each import, re-export, or require() in a file. */
  112546. function forEachImport(sourceFile, action) {
  112547. if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) {
  112548. for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
  112549. var i = _a[_i];
  112550. action(ts.importFromModuleSpecifier(i), i);
  112551. }
  112552. }
  112553. else {
  112554. forEachPossibleImportOrExportStatement(sourceFile, function (statement) {
  112555. switch (statement.kind) {
  112556. case 260 /* ExportDeclaration */:
  112557. case 254 /* ImportDeclaration */: {
  112558. var decl = statement;
  112559. if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) {
  112560. action(decl, decl.moduleSpecifier);
  112561. }
  112562. break;
  112563. }
  112564. case 253 /* ImportEqualsDeclaration */: {
  112565. var decl = statement;
  112566. if (isExternalModuleImportEquals(decl)) {
  112567. action(decl, decl.moduleReference.expression);
  112568. }
  112569. break;
  112570. }
  112571. }
  112572. });
  112573. }
  112574. }
  112575. /**
  112576. * Given a local reference, we might notice that it's an import/export and recursively search for references of that.
  112577. * If at an import, look locally for the symbol it imports.
  112578. * If at an export, look for all imports of it.
  112579. * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`.
  112580. * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here.
  112581. */
  112582. function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
  112583. return comingFromExport ? getExport() : getExport() || getImport();
  112584. function getExport() {
  112585. var parent = node.parent;
  112586. var grandParent = parent.parent;
  112587. if (symbol.exportSymbol) {
  112588. if (parent.kind === 194 /* PropertyAccessExpression */) {
  112589. // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use.
  112590. // So check that we are at the declaration.
  112591. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent)
  112592. ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false)
  112593. : undefined;
  112594. }
  112595. else {
  112596. return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent));
  112597. }
  112598. }
  112599. else {
  112600. var exportNode = getExportNode(parent, node);
  112601. if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) {
  112602. if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) {
  112603. // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement.
  112604. if (comingFromExport) {
  112605. return undefined;
  112606. }
  112607. var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
  112608. return { kind: 0 /* Import */, symbol: lhsSymbol };
  112609. }
  112610. else {
  112611. return exportInfo(symbol, getExportKindForDeclaration(exportNode));
  112612. }
  112613. }
  112614. // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
  112615. else if (ts.isExportAssignment(parent)) {
  112616. return getExportAssignmentExport(parent);
  112617. }
  112618. // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment.
  112619. else if (ts.isExportAssignment(grandParent)) {
  112620. return getExportAssignmentExport(grandParent);
  112621. }
  112622. // Similar for `module.exports =` and `exports.A =`.
  112623. else if (ts.isBinaryExpression(parent)) {
  112624. return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
  112625. }
  112626. else if (ts.isBinaryExpression(grandParent)) {
  112627. return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true);
  112628. }
  112629. else if (ts.isJSDocTypedefTag(parent)) {
  112630. return exportInfo(symbol, 0 /* Named */);
  112631. }
  112632. }
  112633. function getExportAssignmentExport(ex) {
  112634. // Get the symbol for the `export =` node; its parent is the module it's the export of.
  112635. var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent");
  112636. var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */;
  112637. return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } };
  112638. }
  112639. function getSpecialPropertyExport(node, useLhsSymbol) {
  112640. var kind;
  112641. switch (ts.getAssignmentDeclarationKind(node)) {
  112642. case 1 /* ExportsProperty */:
  112643. kind = 0 /* Named */;
  112644. break;
  112645. case 2 /* ModuleExports */:
  112646. kind = 2 /* ExportEquals */;
  112647. break;
  112648. default:
  112649. return undefined;
  112650. }
  112651. var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol;
  112652. // Better detection for GH#20803
  112653. if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) {
  112654. ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.formatSymbol(sym) + ", parent is " + ts.Debug.formatSymbol(sym.parent));
  112655. }
  112656. return sym && exportInfo(sym, kind);
  112657. }
  112658. }
  112659. function getImport() {
  112660. var isImport = isNodeImport(node);
  112661. if (!isImport)
  112662. return undefined;
  112663. // A symbol being imported is always an alias. So get what that aliases to find the local symbol.
  112664. var importedSymbol = checker.getImmediateAliasedSymbol(symbol);
  112665. if (!importedSymbol)
  112666. return undefined;
  112667. // Search on the local symbol in the exporting module, not the exported symbol.
  112668. importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
  112669. // Similarly, skip past the symbol for 'export ='
  112670. if (importedSymbol.escapedName === "export=") {
  112671. importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker);
  112672. }
  112673. // If the import has a different name than the export, do not continue searching.
  112674. // If `importedName` is undefined, do continue searching as the export is anonymous.
  112675. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
  112676. var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
  112677. if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
  112678. return { kind: 0 /* Import */, symbol: importedSymbol };
  112679. }
  112680. }
  112681. function exportInfo(symbol, kind) {
  112682. var exportInfo = getExportInfo(symbol, kind, checker);
  112683. return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo };
  112684. }
  112685. // Not meant for use with export specifiers or export assignment.
  112686. function getExportKindForDeclaration(node) {
  112687. return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */;
  112688. }
  112689. }
  112690. FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol;
  112691. function getExportEqualsLocalSymbol(importedSymbol, checker) {
  112692. if (importedSymbol.flags & 2097152 /* Alias */) {
  112693. return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol));
  112694. }
  112695. var decl = importedSymbol.valueDeclaration;
  112696. if (ts.isExportAssignment(decl)) { // `export = class {}`
  112697. return ts.Debug.assertDefined(decl.expression.symbol);
  112698. }
  112699. else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
  112700. return ts.Debug.assertDefined(decl.right.symbol);
  112701. }
  112702. else if (ts.isSourceFile(decl)) { // json module
  112703. return ts.Debug.assertDefined(decl.symbol);
  112704. }
  112705. return ts.Debug.fail();
  112706. }
  112707. // If a reference is a class expression, the exported node would be its parent.
  112708. // If a reference is a variable declaration, the exported node would be the variable statement.
  112709. function getExportNode(parent, node) {
  112710. var declaration = ts.isVariableDeclaration(parent) ? parent : ts.isBindingElement(parent) ? ts.walkUpBindingElementsAndPatterns(parent) : undefined;
  112711. if (declaration) {
  112712. return parent.name !== node ? undefined :
  112713. ts.isCatchClause(declaration.parent) ? undefined : ts.isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : undefined;
  112714. }
  112715. else {
  112716. return parent;
  112717. }
  112718. }
  112719. function isNodeImport(node) {
  112720. var parent = node.parent;
  112721. switch (parent.kind) {
  112722. case 253 /* ImportEqualsDeclaration */:
  112723. return parent.name === node && isExternalModuleImportEquals(parent);
  112724. case 258 /* ImportSpecifier */:
  112725. // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
  112726. return !parent.propertyName;
  112727. case 255 /* ImportClause */:
  112728. case 256 /* NamespaceImport */:
  112729. ts.Debug.assert(parent.name === node);
  112730. return true;
  112731. default:
  112732. return false;
  112733. }
  112734. }
  112735. function getExportInfo(exportSymbol, exportKind, checker) {
  112736. var moduleSymbol = exportSymbol.parent;
  112737. if (!moduleSymbol)
  112738. return undefined; // This can happen if an `export` is not at the top-level (which is a compile error).
  112739. var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation.
  112740. // `export` may appear in a namespace. In that case, just rely on global search.
  112741. return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
  112742. }
  112743. FindAllReferences.getExportInfo = getExportInfo;
  112744. /** If at an export specifier, go to the symbol it refers to. */
  112745. function skipExportSpecifierSymbol(symbol, checker) {
  112746. // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
  112747. if (symbol.declarations) {
  112748. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  112749. var declaration = _a[_i];
  112750. if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
  112751. return checker.getExportSpecifierLocalTargetSymbol(declaration);
  112752. }
  112753. }
  112754. }
  112755. return symbol;
  112756. }
  112757. function getContainingModuleSymbol(importer, checker) {
  112758. return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
  112759. }
  112760. function getSourceFileLikeForImportDeclaration(node) {
  112761. if (node.kind === 196 /* CallExpression */) {
  112762. return node.getSourceFile();
  112763. }
  112764. var parent = node.parent;
  112765. if (parent.kind === 290 /* SourceFile */) {
  112766. return parent;
  112767. }
  112768. ts.Debug.assert(parent.kind === 250 /* ModuleBlock */);
  112769. return ts.cast(parent.parent, isAmbientModuleDeclaration);
  112770. }
  112771. function isAmbientModuleDeclaration(node) {
  112772. return node.kind === 249 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */;
  112773. }
  112774. function isExternalModuleImportEquals(eq) {
  112775. return eq.moduleReference.kind === 265 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */;
  112776. }
  112777. })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
  112778. })(ts || (ts = {}));
  112779. /* @internal */
  112780. var ts;
  112781. (function (ts) {
  112782. var FindAllReferences;
  112783. (function (FindAllReferences) {
  112784. var DefinitionKind;
  112785. (function (DefinitionKind) {
  112786. DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol";
  112787. DefinitionKind[DefinitionKind["Label"] = 1] = "Label";
  112788. DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword";
  112789. DefinitionKind[DefinitionKind["This"] = 3] = "This";
  112790. DefinitionKind[DefinitionKind["String"] = 4] = "String";
  112791. })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {}));
  112792. var EntryKind;
  112793. (function (EntryKind) {
  112794. EntryKind[EntryKind["Span"] = 0] = "Span";
  112795. EntryKind[EntryKind["Node"] = 1] = "Node";
  112796. EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral";
  112797. EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty";
  112798. EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal";
  112799. })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {}));
  112800. function nodeEntry(node, kind) {
  112801. if (kind === void 0) { kind = 1 /* Node */; }
  112802. return {
  112803. kind: kind,
  112804. node: node.name || node,
  112805. context: getContextNodeForNodeEntry(node)
  112806. };
  112807. }
  112808. FindAllReferences.nodeEntry = nodeEntry;
  112809. function isContextWithStartAndEndNode(node) {
  112810. return node && node.kind === undefined;
  112811. }
  112812. FindAllReferences.isContextWithStartAndEndNode = isContextWithStartAndEndNode;
  112813. function getContextNodeForNodeEntry(node) {
  112814. if (ts.isDeclaration(node)) {
  112815. return getContextNode(node);
  112816. }
  112817. if (!node.parent)
  112818. return undefined;
  112819. if (!ts.isDeclaration(node.parent) && !ts.isExportAssignment(node.parent)) {
  112820. // Special property assignment in javascript
  112821. if (ts.isInJSFile(node)) {
  112822. var binaryExpression = ts.isBinaryExpression(node.parent) ?
  112823. node.parent :
  112824. ts.isAccessExpression(node.parent) &&
  112825. ts.isBinaryExpression(node.parent.parent) &&
  112826. node.parent.parent.left === node.parent ?
  112827. node.parent.parent :
  112828. undefined;
  112829. if (binaryExpression && ts.getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */) {
  112830. return getContextNode(binaryExpression);
  112831. }
  112832. }
  112833. // Jsx Tags
  112834. if (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) {
  112835. return node.parent.parent;
  112836. }
  112837. else if (ts.isJsxSelfClosingElement(node.parent) ||
  112838. ts.isLabeledStatement(node.parent) ||
  112839. ts.isBreakOrContinueStatement(node.parent)) {
  112840. return node.parent;
  112841. }
  112842. else if (ts.isStringLiteralLike(node)) {
  112843. var validImport = ts.tryGetImportFromModuleSpecifier(node);
  112844. if (validImport) {
  112845. var declOrStatement = ts.findAncestor(validImport, function (node) {
  112846. return ts.isDeclaration(node) ||
  112847. ts.isStatement(node) ||
  112848. ts.isJSDocTag(node);
  112849. });
  112850. return ts.isDeclaration(declOrStatement) ?
  112851. getContextNode(declOrStatement) :
  112852. declOrStatement;
  112853. }
  112854. }
  112855. // Handle computed property name
  112856. var propertyName = ts.findAncestor(node, ts.isComputedPropertyName);
  112857. return propertyName ?
  112858. getContextNode(propertyName.parent) :
  112859. undefined;
  112860. }
  112861. if (node.parent.name === node || // node is name of declaration, use parent
  112862. ts.isConstructorDeclaration(node.parent) ||
  112863. ts.isExportAssignment(node.parent) ||
  112864. // Property name of the import export specifier or binding pattern, use parent
  112865. ((ts.isImportOrExportSpecifier(node.parent) || ts.isBindingElement(node.parent))
  112866. && node.parent.propertyName === node) ||
  112867. // Is default export
  112868. (node.kind === 84 /* DefaultKeyword */ && ts.hasModifier(node.parent, 513 /* ExportDefault */))) {
  112869. return getContextNode(node.parent);
  112870. }
  112871. return undefined;
  112872. }
  112873. function getContextNode(node) {
  112874. if (!node)
  112875. return undefined;
  112876. switch (node.kind) {
  112877. case 242 /* VariableDeclaration */:
  112878. return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ?
  112879. node :
  112880. ts.isVariableStatement(node.parent.parent) ?
  112881. node.parent.parent :
  112882. ts.isForInOrOfStatement(node.parent.parent) ?
  112883. getContextNode(node.parent.parent) :
  112884. node.parent;
  112885. case 191 /* BindingElement */:
  112886. return getContextNode(node.parent.parent);
  112887. case 258 /* ImportSpecifier */:
  112888. return node.parent.parent.parent;
  112889. case 263 /* ExportSpecifier */:
  112890. case 256 /* NamespaceImport */:
  112891. return node.parent.parent;
  112892. case 255 /* ImportClause */:
  112893. return node.parent;
  112894. case 209 /* BinaryExpression */:
  112895. return ts.isExpressionStatement(node.parent) ?
  112896. node.parent :
  112897. node;
  112898. case 232 /* ForOfStatement */:
  112899. case 231 /* ForInStatement */:
  112900. return {
  112901. start: node.initializer,
  112902. end: node.expression
  112903. };
  112904. case 281 /* PropertyAssignment */:
  112905. case 282 /* ShorthandPropertyAssignment */:
  112906. return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ?
  112907. getContextNode(ts.findAncestor(node.parent, function (node) {
  112908. return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node);
  112909. })) :
  112910. node;
  112911. default:
  112912. return node;
  112913. }
  112914. }
  112915. FindAllReferences.getContextNode = getContextNode;
  112916. function toContextSpan(textSpan, sourceFile, context) {
  112917. if (!context)
  112918. return undefined;
  112919. var contextSpan = isContextWithStartAndEndNode(context) ?
  112920. getTextSpan(context.start, sourceFile, context.end) :
  112921. getTextSpan(context, sourceFile);
  112922. return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ?
  112923. { contextSpan: contextSpan } :
  112924. undefined;
  112925. }
  112926. FindAllReferences.toContextSpan = toContextSpan;
  112927. var FindReferencesUse;
  112928. (function (FindReferencesUse) {
  112929. /**
  112930. * When searching for references to a symbol, the location will not be adjusted (this is the default behavior when not specified).
  112931. */
  112932. FindReferencesUse[FindReferencesUse["Other"] = 0] = "Other";
  112933. /**
  112934. * When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
  112935. */
  112936. FindReferencesUse[FindReferencesUse["References"] = 1] = "References";
  112937. /**
  112938. * When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
  112939. * Unlike `References`, the location will only be adjusted keyword belonged to a declaration with a valid name.
  112940. * If set, we will find fewer references -- if it is referenced by several different names, we still only find references for the original name.
  112941. */
  112942. FindReferencesUse[FindReferencesUse["Rename"] = 2] = "Rename";
  112943. })(FindReferencesUse = FindAllReferences.FindReferencesUse || (FindAllReferences.FindReferencesUse = {}));
  112944. function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
  112945. var node = ts.getTouchingPropertyName(sourceFile, position);
  112946. var referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, { use: 1 /* References */ });
  112947. var checker = program.getTypeChecker();
  112948. return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
  112949. var definition = _a.definition, references = _a.references;
  112950. // Only include referenced symbols that have a valid definition.
  112951. return definition && {
  112952. definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }),
  112953. references: references.map(toReferenceEntry)
  112954. };
  112955. });
  112956. }
  112957. FindAllReferences.findReferencedSymbols = findReferencedSymbols;
  112958. function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) {
  112959. var node = ts.getTouchingPropertyName(sourceFile, position);
  112960. var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
  112961. var checker = program.getTypeChecker();
  112962. return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); });
  112963. }
  112964. FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
  112965. function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
  112966. if (node.kind === 290 /* SourceFile */) {
  112967. return undefined;
  112968. }
  112969. var checker = program.getTypeChecker();
  112970. // If invoked directly on a shorthand property assignment, then return
  112971. // the declaration of the symbol being assigned (not the symbol being assigned to).
  112972. if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
  112973. var result_1 = [];
  112974. Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
  112975. return result_1;
  112976. }
  112977. else if (node.kind === 102 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
  112978. // References to and accesses on the super keyword only have one possible implementation, so no
  112979. // need to "Find all References"
  112980. var symbol = checker.getSymbolAtLocation(node);
  112981. return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
  112982. }
  112983. else {
  112984. // Perform "Find all References" and retrieve only those that are implementations
  112985. return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: 1 /* References */ });
  112986. }
  112987. }
  112988. function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
  112989. return ts.map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
  112990. }
  112991. FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
  112992. function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
  112993. if (options === void 0) { options = {}; }
  112994. if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
  112995. return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
  112996. }
  112997. FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
  112998. function flattenEntries(referenceSymbols) {
  112999. return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
  113000. }
  113001. function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
  113002. var info = (function () {
  113003. switch (def.type) {
  113004. case 0 /* Symbol */: {
  113005. var symbol = def.symbol;
  113006. var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
  113007. var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
  113008. var declaration = symbol.declarations ? ts.first(symbol.declarations) : undefined;
  113009. return {
  113010. node: declaration ?
  113011. ts.getNameOfDeclaration(declaration) || declaration :
  113012. originalNode,
  113013. name: name_1,
  113014. kind: kind_1,
  113015. displayParts: displayParts_1,
  113016. context: getContextNode(declaration)
  113017. };
  113018. }
  113019. case 1 /* Label */: {
  113020. var node_1 = def.node;
  113021. return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
  113022. }
  113023. case 2 /* Keyword */: {
  113024. var node_2 = def.node;
  113025. var name_2 = ts.tokenToString(node_2.kind);
  113026. return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
  113027. }
  113028. case 3 /* This */: {
  113029. var node_3 = def.node;
  113030. var symbol = checker.getSymbolAtLocation(node_3);
  113031. var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
  113032. return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
  113033. }
  113034. case 4 /* String */: {
  113035. var node_4 = def.node;
  113036. return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
  113037. }
  113038. default:
  113039. return ts.Debug.assertNever(def);
  113040. }
  113041. })();
  113042. var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts, context = info.context;
  113043. var sourceFile = node.getSourceFile();
  113044. var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile);
  113045. return __assign({ containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind,
  113046. name: name,
  113047. textSpan: textSpan,
  113048. displayParts: displayParts }, toContextSpan(textSpan, sourceFile, context));
  113049. }
  113050. function getDefinitionKindAndDisplayParts(symbol, checker, node) {
  113051. var meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
  113052. var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node;
  113053. var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
  113054. return { displayParts: displayParts, kind: symbolKind };
  113055. }
  113056. function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) {
  113057. return __assign(__assign({}, entryToDocumentSpan(entry)), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker)));
  113058. }
  113059. FindAllReferences.toRenameLocation = toRenameLocation;
  113060. function toReferenceEntry(entry) {
  113061. var documentSpan = entryToDocumentSpan(entry);
  113062. if (entry.kind === 0 /* Span */) {
  113063. return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false });
  113064. }
  113065. var kind = entry.kind, node = entry.node;
  113066. return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined });
  113067. }
  113068. FindAllReferences.toReferenceEntry = toReferenceEntry;
  113069. function entryToDocumentSpan(entry) {
  113070. if (entry.kind === 0 /* Span */) {
  113071. return { textSpan: entry.textSpan, fileName: entry.fileName };
  113072. }
  113073. else {
  113074. var sourceFile = entry.node.getSourceFile();
  113075. var textSpan = getTextSpan(entry.node, sourceFile);
  113076. return __assign({ textSpan: textSpan, fileName: sourceFile.fileName }, toContextSpan(textSpan, sourceFile, entry.context));
  113077. }
  113078. }
  113079. function getPrefixAndSuffixText(entry, originalNode, checker) {
  113080. if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
  113081. var node = entry.node, kind = entry.kind;
  113082. var name = originalNode.text;
  113083. var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
  113084. if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent) && node.parent.name === node) {
  113085. var prefixColon = { prefixText: name + ": " };
  113086. var suffixColon = { suffixText: ": " + name };
  113087. return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
  113088. : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
  113089. // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
  113090. // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
  113091. : isShorthandAssignment ? suffixColon : prefixColon;
  113092. }
  113093. else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
  113094. // If the original symbol was using this alias, just rename the alias.
  113095. var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
  113096. return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
  113097. }
  113098. else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
  113099. // If the symbol for the node is same as declared node symbol use prefix text
  113100. return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ?
  113101. { prefixText: name + " as " } :
  113102. { suffixText: " as " + name };
  113103. }
  113104. }
  113105. return ts.emptyOptions;
  113106. }
  113107. function toImplementationLocation(entry, checker) {
  113108. var documentSpan = entryToDocumentSpan(entry);
  113109. if (entry.kind !== 0 /* Span */) {
  113110. var node = entry.node;
  113111. return __assign(__assign({}, documentSpan), implementationKindDisplayParts(node, checker));
  113112. }
  113113. else {
  113114. return __assign(__assign({}, documentSpan), { kind: "" /* unknown */, displayParts: [] });
  113115. }
  113116. }
  113117. function implementationKindDisplayParts(node, checker) {
  113118. var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
  113119. if (symbol) {
  113120. return getDefinitionKindAndDisplayParts(symbol, checker, node);
  113121. }
  113122. else if (node.kind === 193 /* ObjectLiteralExpression */) {
  113123. return {
  113124. kind: "interface" /* interfaceElement */,
  113125. displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)]
  113126. };
  113127. }
  113128. else if (node.kind === 214 /* ClassExpression */) {
  113129. return {
  113130. kind: "local class" /* localClassElement */,
  113131. displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)]
  113132. };
  113133. }
  113134. else {
  113135. return { kind: ts.getNodeKind(node), displayParts: [] };
  113136. }
  113137. }
  113138. function toHighlightSpan(entry) {
  113139. var documentSpan = entryToDocumentSpan(entry);
  113140. if (entry.kind === 0 /* Span */) {
  113141. return {
  113142. fileName: documentSpan.fileName,
  113143. span: {
  113144. textSpan: documentSpan.textSpan,
  113145. kind: "reference" /* reference */
  113146. }
  113147. };
  113148. }
  113149. var writeAccess = isWriteAccessForReference(entry.node);
  113150. var span = __assign({ textSpan: documentSpan.textSpan, kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: entry.kind === 2 /* StringLiteral */ ? true : undefined }, documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan });
  113151. return { fileName: documentSpan.fileName, span: span };
  113152. }
  113153. FindAllReferences.toHighlightSpan = toHighlightSpan;
  113154. function getTextSpan(node, sourceFile, endNode) {
  113155. var start = node.getStart(sourceFile);
  113156. var end = (endNode || node).getEnd();
  113157. if (ts.isStringLiteralLike(node)) {
  113158. ts.Debug.assert(endNode === undefined);
  113159. start += 1;
  113160. end -= 1;
  113161. }
  113162. return ts.createTextSpanFromBounds(start, end);
  113163. }
  113164. function getTextSpanOfEntry(entry) {
  113165. return entry.kind === 0 /* Span */ ? entry.textSpan :
  113166. getTextSpan(entry.node, entry.node.getSourceFile());
  113167. }
  113168. FindAllReferences.getTextSpanOfEntry = getTextSpanOfEntry;
  113169. /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
  113170. function isWriteAccessForReference(node) {
  113171. var decl = ts.getDeclarationFromName(node);
  113172. return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node);
  113173. }
  113174. function isDefinitionForReference(node) {
  113175. return node.kind === 84 /* DefaultKeyword */
  113176. || !!ts.getDeclarationFromName(node)
  113177. || ts.isLiteralComputedPropertyDeclarationName(node)
  113178. || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent));
  113179. }
  113180. /**
  113181. * True if 'decl' provides a value, as in `function f() {}`;
  113182. * false if 'decl' is just a location for a future write, as in 'let x;'
  113183. */
  113184. function declarationIsWriteAccess(decl) {
  113185. // Consider anything in an ambient declaration to be a write access since it may be coming from JS.
  113186. if (!!(decl.flags & 8388608 /* Ambient */))
  113187. return true;
  113188. switch (decl.kind) {
  113189. case 209 /* BinaryExpression */:
  113190. case 191 /* BindingElement */:
  113191. case 245 /* ClassDeclaration */:
  113192. case 214 /* ClassExpression */:
  113193. case 84 /* DefaultKeyword */:
  113194. case 248 /* EnumDeclaration */:
  113195. case 284 /* EnumMember */:
  113196. case 263 /* ExportSpecifier */:
  113197. case 255 /* ImportClause */: // default import
  113198. case 253 /* ImportEqualsDeclaration */:
  113199. case 258 /* ImportSpecifier */:
  113200. case 246 /* InterfaceDeclaration */:
  113201. case 314 /* JSDocCallbackTag */:
  113202. case 321 /* JSDocTypedefTag */:
  113203. case 273 /* JsxAttribute */:
  113204. case 249 /* ModuleDeclaration */:
  113205. case 252 /* NamespaceExportDeclaration */:
  113206. case 256 /* NamespaceImport */:
  113207. case 262 /* NamespaceExport */:
  113208. case 156 /* Parameter */:
  113209. case 282 /* ShorthandPropertyAssignment */:
  113210. case 247 /* TypeAliasDeclaration */:
  113211. case 155 /* TypeParameter */:
  113212. return true;
  113213. case 281 /* PropertyAssignment */:
  113214. // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.)
  113215. return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
  113216. case 244 /* FunctionDeclaration */:
  113217. case 201 /* FunctionExpression */:
  113218. case 162 /* Constructor */:
  113219. case 161 /* MethodDeclaration */:
  113220. case 163 /* GetAccessor */:
  113221. case 164 /* SetAccessor */:
  113222. return !!decl.body;
  113223. case 242 /* VariableDeclaration */:
  113224. case 159 /* PropertyDeclaration */:
  113225. return !!decl.initializer || ts.isCatchClause(decl.parent);
  113226. case 160 /* MethodSignature */:
  113227. case 158 /* PropertySignature */:
  113228. case 322 /* JSDocPropertyTag */:
  113229. case 316 /* JSDocParameterTag */:
  113230. return false;
  113231. default:
  113232. return ts.Debug.failBadSyntaxKind(decl);
  113233. }
  113234. }
  113235. /** Encapsulates the core find-all-references algorithm. */
  113236. var Core;
  113237. (function (Core) {
  113238. /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
  113239. function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
  113240. if (options === void 0) { options = {}; }
  113241. if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
  113242. if (options.use === 1 /* References */) {
  113243. node = ts.getAdjustedReferenceLocation(node);
  113244. }
  113245. else if (options.use === 2 /* Rename */) {
  113246. node = ts.getAdjustedRenameLocation(node);
  113247. }
  113248. if (ts.isSourceFile(node)) {
  113249. var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
  113250. var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol);
  113251. return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
  113252. }
  113253. if (!options.implementations) {
  113254. var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
  113255. if (special) {
  113256. return special;
  113257. }
  113258. }
  113259. var checker = program.getTypeChecker();
  113260. var symbol = checker.getSymbolAtLocation(node);
  113261. // Could not find a symbol e.g. unknown identifier
  113262. if (!symbol) {
  113263. // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
  113264. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
  113265. }
  113266. if (symbol.escapedName === "export=" /* ExportEquals */) {
  113267. return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
  113268. }
  113269. var moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
  113270. if (moduleReferences && !(symbol.flags & 33554432 /* Transient */)) {
  113271. return moduleReferences;
  113272. }
  113273. var aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker);
  113274. var moduleReferencesOfExportTarget = aliasedSymbol &&
  113275. getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
  113276. var references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
  113277. return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
  113278. }
  113279. Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
  113280. function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) {
  113281. if (node.parent && ts.isNamespaceExportDeclaration(node.parent)) {
  113282. var aliasedSymbol = checker.getAliasedSymbol(symbol);
  113283. var targetSymbol = checker.getMergedSymbol(aliasedSymbol);
  113284. if (aliasedSymbol !== targetSymbol) {
  113285. return targetSymbol;
  113286. }
  113287. }
  113288. return undefined;
  113289. }
  113290. function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
  113291. var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile);
  113292. if (!moduleSourceFile)
  113293. return undefined;
  113294. var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
  113295. // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
  113296. var moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
  113297. if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
  113298. return moduleReferences;
  113299. // Continue to get references to 'export ='.
  113300. var checker = program.getTypeChecker();
  113301. symbol = ts.skipAlias(exportEquals, checker);
  113302. return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ undefined, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
  113303. }
  113304. /**
  113305. * Merges the references by sorting them (by file index in sourceFiles and their location in it) that point to same definition symbol
  113306. */
  113307. function mergeReferences(program) {
  113308. var referencesToMerge = [];
  113309. for (var _i = 1; _i < arguments.length; _i++) {
  113310. referencesToMerge[_i - 1] = arguments[_i];
  113311. }
  113312. var result;
  113313. for (var _a = 0, referencesToMerge_1 = referencesToMerge; _a < referencesToMerge_1.length; _a++) {
  113314. var references = referencesToMerge_1[_a];
  113315. if (!references || !references.length)
  113316. continue;
  113317. if (!result) {
  113318. result = references;
  113319. continue;
  113320. }
  113321. var _loop_3 = function (entry) {
  113322. if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
  113323. result.push(entry);
  113324. return "continue";
  113325. }
  113326. var symbol = entry.definition.symbol;
  113327. var refIndex = ts.findIndex(result, function (ref) { return !!ref.definition &&
  113328. ref.definition.type === 0 /* Symbol */ &&
  113329. ref.definition.symbol === symbol; });
  113330. if (refIndex === -1) {
  113331. result.push(entry);
  113332. return "continue";
  113333. }
  113334. var reference = result[refIndex];
  113335. result[refIndex] = {
  113336. definition: reference.definition,
  113337. references: reference.references.concat(entry.references).sort(function (entry1, entry2) {
  113338. var entry1File = getSourceFileIndexOfEntry(program, entry1);
  113339. var entry2File = getSourceFileIndexOfEntry(program, entry2);
  113340. if (entry1File !== entry2File) {
  113341. return ts.compareValues(entry1File, entry2File);
  113342. }
  113343. var entry1Span = getTextSpanOfEntry(entry1);
  113344. var entry2Span = getTextSpanOfEntry(entry2);
  113345. return entry1Span.start !== entry2Span.start ?
  113346. ts.compareValues(entry1Span.start, entry2Span.start) :
  113347. ts.compareValues(entry1Span.length, entry2Span.length);
  113348. })
  113349. };
  113350. };
  113351. for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
  113352. var entry = references_1[_b];
  113353. _loop_3(entry);
  113354. }
  113355. }
  113356. return result;
  113357. }
  113358. function getSourceFileIndexOfEntry(program, entry) {
  113359. var sourceFile = entry.kind === 0 /* Span */ ?
  113360. program.getSourceFile(entry.fileName) :
  113361. entry.node.getSourceFile();
  113362. return program.getSourceFiles().indexOf(sourceFile);
  113363. }
  113364. function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
  113365. ts.Debug.assert(!!symbol.valueDeclaration);
  113366. var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
  113367. if (reference.kind === "import") {
  113368. var parent = reference.literal.parent;
  113369. if (ts.isLiteralTypeNode(parent)) {
  113370. var importType = ts.cast(parent.parent, ts.isImportTypeNode);
  113371. if (excludeImportTypeOfExportEquals && !importType.qualifier) {
  113372. return undefined;
  113373. }
  113374. }
  113375. // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
  113376. return nodeEntry(reference.literal);
  113377. }
  113378. else {
  113379. return {
  113380. kind: 0 /* Span */,
  113381. fileName: reference.referencingFile.fileName,
  113382. textSpan: ts.createTextSpanFromRange(reference.ref),
  113383. };
  113384. }
  113385. });
  113386. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  113387. var decl = _a[_i];
  113388. switch (decl.kind) {
  113389. case 290 /* SourceFile */:
  113390. // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
  113391. break;
  113392. case 249 /* ModuleDeclaration */:
  113393. if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
  113394. references.push(nodeEntry(decl.name));
  113395. }
  113396. break;
  113397. default:
  113398. // This may be merged with something.
  113399. ts.Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
  113400. }
  113401. }
  113402. var exported = symbol.exports.get("export=" /* ExportEquals */);
  113403. if (exported) {
  113404. for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) {
  113405. var decl = _c[_b];
  113406. var sourceFile = decl.getSourceFile();
  113407. if (sourceFilesSet.has(sourceFile.fileName)) {
  113408. // At `module.exports = ...`, reference node is `module`
  113409. var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) ? decl.left.expression :
  113410. ts.isExportAssignment(decl) ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 89 /* ExportKeyword */, sourceFile)) :
  113411. ts.getNameOfDeclaration(decl) || decl;
  113412. references.push(nodeEntry(node));
  113413. }
  113414. }
  113415. }
  113416. return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray;
  113417. }
  113418. /** As in a `readonly prop: any` or `constructor(readonly prop: any)`, not a `readonly any[]`. */
  113419. function isReadonlyTypeOperator(node) {
  113420. return node.kind === 138 /* ReadonlyKeyword */
  113421. && ts.isTypeOperatorNode(node.parent)
  113422. && node.parent.operator === 138 /* ReadonlyKeyword */;
  113423. }
  113424. /** getReferencedSymbols for special node kinds. */
  113425. function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
  113426. if (ts.isTypeKeyword(node.kind)) {
  113427. // A void expression (i.e., `void foo()`) is not special, but the `void` type is.
  113428. if (node.kind === 110 /* VoidKeyword */ && ts.isVoidExpression(node.parent)) {
  113429. return undefined;
  113430. }
  113431. // A modifier readonly (like on a property declaration) is not special;
  113432. // a readonly type keyword (like `readonly string[]`) is.
  113433. if (node.kind === 138 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) {
  113434. return undefined;
  113435. }
  113436. // Likewise, when we *are* looking for a special keyword, make sure we
  113437. // *don’t* include readonly member modifiers.
  113438. return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 138 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : undefined);
  113439. }
  113440. // Labels
  113441. if (ts.isJumpStatementTarget(node)) {
  113442. var labelDefinition = ts.getTargetLabel(node.parent, node.text);
  113443. // if we have a label definition, look within its statement for references, if not, then
  113444. // the label is undefined and we have no results..
  113445. return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
  113446. }
  113447. else if (ts.isLabelOfLabeledStatement(node)) {
  113448. // it is a label definition and not a target, search within the parent labeledStatement
  113449. return getLabelReferencesInNode(node.parent, node);
  113450. }
  113451. if (ts.isThis(node)) {
  113452. return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
  113453. }
  113454. if (node.kind === 102 /* SuperKeyword */) {
  113455. return getReferencesForSuperKeyword(node);
  113456. }
  113457. return undefined;
  113458. }
  113459. /** Core find-all-references algorithm for a normal symbol. */
  113460. function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
  113461. var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol;
  113462. // Compute the meaning from the location and the symbol it references
  113463. var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
  113464. var result = [];
  113465. var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
  113466. var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
  113467. if (exportSpecifier) {
  113468. // When renaming at an export specifier, rename the export and not the thing being exported.
  113469. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
  113470. }
  113471. else if (node && node.kind === 84 /* DefaultKeyword */) {
  113472. addReference(node, symbol, state);
  113473. searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
  113474. }
  113475. else {
  113476. var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
  113477. getReferencesInContainerOrFiles(symbol, state, search);
  113478. }
  113479. return result;
  113480. }
  113481. function getReferencesInContainerOrFiles(symbol, state, search) {
  113482. // Try to get the smallest valid scope that we can limit our search to;
  113483. // otherwise we'll need to search globally (i.e. include each file).
  113484. var scope = getSymbolScope(symbol);
  113485. if (scope) {
  113486. getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
  113487. }
  113488. else {
  113489. // Global search
  113490. for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) {
  113491. var sourceFile = _a[_i];
  113492. state.cancellationToken.throwIfCancellationRequested();
  113493. searchForName(sourceFile, search, state);
  113494. }
  113495. }
  113496. }
  113497. function getSpecialSearchKind(node) {
  113498. switch (node.kind) {
  113499. case 129 /* ConstructorKeyword */:
  113500. return 1 /* Constructor */;
  113501. case 75 /* Identifier */:
  113502. if (ts.isClassLike(node.parent)) {
  113503. ts.Debug.assert(node.parent.name === node);
  113504. return 2 /* Class */;
  113505. }
  113506. // falls through
  113507. default:
  113508. return 0 /* None */;
  113509. }
  113510. }
  113511. /** Handle a few special cases relating to export/import specifiers. */
  113512. function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) {
  113513. var parent = node.parent;
  113514. if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) {
  113515. return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
  113516. }
  113517. // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
  113518. return ts.firstDefined(symbol.declarations, function (decl) {
  113519. if (!decl.parent) {
  113520. // Ignore UMD module and global merge
  113521. if (symbol.flags & 33554432 /* Transient */)
  113522. return undefined;
  113523. // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
  113524. ts.Debug.fail("Unexpected symbol at " + ts.Debug.formatSyntaxKind(node.kind) + ": " + ts.Debug.formatSymbol(symbol));
  113525. }
  113526. return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
  113527. ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name)
  113528. : undefined;
  113529. });
  113530. }
  113531. var SpecialSearchKind;
  113532. (function (SpecialSearchKind) {
  113533. SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None";
  113534. SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor";
  113535. SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class";
  113536. })(SpecialSearchKind || (SpecialSearchKind = {}));
  113537. function getNonModuleSymbolOfMergedModuleSymbol(symbol) {
  113538. if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */)))
  113539. return undefined;
  113540. var decl = symbol.declarations && ts.find(symbol.declarations, function (d) { return !ts.isSourceFile(d) && !ts.isModuleDeclaration(d); });
  113541. return decl && decl.symbol;
  113542. }
  113543. /**
  113544. * Holds all state needed for the finding references.
  113545. * Unlike `Search`, there is only one `State`.
  113546. */
  113547. var State = /** @class */ (function () {
  113548. function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
  113549. this.sourceFiles = sourceFiles;
  113550. this.sourceFilesSet = sourceFilesSet;
  113551. this.specialSearchKind = specialSearchKind;
  113552. this.checker = checker;
  113553. this.cancellationToken = cancellationToken;
  113554. this.searchMeaning = searchMeaning;
  113555. this.options = options;
  113556. this.result = result;
  113557. /** Cache for `explicitlyinheritsFrom`. */
  113558. this.inheritsFromCache = ts.createMap();
  113559. /**
  113560. * Type nodes can contain multiple references to the same type. For example:
  113561. * let x: Foo & (Foo & Bar) = ...
  113562. * Because we are returning the implementation locations and not the identifier locations,
  113563. * duplicate entries would be returned here as each of the type references is part of
  113564. * the same implementation. For that reason, check before we add a new entry.
  113565. */
  113566. this.markSeenContainingTypeReference = ts.nodeSeenTracker();
  113567. /**
  113568. * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
  113569. * For example:
  113570. * // b.ts
  113571. * export { foo as bar } from "./a";
  113572. * import { bar } from "./b";
  113573. *
  113574. * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
  113575. * But another reference to it may appear in the same source file.
  113576. * See `tests/cases/fourslash/transitiveExportImports3.ts`.
  113577. */
  113578. this.markSeenReExportRHS = ts.nodeSeenTracker();
  113579. this.symbolIdToReferences = [];
  113580. // Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
  113581. this.sourceFileToSeenSymbols = [];
  113582. }
  113583. State.prototype.includesSourceFile = function (sourceFile) {
  113584. return this.sourceFilesSet.has(sourceFile.fileName);
  113585. };
  113586. /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
  113587. State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
  113588. if (!this.importTracker)
  113589. this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
  113590. return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */);
  113591. };
  113592. /** @param allSearchSymbols set of additional symbols for use by `includes`. */
  113593. State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) {
  113594. if (searchOptions === void 0) { searchOptions = {}; }
  113595. // Note: if this is an external module symbol, the name doesn't include quotes.
  113596. // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
  113597. // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
  113598. // here appears to be intentional).
  113599. var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.symbolName(ts.getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b;
  113600. var escapedText = ts.escapeLeadingUnderscores(text);
  113601. var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined;
  113602. return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
  113603. };
  113604. /**
  113605. * Callback to add references for a particular searched symbol.
  113606. * This initializes a reference group, so only call this if you will add at least one reference.
  113607. */
  113608. State.prototype.referenceAdder = function (searchSymbol) {
  113609. var symbolId = ts.getSymbolId(searchSymbol);
  113610. var references = this.symbolIdToReferences[symbolId];
  113611. if (!references) {
  113612. references = this.symbolIdToReferences[symbolId] = [];
  113613. this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references });
  113614. }
  113615. return function (node, kind) { return references.push(nodeEntry(node, kind)); };
  113616. };
  113617. /** Add a reference with no associated definition. */
  113618. State.prototype.addStringOrCommentReference = function (fileName, textSpan) {
  113619. this.result.push({
  113620. definition: undefined,
  113621. references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }]
  113622. });
  113623. };
  113624. /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
  113625. State.prototype.markSearchedSymbols = function (sourceFile, symbols) {
  113626. var sourceId = ts.getNodeId(sourceFile);
  113627. var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
  113628. var anyNewSymbols = false;
  113629. for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
  113630. var sym = symbols_3[_i];
  113631. anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
  113632. }
  113633. return anyNewSymbols;
  113634. };
  113635. return State;
  113636. }());
  113637. /** Search for all imports of a given exported symbol using `State.getImportSearches`. */
  113638. function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
  113639. var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
  113640. // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
  113641. if (singleReferences.length) {
  113642. var addRef = state.referenceAdder(exportSymbol);
  113643. for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
  113644. var singleRef = singleReferences_1[_i];
  113645. if (shouldAddSingleReference(singleRef, state))
  113646. addRef(singleRef);
  113647. }
  113648. }
  113649. // For each import, find all references to that import in its source file.
  113650. for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) {
  113651. var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1];
  113652. getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
  113653. }
  113654. if (indirectUsers.length) {
  113655. var indirectSearch = void 0;
  113656. switch (exportInfo.exportKind) {
  113657. case 0 /* Named */:
  113658. indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
  113659. break;
  113660. case 1 /* Default */:
  113661. // Search for a property access to '.default'. This can't be renamed.
  113662. indirectSearch = state.options.use === 2 /* Rename */ ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
  113663. break;
  113664. case 2 /* ExportEquals */:
  113665. break;
  113666. }
  113667. if (indirectSearch) {
  113668. for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) {
  113669. var indirectUser = indirectUsers_1[_d];
  113670. searchForName(indirectUser, indirectSearch, state);
  113671. }
  113672. }
  113673. }
  113674. }
  113675. function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
  113676. var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken);
  113677. var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers;
  113678. for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) {
  113679. var importLocation = importSearches_2[_i][0];
  113680. cb(importLocation);
  113681. }
  113682. for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) {
  113683. var indirectUser = indirectUsers_2[_b];
  113684. for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
  113685. var node = _d[_c];
  113686. // Import specifiers should be handled by importSearches
  113687. if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
  113688. cb(node);
  113689. }
  113690. }
  113691. }
  113692. }
  113693. Core.eachExportReference = eachExportReference;
  113694. function shouldAddSingleReference(singleRef, state) {
  113695. if (!hasMatchingMeaning(singleRef, state))
  113696. return false;
  113697. if (state.options.use !== 2 /* Rename */)
  113698. return true;
  113699. // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
  113700. if (!ts.isIdentifier(singleRef))
  113701. return false;
  113702. // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
  113703. return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
  113704. }
  113705. // Go to the symbol we imported from and find references for it.
  113706. function searchForImportedSymbol(symbol, state) {
  113707. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  113708. var declaration = _a[_i];
  113709. var exportingFile = declaration.getSourceFile();
  113710. // Need to search in the file even if it's not in the search-file set, because it might export the symbol.
  113711. getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile));
  113712. }
  113713. }
  113714. /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
  113715. function searchForName(sourceFile, search, state) {
  113716. if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) {
  113717. getReferencesInSourceFile(sourceFile, search, state);
  113718. }
  113719. }
  113720. function getPropertySymbolOfDestructuringAssignment(location, checker) {
  113721. return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent)
  113722. ? checker.getPropertySymbolOfDestructuringAssignment(location)
  113723. : undefined;
  113724. }
  113725. /**
  113726. * Determines the smallest scope in which a symbol may have named references.
  113727. * Note that not every construct has been accounted for. This function can
  113728. * probably be improved.
  113729. *
  113730. * @returns undefined if the scope cannot be determined, implying that
  113731. * a reference to a symbol can occur anywhere.
  113732. */
  113733. function getSymbolScope(symbol) {
  113734. // If this is the symbol of a named function expression or named class expression,
  113735. // then named references are limited to its own scope.
  113736. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration;
  113737. if (valueDeclaration && (valueDeclaration.kind === 201 /* FunctionExpression */ || valueDeclaration.kind === 214 /* ClassExpression */)) {
  113738. return valueDeclaration;
  113739. }
  113740. if (!declarations) {
  113741. return undefined;
  113742. }
  113743. // If this is private property or method, the scope is the containing class
  113744. if (flags & (4 /* Property */ | 8192 /* Method */)) {
  113745. var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); });
  113746. if (privateDeclaration) {
  113747. return ts.getAncestor(privateDeclaration, 245 /* ClassDeclaration */);
  113748. }
  113749. // Else this is a public property and could be accessed from anywhere.
  113750. return undefined;
  113751. }
  113752. // If symbol is of object binding pattern element without property name we would want to
  113753. // look for property too and that could be anywhere
  113754. if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) {
  113755. return undefined;
  113756. }
  113757. /*
  113758. If the symbol has a parent, it's globally visible unless:
  113759. - It's a private property (handled above).
  113760. - It's a type parameter.
  113761. - The parent is an external module: then we should only search in the module (and recurse on the export later).
  113762. - But if the parent has `export as namespace`, the symbol is globally visible through that namespace.
  113763. */
  113764. var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */);
  113765. if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) {
  113766. return undefined;
  113767. }
  113768. var scope;
  113769. for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
  113770. var declaration = declarations_1[_i];
  113771. var container = ts.getContainerNode(declaration);
  113772. if (scope && scope !== container) {
  113773. // Different declarations have different containers, bail out
  113774. return undefined;
  113775. }
  113776. if (!container || container.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
  113777. // This is a global variable and not an external module, any declaration defined
  113778. // within this scope is visible outside the file
  113779. return undefined;
  113780. }
  113781. // The search scope is the container node
  113782. scope = container;
  113783. }
  113784. // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
  113785. // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
  113786. // declare module "a" { export type T = number; }
  113787. // declare module "b" { import { T } from "a"; export const x: T; }
  113788. // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
  113789. return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217
  113790. }
  113791. /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
  113792. function isSymbolReferencedInFile(definition, checker, sourceFile) {
  113793. return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false;
  113794. }
  113795. Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
  113796. function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) {
  113797. var symbol = ts.isParameterPropertyDeclaration(definition.parent, definition.parent.parent)
  113798. ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text))
  113799. : checker.getSymbolAtLocation(definition);
  113800. if (!symbol)
  113801. return undefined;
  113802. for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) {
  113803. var token = _a[_i];
  113804. if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText)
  113805. continue;
  113806. var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary
  113807. if (referenceSymbol === symbol
  113808. || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol
  113809. || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
  113810. var res = cb(token);
  113811. if (res)
  113812. return res;
  113813. }
  113814. }
  113815. }
  113816. Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
  113817. function eachSignatureCall(signature, sourceFiles, checker, cb) {
  113818. if (!signature.name || !ts.isIdentifier(signature.name))
  113819. return;
  113820. var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
  113821. for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
  113822. var sourceFile = sourceFiles_3[_i];
  113823. for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
  113824. var name = _b[_a];
  113825. if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
  113826. continue;
  113827. var called = ts.climbPastPropertyAccess(name);
  113828. var call = called.parent;
  113829. if (!ts.isCallExpression(call) || call.expression !== called)
  113830. continue;
  113831. var referenceSymbol = checker.getSymbolAtLocation(name);
  113832. if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) {
  113833. cb(call);
  113834. }
  113835. }
  113836. }
  113837. }
  113838. Core.eachSignatureCall = eachSignatureCall;
  113839. function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) {
  113840. if (container === void 0) { container = sourceFile; }
  113841. return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); });
  113842. }
  113843. function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
  113844. if (container === void 0) { container = sourceFile; }
  113845. var positions = [];
  113846. /// TODO: Cache symbol existence for files to save text search
  113847. // Also, need to make this work for unicode escapes.
  113848. // Be resilient in the face of a symbol with no name or zero length name
  113849. if (!symbolName || !symbolName.length) {
  113850. return positions;
  113851. }
  113852. var text = sourceFile.text;
  113853. var sourceLength = text.length;
  113854. var symbolNameLength = symbolName.length;
  113855. var position = text.indexOf(symbolName, container.pos);
  113856. while (position >= 0) {
  113857. // If we are past the end, stop looking
  113858. if (position > container.end)
  113859. break;
  113860. // We found a match. Make sure it's not part of a larger word (i.e. the char
  113861. // before and after it have to be a non-identifier char).
  113862. var endPosition = position + symbolNameLength;
  113863. if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */)) &&
  113864. (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */))) {
  113865. // Found a real match. Keep searching.
  113866. positions.push(position);
  113867. }
  113868. position = text.indexOf(symbolName, position + symbolNameLength + 1);
  113869. }
  113870. return positions;
  113871. }
  113872. function getLabelReferencesInNode(container, targetLabel) {
  113873. var sourceFile = container.getSourceFile();
  113874. var labelName = targetLabel.text;
  113875. var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) {
  113876. // Only pick labels that are either the target label, or have a target that is the target label
  113877. return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? nodeEntry(node) : undefined;
  113878. });
  113879. return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }];
  113880. }
  113881. function isValidReferencePosition(node, searchSymbolName) {
  113882. // Compare the length so we filter out strict superstrings of the symbol we are looking for
  113883. switch (node.kind) {
  113884. case 76 /* PrivateIdentifier */:
  113885. case 75 /* Identifier */:
  113886. return node.text.length === searchSymbolName.length;
  113887. case 14 /* NoSubstitutionTemplateLiteral */:
  113888. case 10 /* StringLiteral */: {
  113889. var str = node;
  113890. return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) &&
  113891. str.text.length === searchSymbolName.length;
  113892. }
  113893. case 8 /* NumericLiteral */:
  113894. return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length;
  113895. case 84 /* DefaultKeyword */:
  113896. return "default".length === searchSymbolName.length;
  113897. default:
  113898. return false;
  113899. }
  113900. }
  113901. function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter) {
  113902. var references = ts.flatMap(sourceFiles, function (sourceFile) {
  113903. cancellationToken.throwIfCancellationRequested();
  113904. return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) {
  113905. if (referenceLocation.kind === keywordKind && (!filter || filter(referenceLocation))) {
  113906. return nodeEntry(referenceLocation);
  113907. }
  113908. });
  113909. });
  113910. return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined;
  113911. }
  113912. function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) {
  113913. if (addReferencesHere === void 0) { addReferencesHere = true; }
  113914. state.cancellationToken.throwIfCancellationRequested();
  113915. return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere);
  113916. }
  113917. /**
  113918. * Search within node "container" for references for a search value, where the search value is defined as a
  113919. * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
  113920. * searchLocation: a node where the search value
  113921. */
  113922. function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) {
  113923. if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) {
  113924. return;
  113925. }
  113926. for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) {
  113927. var position = _a[_i];
  113928. getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
  113929. }
  113930. }
  113931. function hasMatchingMeaning(referenceLocation, state) {
  113932. return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
  113933. }
  113934. function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
  113935. var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
  113936. if (!isValidReferencePosition(referenceLocation, search.text)) {
  113937. // This wasn't the start of a token. Check to see if it might be a
  113938. // match in a comment or string if that's what the caller is asking
  113939. // for.
  113940. if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) {
  113941. // In the case where we're looking inside comments/strings, we don't have
  113942. // an actual definition. So just use 'undefined' here. Features like
  113943. // 'Rename' won't care (as they ignore the definitions), and features like
  113944. // 'FindReferences' will just filter out these results.
  113945. state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length));
  113946. }
  113947. return;
  113948. }
  113949. if (!hasMatchingMeaning(referenceLocation, state))
  113950. return;
  113951. var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
  113952. if (!referenceSymbol) {
  113953. return;
  113954. }
  113955. var parent = referenceLocation.parent;
  113956. if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) {
  113957. // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again.
  113958. return;
  113959. }
  113960. if (ts.isExportSpecifier(parent)) {
  113961. ts.Debug.assert(referenceLocation.kind === 75 /* Identifier */);
  113962. getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere);
  113963. return;
  113964. }
  113965. var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
  113966. if (!relatedSymbol) {
  113967. getReferenceForShorthandProperty(referenceSymbol, search, state);
  113968. return;
  113969. }
  113970. switch (state.specialSearchKind) {
  113971. case 0 /* None */:
  113972. if (addReferencesHere)
  113973. addReference(referenceLocation, relatedSymbol, state);
  113974. break;
  113975. case 1 /* Constructor */:
  113976. addConstructorReferences(referenceLocation, sourceFile, search, state);
  113977. break;
  113978. case 2 /* Class */:
  113979. addClassStaticThisReferences(referenceLocation, search, state);
  113980. break;
  113981. default:
  113982. ts.Debug.assertNever(state.specialSearchKind);
  113983. }
  113984. getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
  113985. }
  113986. function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
  113987. ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled");
  113988. var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
  113989. var exportDeclaration = parent.parent;
  113990. var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
  113991. if (!alwaysGetReferences && !search.includes(localSymbol)) {
  113992. return;
  113993. }
  113994. if (!propertyName) {
  113995. // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
  113996. if (!(state.options.use === 2 /* Rename */ && (name.escapedText === "default" /* Default */))) {
  113997. addRef();
  113998. }
  113999. }
  114000. else if (referenceLocation === propertyName) {
  114001. // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export.
  114002. // For `export { foo as bar };`, where `foo` is a local, so add it now.
  114003. if (!exportDeclaration.moduleSpecifier) {
  114004. addRef();
  114005. }
  114006. if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) {
  114007. addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state);
  114008. }
  114009. }
  114010. else {
  114011. if (state.markSeenReExportRHS(referenceLocation)) {
  114012. addRef();
  114013. }
  114014. }
  114015. // For `export { foo as bar }`, rename `foo`, but not `bar`.
  114016. if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
  114017. var isDefaultExport = referenceLocation.originalKeywordKind === 84 /* DefaultKeyword */
  114018. || exportSpecifier.name.originalKeywordKind === 84 /* DefaultKeyword */;
  114019. var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
  114020. var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
  114021. var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker);
  114022. if (exportInfo) {
  114023. searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
  114024. }
  114025. }
  114026. // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
  114027. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) {
  114028. var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
  114029. if (imported)
  114030. searchForImportedSymbol(imported, state);
  114031. }
  114032. function addRef() {
  114033. if (addReferencesHere)
  114034. addReference(referenceLocation, localSymbol, state);
  114035. }
  114036. }
  114037. function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
  114038. return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol;
  114039. }
  114040. function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
  114041. var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
  114042. ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation);
  114043. if (propertyName) {
  114044. // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol.
  114045. return propertyName === referenceLocation;
  114046. }
  114047. else {
  114048. // `export { foo } from "foo"` is a re-export.
  114049. // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`.
  114050. return !parent.parent.moduleSpecifier;
  114051. }
  114052. }
  114053. function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
  114054. var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
  114055. if (!importOrExport)
  114056. return;
  114057. var symbol = importOrExport.symbol;
  114058. if (importOrExport.kind === 0 /* Import */) {
  114059. if (!(isForRenameWithPrefixAndSuffixText(state.options))) {
  114060. searchForImportedSymbol(symbol, state);
  114061. }
  114062. }
  114063. else {
  114064. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
  114065. }
  114066. }
  114067. function getReferenceForShorthandProperty(_a, search, state) {
  114068. var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
  114069. var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
  114070. var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration);
  114071. /*
  114072. * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
  114073. * has two meanings: property name and property value. Therefore when we do findAllReference at the position where
  114074. * an identifier is declared, the language service should return the position of the variable declaration as well as
  114075. * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
  114076. * position of property accessing, the referenceEntry of such position will be handled in the first case.
  114077. */
  114078. if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
  114079. addReference(name, shorthandValueSymbol, state);
  114080. }
  114081. }
  114082. function addReference(referenceLocation, relatedSymbol, state) {
  114083. var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; // eslint-disable-line no-in-operator
  114084. var addRef = state.referenceAdder(symbol);
  114085. if (state.options.implementations) {
  114086. addImplementationReferences(referenceLocation, addRef, state);
  114087. }
  114088. else {
  114089. addRef(referenceLocation, kind);
  114090. }
  114091. }
  114092. /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
  114093. function addConstructorReferences(referenceLocation, sourceFile, search, state) {
  114094. if (ts.isNewExpressionTarget(referenceLocation)) {
  114095. addReference(referenceLocation, search.symbol, state);
  114096. }
  114097. var pusher = function () { return state.referenceAdder(search.symbol); };
  114098. if (ts.isClassLike(referenceLocation.parent)) {
  114099. ts.Debug.assert(referenceLocation.kind === 84 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
  114100. // This is the class declaration containing the constructor.
  114101. findOwnConstructorReferences(search.symbol, sourceFile, pusher());
  114102. }
  114103. else {
  114104. // If this class appears in `extends C`, then the extending class' "super" calls are references.
  114105. var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
  114106. if (classExtending) {
  114107. findSuperConstructorAccesses(classExtending, pusher());
  114108. findInheritedConstructorReferences(classExtending, state);
  114109. }
  114110. }
  114111. }
  114112. function addClassStaticThisReferences(referenceLocation, search, state) {
  114113. addReference(referenceLocation, search.symbol, state);
  114114. var classLike = referenceLocation.parent;
  114115. if (state.options.use === 2 /* Rename */ || !ts.isClassLike(classLike))
  114116. return;
  114117. ts.Debug.assert(classLike.name === referenceLocation);
  114118. var addRef = state.referenceAdder(search.symbol);
  114119. for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) {
  114120. var member = _a[_i];
  114121. if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) {
  114122. continue;
  114123. }
  114124. if (member.body) {
  114125. member.body.forEachChild(function cb(node) {
  114126. if (node.kind === 104 /* ThisKeyword */) {
  114127. addRef(node);
  114128. }
  114129. else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
  114130. node.forEachChild(cb);
  114131. }
  114132. });
  114133. }
  114134. }
  114135. }
  114136. /**
  114137. * `classSymbol` is the class where the constructor was defined.
  114138. * Reference the constructor and all calls to `new this()`.
  114139. */
  114140. function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
  114141. var constructorSymbol = getClassConstructorSymbol(classSymbol);
  114142. if (constructorSymbol) {
  114143. for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
  114144. var decl = _a[_i];
  114145. var ctrKeyword = ts.findChildOfKind(decl, 129 /* ConstructorKeyword */, sourceFile);
  114146. ts.Debug.assert(decl.kind === 162 /* Constructor */ && !!ctrKeyword);
  114147. addNode(ctrKeyword);
  114148. }
  114149. }
  114150. if (classSymbol.exports) {
  114151. classSymbol.exports.forEach(function (member) {
  114152. var decl = member.valueDeclaration;
  114153. if (decl && decl.kind === 161 /* MethodDeclaration */) {
  114154. var body = decl.body;
  114155. if (body) {
  114156. forEachDescendantOfKind(body, 104 /* ThisKeyword */, function (thisKeyword) {
  114157. if (ts.isNewExpressionTarget(thisKeyword)) {
  114158. addNode(thisKeyword);
  114159. }
  114160. });
  114161. }
  114162. }
  114163. });
  114164. }
  114165. }
  114166. function getClassConstructorSymbol(classSymbol) {
  114167. return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
  114168. }
  114169. /** Find references to `super` in the constructor of an extending class. */
  114170. function findSuperConstructorAccesses(classDeclaration, addNode) {
  114171. var constructor = getClassConstructorSymbol(classDeclaration.symbol);
  114172. if (!constructor) {
  114173. return;
  114174. }
  114175. for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
  114176. var decl = _a[_i];
  114177. ts.Debug.assert(decl.kind === 162 /* Constructor */);
  114178. var body = decl.body;
  114179. if (body) {
  114180. forEachDescendantOfKind(body, 102 /* SuperKeyword */, function (node) {
  114181. if (ts.isCallExpressionTarget(node)) {
  114182. addNode(node);
  114183. }
  114184. });
  114185. }
  114186. }
  114187. }
  114188. function hasOwnConstructor(classDeclaration) {
  114189. return !!getClassConstructorSymbol(classDeclaration.symbol);
  114190. }
  114191. function findInheritedConstructorReferences(classDeclaration, state) {
  114192. if (hasOwnConstructor(classDeclaration))
  114193. return;
  114194. var classSymbol = classDeclaration.symbol;
  114195. var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
  114196. getReferencesInContainerOrFiles(classSymbol, state, search);
  114197. }
  114198. function addImplementationReferences(refNode, addReference, state) {
  114199. // Check if we found a function/propertyAssignment/method with an implementation or initializer
  114200. if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
  114201. addReference(refNode);
  114202. return;
  114203. }
  114204. if (refNode.kind !== 75 /* Identifier */) {
  114205. return;
  114206. }
  114207. if (refNode.parent.kind === 282 /* ShorthandPropertyAssignment */) {
  114208. // Go ahead and dereference the shorthand assignment by going to its definition
  114209. getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference);
  114210. }
  114211. // Check if the node is within an extends or implements clause
  114212. var containingClass = getContainingClassIfInHeritageClause(refNode);
  114213. if (containingClass) {
  114214. addReference(containingClass);
  114215. return;
  114216. }
  114217. // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface
  114218. // Find the first node whose parent isn't a type node -- i.e., the highest type node.
  114219. var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); });
  114220. var typeHavingNode = typeNode.parent;
  114221. if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) {
  114222. if (ts.hasInitializer(typeHavingNode)) {
  114223. addIfImplementation(typeHavingNode.initializer);
  114224. }
  114225. else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) {
  114226. var body = typeHavingNode.body;
  114227. if (body.kind === 223 /* Block */) {
  114228. ts.forEachReturnStatement(body, function (returnStatement) {
  114229. if (returnStatement.expression)
  114230. addIfImplementation(returnStatement.expression);
  114231. });
  114232. }
  114233. else {
  114234. addIfImplementation(body);
  114235. }
  114236. }
  114237. else if (ts.isAssertionExpression(typeHavingNode)) {
  114238. addIfImplementation(typeHavingNode.expression);
  114239. }
  114240. }
  114241. function addIfImplementation(e) {
  114242. if (isImplementationExpression(e))
  114243. addReference(e);
  114244. }
  114245. }
  114246. function getContainingClassIfInHeritageClause(node) {
  114247. return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent)
  114248. : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined;
  114249. }
  114250. /**
  114251. * Returns true if this is an expression that can be considered an implementation
  114252. */
  114253. function isImplementationExpression(node) {
  114254. switch (node.kind) {
  114255. case 200 /* ParenthesizedExpression */:
  114256. return isImplementationExpression(node.expression);
  114257. case 202 /* ArrowFunction */:
  114258. case 201 /* FunctionExpression */:
  114259. case 193 /* ObjectLiteralExpression */:
  114260. case 214 /* ClassExpression */:
  114261. case 192 /* ArrayLiteralExpression */:
  114262. return true;
  114263. default:
  114264. return false;
  114265. }
  114266. }
  114267. /**
  114268. * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol
  114269. * is an interface, determines if some ancestor of the child symbol extends or inherits from it.
  114270. * Also takes in a cache of previous results which makes this slightly more efficient and is
  114271. * necessary to avoid potential loops like so:
  114272. * class A extends B { }
  114273. * class B extends A { }
  114274. *
  114275. * We traverse the AST rather than using the type checker because users are typically only interested
  114276. * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling
  114277. * implementations of types that share a common ancestor with the type whose implementation we are
  114278. * searching for need to be filtered out of the results. The type checker doesn't let us make the
  114279. * distinction between structurally compatible implementations and explicit implementations, so we
  114280. * must use the AST.
  114281. *
  114282. * @param symbol A class or interface Symbol
  114283. * @param parent Another class or interface Symbol
  114284. * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results
  114285. */
  114286. function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) {
  114287. if (symbol === parent) {
  114288. return true;
  114289. }
  114290. var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent);
  114291. var cached = cachedResults.get(key);
  114292. if (cached !== undefined) {
  114293. return cached;
  114294. }
  114295. // Set the key so that we don't infinitely recurse
  114296. cachedResults.set(key, false);
  114297. var inherits = symbol.declarations.some(function (declaration) {
  114298. return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) {
  114299. var type = checker.getTypeAtLocation(typeReference);
  114300. return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker);
  114301. });
  114302. });
  114303. cachedResults.set(key, inherits);
  114304. return inherits;
  114305. }
  114306. function getReferencesForSuperKeyword(superKeyword) {
  114307. var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false);
  114308. if (!searchSpaceNode) {
  114309. return undefined;
  114310. }
  114311. // Whether 'super' occurs in a static context within a class.
  114312. var staticFlag = 32 /* Static */;
  114313. switch (searchSpaceNode.kind) {
  114314. case 159 /* PropertyDeclaration */:
  114315. case 158 /* PropertySignature */:
  114316. case 161 /* MethodDeclaration */:
  114317. case 160 /* MethodSignature */:
  114318. case 162 /* Constructor */:
  114319. case 163 /* GetAccessor */:
  114320. case 164 /* SetAccessor */:
  114321. staticFlag &= ts.getModifierFlags(searchSpaceNode);
  114322. searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
  114323. break;
  114324. default:
  114325. return undefined;
  114326. }
  114327. var sourceFile = searchSpaceNode.getSourceFile();
  114328. var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) {
  114329. if (node.kind !== 102 /* SuperKeyword */) {
  114330. return;
  114331. }
  114332. var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
  114333. // If we have a 'super' container, we must have an enclosing class.
  114334. // Now make sure the owning class is the same as the search-space
  114335. // and has the same static qualifier as the original 'super's owner.
  114336. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : undefined;
  114337. });
  114338. return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }];
  114339. }
  114340. function isParameterName(node) {
  114341. return node.kind === 75 /* Identifier */ && node.parent.kind === 156 /* Parameter */ && node.parent.name === node;
  114342. }
  114343. function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
  114344. var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
  114345. // Whether 'this' occurs in a static context within a class.
  114346. var staticFlag = 32 /* Static */;
  114347. switch (searchSpaceNode.kind) {
  114348. case 161 /* MethodDeclaration */:
  114349. case 160 /* MethodSignature */:
  114350. if (ts.isObjectLiteralMethod(searchSpaceNode)) {
  114351. break;
  114352. }
  114353. // falls through
  114354. case 159 /* PropertyDeclaration */:
  114355. case 158 /* PropertySignature */:
  114356. case 162 /* Constructor */:
  114357. case 163 /* GetAccessor */:
  114358. case 164 /* SetAccessor */:
  114359. staticFlag &= ts.getModifierFlags(searchSpaceNode);
  114360. searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
  114361. break;
  114362. case 290 /* SourceFile */:
  114363. if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
  114364. return undefined;
  114365. }
  114366. // falls through
  114367. case 244 /* FunctionDeclaration */:
  114368. case 201 /* FunctionExpression */:
  114369. break;
  114370. // Computed properties in classes are not handled here because references to this are illegal,
  114371. // so there is no point finding references to them.
  114372. default:
  114373. return undefined;
  114374. }
  114375. var references = ts.flatMap(searchSpaceNode.kind === 290 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
  114376. cancellationToken.throwIfCancellationRequested();
  114377. return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
  114378. if (!ts.isThis(node)) {
  114379. return false;
  114380. }
  114381. var container = ts.getThisContainer(node, /* includeArrowFunctions */ false);
  114382. switch (searchSpaceNode.kind) {
  114383. case 201 /* FunctionExpression */:
  114384. case 244 /* FunctionDeclaration */:
  114385. return searchSpaceNode.symbol === container.symbol;
  114386. case 161 /* MethodDeclaration */:
  114387. case 160 /* MethodSignature */:
  114388. return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
  114389. case 214 /* ClassExpression */:
  114390. case 245 /* ClassDeclaration */:
  114391. // Make sure the container belongs to the same class
  114392. // and has the appropriate static modifier from the original container.
  114393. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
  114394. case 290 /* SourceFile */:
  114395. return container.kind === 290 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
  114396. }
  114397. });
  114398. }).map(function (n) { return nodeEntry(n); });
  114399. var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; });
  114400. return [{
  114401. definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
  114402. references: references
  114403. }];
  114404. }
  114405. function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
  114406. var references = ts.flatMap(sourceFiles, function (sourceFile) {
  114407. cancellationToken.throwIfCancellationRequested();
  114408. return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) {
  114409. return ts.isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, 2 /* StringLiteral */) : undefined;
  114410. });
  114411. });
  114412. return [{
  114413. definition: { type: 4 /* String */, node: node },
  114414. references: references
  114415. }];
  114416. }
  114417. // For certain symbol kinds, we need to include other symbols in the search set.
  114418. // This is not needed when searching for re-exports.
  114419. function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) {
  114420. var result = [];
  114421. forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); },
  114422. /*allowBaseTypes*/ function () { return !implementations; });
  114423. return result;
  114424. }
  114425. function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) {
  114426. var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location);
  114427. if (containingObjectLiteralElement) {
  114428. /* Because in short-hand property assignment, location has two meaning : property name and as value of the property
  114429. * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of
  114430. * property name and variable declaration of the identifier.
  114431. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service
  114432. * should show both 'name' in 'obj' and 'name' in variable declaration
  114433. * const name = "Foo";
  114434. * const obj = { name };
  114435. * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment
  114436. * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration
  114437. * will be included correctly.
  114438. */
  114439. var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol
  114440. if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) {
  114441. // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property.
  114442. return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */);
  114443. }
  114444. // If the location is in a context sensitive location (i.e. in an object literal) try
  114445. // to get a contextual type for it, and add the property symbol from the contextual
  114446. // type to the search set
  114447. var contextualType = checker.getContextualType(containingObjectLiteralElement.parent);
  114448. var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); });
  114449. if (res_1)
  114450. return res_1;
  114451. // If the location is name of property symbol from object literal destructuring pattern
  114452. // Search the property symbol
  114453. // for ( { property: p2 } of elems) { }
  114454. var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
  114455. var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */);
  114456. if (res1)
  114457. return res1;
  114458. var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */);
  114459. if (res2)
  114460. return res2;
  114461. }
  114462. var aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker);
  114463. if (aliasedSymbol) {
  114464. // In case of UMD module and global merging, search for global as well
  114465. var res_2 = cbSymbol(aliasedSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 1 /* Node */);
  114466. if (res_2)
  114467. return res_2;
  114468. }
  114469. var res = fromRoot(symbol);
  114470. if (res)
  114471. return res;
  114472. if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) {
  114473. // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property).
  114474. var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name);
  114475. ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property]
  114476. return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]);
  114477. }
  114478. var exportSpecifier = ts.getDeclarationOfKind(symbol, 263 /* ExportSpecifier */);
  114479. if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) {
  114480. var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
  114481. if (localSymbol) {
  114482. var res_3 = cbSymbol(localSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 1 /* Node */);
  114483. if (res_3)
  114484. return res_3;
  114485. }
  114486. }
  114487. // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property.
  114488. // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local.
  114489. if (!isForRenamePopulateSearchSymbolSet) {
  114490. var bindingElementPropertySymbol = void 0;
  114491. if (onlyIncludeBindingElementAtReferenceLocation) {
  114492. bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined;
  114493. }
  114494. else {
  114495. bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
  114496. }
  114497. return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
  114498. }
  114499. ts.Debug.assert(isForRenamePopulateSearchSymbolSet);
  114500. // due to the above assert and the arguments at the uses of this function,
  114501. // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds
  114502. var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation;
  114503. if (includeOriginalSymbolOfBindingElement) {
  114504. var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
  114505. return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
  114506. }
  114507. function fromRoot(sym, kind) {
  114508. // If this is a union property:
  114509. // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types.
  114510. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search.
  114511. // If the symbol is an instantiation from a another symbol (e.g. widened symbol):
  114512. // - In populateSearchSymbolsSet, add the root the list
  114513. // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.)
  114514. return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) {
  114515. return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind)
  114516. // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
  114517. || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol)
  114518. ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); })
  114519. : undefined);
  114520. });
  114521. }
  114522. function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
  114523. var bindingElement = ts.getDeclarationOfKind(symbol, 191 /* BindingElement */);
  114524. if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) {
  114525. return ts.getPropertySymbolFromBindingElement(checker, bindingElement);
  114526. }
  114527. }
  114528. }
  114529. function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
  114530. var checker = state.checker;
  114531. return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false,
  114532. /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym)
  114533. // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol.
  114534. ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind }
  114535. : undefined; },
  114536. /*allowBaseTypes*/ function (rootSymbol) {
  114537. return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); }));
  114538. });
  114539. }
  114540. /**
  114541. * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
  114542. * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
  114543. * then we need to widen the search to include type positions as well.
  114544. * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated
  114545. * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
  114546. * do not intersect in any of the three spaces.
  114547. */
  114548. function getIntersectingMeaningFromDeclarations(node, symbol) {
  114549. var meaning = ts.getMeaningFromLocation(node);
  114550. var declarations = symbol.declarations;
  114551. if (declarations) {
  114552. var lastIterationMeaning = void 0;
  114553. do {
  114554. // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module]
  114555. // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module
  114556. // intersects with the class in the value space.
  114557. // To achieve that we will keep iterating until the result stabilizes.
  114558. // Remember the last meaning
  114559. lastIterationMeaning = meaning;
  114560. for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
  114561. var declaration = declarations_2[_i];
  114562. var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
  114563. if (declarationMeaning & meaning) {
  114564. meaning |= declarationMeaning;
  114565. }
  114566. }
  114567. } while (meaning !== lastIterationMeaning);
  114568. }
  114569. return meaning;
  114570. }
  114571. Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
  114572. function isImplementation(node) {
  114573. return !!(node.flags & 8388608 /* Ambient */) ? !(ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) :
  114574. (ts.isVariableLike(node) ? ts.hasInitializer(node) :
  114575. ts.isFunctionLikeDeclaration(node) ? !!node.body :
  114576. ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node));
  114577. }
  114578. function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) {
  114579. var refSymbol = checker.getSymbolAtLocation(node);
  114580. var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
  114581. if (shorthandSymbol) {
  114582. for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
  114583. var declaration = _a[_i];
  114584. if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
  114585. addReference(declaration);
  114586. }
  114587. }
  114588. }
  114589. }
  114590. Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
  114591. function forEachDescendantOfKind(node, kind, action) {
  114592. ts.forEachChild(node, function (child) {
  114593. if (child.kind === kind) {
  114594. action(child);
  114595. }
  114596. forEachDescendantOfKind(child, kind, action);
  114597. });
  114598. }
  114599. /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */
  114600. function tryGetClassByExtendingIdentifier(node) {
  114601. return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent);
  114602. }
  114603. /**
  114604. * If we are just looking for implementations and this is a property access expression, we need to get the
  114605. * symbol of the local type of the symbol the property is being accessed on. This is because our search
  114606. * symbol may have a different parent symbol if the local type's symbol does not declare the property
  114607. * being accessed (i.e. it is declared in some parent class or interface)
  114608. */
  114609. function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
  114610. var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined;
  114611. var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
  114612. var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) {
  114613. return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined;
  114614. });
  114615. return res.length === 0 ? undefined : res;
  114616. }
  114617. function isForRenameWithPrefixAndSuffixText(options) {
  114618. return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename;
  114619. }
  114620. })(Core = FindAllReferences.Core || (FindAllReferences.Core = {}));
  114621. })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
  114622. })(ts || (ts = {}));
  114623. /* @internal */
  114624. var ts;
  114625. (function (ts) {
  114626. var CallHierarchy;
  114627. (function (CallHierarchy) {
  114628. /** Indictates whether a node is named function or class expression. */
  114629. function isNamedExpression(node) {
  114630. return (ts.isFunctionExpression(node) || ts.isClassExpression(node)) && ts.isNamedDeclaration(node);
  114631. }
  114632. /** Indicates whether a node is a function, arrow, or class expression assigned to a constant variable. */
  114633. function isConstNamedExpression(node) {
  114634. return (ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node))
  114635. && ts.isVariableDeclaration(node.parent)
  114636. && node === node.parent.initializer
  114637. && ts.isIdentifier(node.parent.name)
  114638. && !!(ts.getCombinedNodeFlags(node.parent) & 2 /* Const */);
  114639. }
  114640. /**
  114641. * Indicates whether a node could possibly be a call hierarchy declaration.
  114642. *
  114643. * See `resolveCallHierarchyDeclaration` for the specific rules.
  114644. */
  114645. function isPossibleCallHierarchyDeclaration(node) {
  114646. return ts.isSourceFile(node)
  114647. || ts.isModuleDeclaration(node)
  114648. || ts.isFunctionDeclaration(node)
  114649. || ts.isFunctionExpression(node)
  114650. || ts.isClassDeclaration(node)
  114651. || ts.isClassExpression(node)
  114652. || ts.isMethodDeclaration(node)
  114653. || ts.isMethodSignature(node)
  114654. || ts.isGetAccessorDeclaration(node)
  114655. || ts.isSetAccessorDeclaration(node);
  114656. }
  114657. /**
  114658. * Indicates whether a node is a valid a call hierarchy declaration.
  114659. *
  114660. * See `resolveCallHierarchyDeclaration` for the specific rules.
  114661. */
  114662. function isValidCallHierarchyDeclaration(node) {
  114663. return ts.isSourceFile(node)
  114664. || ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)
  114665. || ts.isFunctionDeclaration(node)
  114666. || ts.isClassDeclaration(node)
  114667. || ts.isMethodDeclaration(node)
  114668. || ts.isMethodSignature(node)
  114669. || ts.isGetAccessorDeclaration(node)
  114670. || ts.isSetAccessorDeclaration(node)
  114671. || isNamedExpression(node)
  114672. || isConstNamedExpression(node);
  114673. }
  114674. /** Gets the node that can be used as a reference to a call hierarchy declaration. */
  114675. function getCallHierarchyDeclarationReferenceNode(node) {
  114676. if (ts.isSourceFile(node))
  114677. return node;
  114678. if (ts.isNamedDeclaration(node))
  114679. return node.name;
  114680. if (isConstNamedExpression(node))
  114681. return node.parent.name;
  114682. return ts.Debug.assertDefined(node.modifiers && ts.find(node.modifiers, isDefaultModifier));
  114683. }
  114684. function isDefaultModifier(node) {
  114685. return node.kind === 84 /* DefaultKeyword */;
  114686. }
  114687. /** Gets the symbol for a call hierarchy declaration. */
  114688. function getSymbolOfCallHierarchyDeclaration(typeChecker, node) {
  114689. var location = getCallHierarchyDeclarationReferenceNode(node);
  114690. return location && typeChecker.getSymbolAtLocation(location);
  114691. }
  114692. /** Gets the text and range for the name of a call hierarchy declaration. */
  114693. function getCallHierarchyItemName(program, node) {
  114694. if (ts.isSourceFile(node)) {
  114695. return { text: node.fileName, pos: 0, end: 0 };
  114696. }
  114697. if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && !ts.isNamedDeclaration(node)) {
  114698. var defaultModifier = node.modifiers && ts.find(node.modifiers, isDefaultModifier);
  114699. if (defaultModifier) {
  114700. return { text: "default", pos: defaultModifier.getStart(), end: defaultModifier.getEnd() };
  114701. }
  114702. }
  114703. var declName = isConstNamedExpression(node) ? node.parent.name :
  114704. ts.Debug.assertDefined(ts.getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
  114705. var text = ts.isIdentifier(declName) ? ts.idText(declName) :
  114706. ts.isStringOrNumericLiteralLike(declName) ? declName.text :
  114707. ts.isComputedPropertyName(declName) ?
  114708. ts.isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text :
  114709. undefined :
  114710. undefined;
  114711. if (text === undefined) {
  114712. var typeChecker = program.getTypeChecker();
  114713. var symbol = typeChecker.getSymbolAtLocation(declName);
  114714. if (symbol) {
  114715. text = typeChecker.symbolToString(symbol, node);
  114716. }
  114717. }
  114718. if (text === undefined) {
  114719. // get the text from printing the node on a single line without comments...
  114720. var printer_1 = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
  114721. text = ts.usingSingleLineStringWriter(function (writer) { return printer_1.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer); });
  114722. }
  114723. return { text: text, pos: declName.getStart(), end: declName.getEnd() };
  114724. }
  114725. function findImplementation(typeChecker, node) {
  114726. if (node.body) {
  114727. return node;
  114728. }
  114729. if (ts.isConstructorDeclaration(node)) {
  114730. return ts.getFirstConstructorWithBody(node.parent);
  114731. }
  114732. if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
  114733. var symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
  114734. if (symbol && symbol.valueDeclaration && ts.isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) {
  114735. return symbol.valueDeclaration;
  114736. }
  114737. return undefined;
  114738. }
  114739. return node;
  114740. }
  114741. function findAllInitialDeclarations(typeChecker, node) {
  114742. var symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
  114743. var declarations;
  114744. if (symbol && symbol.declarations) {
  114745. var indices = ts.indicesOf(symbol.declarations);
  114746. var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); });
  114747. indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; });
  114748. var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; });
  114749. var lastDecl = void 0;
  114750. for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) {
  114751. var decl = sortedDeclarations_1[_i];
  114752. if (isValidCallHierarchyDeclaration(decl)) {
  114753. if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) {
  114754. declarations = ts.append(declarations, decl);
  114755. }
  114756. lastDecl = decl;
  114757. }
  114758. }
  114759. }
  114760. return declarations;
  114761. }
  114762. /** Find the implementation or the first declaration for a call hierarchy declaration. */
  114763. function findImplementationOrAllInitialDeclarations(typeChecker, node) {
  114764. var _a, _b, _c;
  114765. if (ts.isFunctionLikeDeclaration(node)) {
  114766. return (_b = (_a = findImplementation(typeChecker, node)) !== null && _a !== void 0 ? _a : findAllInitialDeclarations(typeChecker, node)) !== null && _b !== void 0 ? _b : node;
  114767. }
  114768. return (_c = findAllInitialDeclarations(typeChecker, node)) !== null && _c !== void 0 ? _c : node;
  114769. }
  114770. /** Resolves the call hierarchy declaration for a node. */
  114771. function resolveCallHierarchyDeclaration(program, location) {
  114772. // A call hierarchy item must refer to either a SourceFile, Module Declaration, or something intrinsically callable that has a name:
  114773. // - Class Declarations
  114774. // - Class Expressions (with a name)
  114775. // - Function Declarations
  114776. // - Function Expressions (with a name or assigned to a const variable)
  114777. // - Arrow Functions (assigned to a const variable)
  114778. // - Constructors
  114779. // - Methods
  114780. // - Accessors
  114781. //
  114782. // If a call is contained in a non-named callable Node (function expression, arrow function, etc.), then
  114783. // its containing `CallHierarchyItem` is a containing function or SourceFile that matches the above list.
  114784. var typeChecker = program.getTypeChecker();
  114785. var followingSymbol = false;
  114786. while (true) {
  114787. if (isValidCallHierarchyDeclaration(location)) {
  114788. return findImplementationOrAllInitialDeclarations(typeChecker, location);
  114789. }
  114790. if (isPossibleCallHierarchyDeclaration(location)) {
  114791. var ancestor = ts.findAncestor(location, isValidCallHierarchyDeclaration);
  114792. return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
  114793. }
  114794. if (ts.isDeclarationName(location)) {
  114795. if (isValidCallHierarchyDeclaration(location.parent)) {
  114796. return findImplementationOrAllInitialDeclarations(typeChecker, location.parent);
  114797. }
  114798. if (isPossibleCallHierarchyDeclaration(location.parent)) {
  114799. var ancestor = ts.findAncestor(location.parent, isValidCallHierarchyDeclaration);
  114800. return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
  114801. }
  114802. if (ts.isVariableDeclaration(location.parent) && location.parent.initializer && isConstNamedExpression(location.parent.initializer)) {
  114803. return location.parent.initializer;
  114804. }
  114805. return undefined;
  114806. }
  114807. if (ts.isConstructorDeclaration(location)) {
  114808. if (isValidCallHierarchyDeclaration(location.parent)) {
  114809. return location.parent;
  114810. }
  114811. return undefined;
  114812. }
  114813. if (!followingSymbol) {
  114814. var symbol = typeChecker.getSymbolAtLocation(location);
  114815. if (symbol) {
  114816. if (symbol.flags & 2097152 /* Alias */) {
  114817. symbol = typeChecker.getAliasedSymbol(symbol);
  114818. }
  114819. if (symbol.valueDeclaration) {
  114820. followingSymbol = true;
  114821. location = symbol.valueDeclaration;
  114822. continue;
  114823. }
  114824. }
  114825. }
  114826. return undefined;
  114827. }
  114828. }
  114829. CallHierarchy.resolveCallHierarchyDeclaration = resolveCallHierarchyDeclaration;
  114830. /** Creates a `CallHierarchyItem` for a call hierarchy declaration. */
  114831. function createCallHierarchyItem(program, node) {
  114832. var sourceFile = node.getSourceFile();
  114833. var name = getCallHierarchyItemName(program, node);
  114834. var kind = ts.getNodeKind(node);
  114835. var span = ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, node.getFullStart(), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true), node.getEnd());
  114836. var selectionSpan = ts.createTextSpanFromBounds(name.pos, name.end);
  114837. return { file: sourceFile.fileName, kind: kind, name: name.text, span: span, selectionSpan: selectionSpan };
  114838. }
  114839. CallHierarchy.createCallHierarchyItem = createCallHierarchyItem;
  114840. function isDefined(x) {
  114841. return x !== undefined;
  114842. }
  114843. function convertEntryToCallSite(entry) {
  114844. if (entry.kind === 1 /* Node */) {
  114845. var node = entry.node;
  114846. if (ts.isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
  114847. || ts.isTaggedTemplateTag(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
  114848. || ts.isDecoratorTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
  114849. || ts.isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
  114850. || ts.isRightSideOfPropertyAccess(node)
  114851. || ts.isArgumentExpressionOfElementAccess(node)) {
  114852. var sourceFile = node.getSourceFile();
  114853. var ancestor = ts.findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile;
  114854. return { declaration: ancestor, range: ts.createTextRangeFromNode(node, sourceFile) };
  114855. }
  114856. }
  114857. }
  114858. function getCallSiteGroupKey(entry) {
  114859. return "" + ts.getNodeId(entry.declaration);
  114860. }
  114861. function createCallHierarchyIncomingCall(from, fromSpans) {
  114862. return { from: from, fromSpans: fromSpans };
  114863. }
  114864. function convertCallSiteGroupToIncomingCall(program, entries) {
  114865. return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, function (entry) { return ts.createTextSpanFromRange(entry.range); }));
  114866. }
  114867. /** Gets the call sites that call into the provided call hierarchy declaration. */
  114868. function getIncomingCalls(program, declaration, cancellationToken) {
  114869. // Source files and modules have no incoming calls.
  114870. if (ts.isSourceFile(declaration) || ts.isModuleDeclaration(declaration)) {
  114871. return [];
  114872. }
  114873. var location = getCallHierarchyDeclarationReferenceNode(declaration);
  114874. var calls = ts.filter(ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, program.getSourceFiles(), location, /*position*/ 0, { use: 1 /* References */ }, convertEntryToCallSite), isDefined);
  114875. return calls ? ts.group(calls, getCallSiteGroupKey, function (entries) { return convertCallSiteGroupToIncomingCall(program, entries); }) : [];
  114876. }
  114877. CallHierarchy.getIncomingCalls = getIncomingCalls;
  114878. function createCallSiteCollector(program, callSites) {
  114879. function recordCallSite(node) {
  114880. var target = ts.isTaggedTemplateExpression(node) ? node.tag :
  114881. ts.isJsxOpeningLikeElement(node) ? node.tagName :
  114882. ts.isAccessExpression(node) ? node :
  114883. node.expression;
  114884. var declaration = resolveCallHierarchyDeclaration(program, target);
  114885. if (declaration) {
  114886. var range = ts.createTextRangeFromNode(target, node.getSourceFile());
  114887. if (ts.isArray(declaration)) {
  114888. for (var _i = 0, declaration_1 = declaration; _i < declaration_1.length; _i++) {
  114889. var decl = declaration_1[_i];
  114890. callSites.push({ declaration: decl, range: range });
  114891. }
  114892. }
  114893. else {
  114894. callSites.push({ declaration: declaration, range: range });
  114895. }
  114896. }
  114897. }
  114898. function collect(node) {
  114899. if (!node)
  114900. return;
  114901. if (node.flags & 8388608 /* Ambient */) {
  114902. // do not descend into ambient nodes.
  114903. return;
  114904. }
  114905. if (isValidCallHierarchyDeclaration(node)) {
  114906. // do not descend into other call site declarations, other than class member names
  114907. if (ts.isClassLike(node)) {
  114908. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  114909. var member = _a[_i];
  114910. if (member.name && ts.isComputedPropertyName(member.name)) {
  114911. collect(member.name.expression);
  114912. }
  114913. }
  114914. }
  114915. return;
  114916. }
  114917. switch (node.kind) {
  114918. case 75 /* Identifier */:
  114919. case 253 /* ImportEqualsDeclaration */:
  114920. case 254 /* ImportDeclaration */:
  114921. case 260 /* ExportDeclaration */:
  114922. case 246 /* InterfaceDeclaration */:
  114923. case 247 /* TypeAliasDeclaration */:
  114924. // do not descend into nodes that cannot contain callable nodes
  114925. return;
  114926. case 199 /* TypeAssertionExpression */:
  114927. case 217 /* AsExpression */:
  114928. // do not descend into the type side of an assertion
  114929. collect(node.expression);
  114930. return;
  114931. case 242 /* VariableDeclaration */:
  114932. case 156 /* Parameter */:
  114933. // do not descend into the type of a variable or parameter declaration
  114934. collect(node.name);
  114935. collect(node.initializer);
  114936. return;
  114937. case 196 /* CallExpression */:
  114938. // do not descend into the type arguments of a call expression
  114939. recordCallSite(node);
  114940. collect(node.expression);
  114941. ts.forEach(node.arguments, collect);
  114942. return;
  114943. case 197 /* NewExpression */:
  114944. // do not descend into the type arguments of a new expression
  114945. recordCallSite(node);
  114946. collect(node.expression);
  114947. ts.forEach(node.arguments, collect);
  114948. return;
  114949. case 198 /* TaggedTemplateExpression */:
  114950. // do not descend into the type arguments of a tagged template expression
  114951. recordCallSite(node);
  114952. collect(node.tag);
  114953. collect(node.template);
  114954. return;
  114955. case 268 /* JsxOpeningElement */:
  114956. case 267 /* JsxSelfClosingElement */:
  114957. // do not descend into the type arguments of a JsxOpeningLikeElement
  114958. recordCallSite(node);
  114959. collect(node.tagName);
  114960. collect(node.attributes);
  114961. return;
  114962. case 157 /* Decorator */:
  114963. recordCallSite(node);
  114964. collect(node.expression);
  114965. return;
  114966. case 194 /* PropertyAccessExpression */:
  114967. case 195 /* ElementAccessExpression */:
  114968. recordCallSite(node);
  114969. ts.forEachChild(node, collect);
  114970. break;
  114971. }
  114972. if (ts.isPartOfTypeNode(node)) {
  114973. // do not descend into types
  114974. return;
  114975. }
  114976. ts.forEachChild(node, collect);
  114977. }
  114978. return collect;
  114979. }
  114980. function collectCallSitesOfSourceFile(node, collect) {
  114981. ts.forEach(node.statements, collect);
  114982. }
  114983. function collectCallSitesOfModuleDeclaration(node, collect) {
  114984. if (!ts.hasModifier(node, 2 /* Ambient */) && node.body && ts.isModuleBlock(node.body)) {
  114985. ts.forEach(node.body.statements, collect);
  114986. }
  114987. }
  114988. function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) {
  114989. var implementation = findImplementation(typeChecker, node);
  114990. if (implementation) {
  114991. ts.forEach(implementation.parameters, collect);
  114992. collect(implementation.body);
  114993. }
  114994. }
  114995. function collectCallSitesOfClassLikeDeclaration(node, collect) {
  114996. ts.forEach(node.decorators, collect);
  114997. var heritage = ts.getClassExtendsHeritageElement(node);
  114998. if (heritage) {
  114999. collect(heritage.expression);
  115000. }
  115001. for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
  115002. var member = _a[_i];
  115003. ts.forEach(member.decorators, collect);
  115004. if (ts.isPropertyDeclaration(member)) {
  115005. collect(member.initializer);
  115006. }
  115007. else if (ts.isConstructorDeclaration(member) && member.body) {
  115008. ts.forEach(member.parameters, collect);
  115009. collect(member.body);
  115010. }
  115011. }
  115012. }
  115013. function collectCallSites(program, node) {
  115014. var callSites = [];
  115015. var collect = createCallSiteCollector(program, callSites);
  115016. switch (node.kind) {
  115017. case 290 /* SourceFile */:
  115018. collectCallSitesOfSourceFile(node, collect);
  115019. break;
  115020. case 249 /* ModuleDeclaration */:
  115021. collectCallSitesOfModuleDeclaration(node, collect);
  115022. break;
  115023. case 244 /* FunctionDeclaration */:
  115024. case 201 /* FunctionExpression */:
  115025. case 202 /* ArrowFunction */:
  115026. case 161 /* MethodDeclaration */:
  115027. case 163 /* GetAccessor */:
  115028. case 164 /* SetAccessor */:
  115029. collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect);
  115030. break;
  115031. case 245 /* ClassDeclaration */:
  115032. case 214 /* ClassExpression */:
  115033. collectCallSitesOfClassLikeDeclaration(node, collect);
  115034. break;
  115035. default:
  115036. ts.Debug.assertNever(node);
  115037. }
  115038. return callSites;
  115039. }
  115040. function createCallHierarchyOutgoingCall(to, fromSpans) {
  115041. return { to: to, fromSpans: fromSpans };
  115042. }
  115043. function convertCallSiteGroupToOutgoingCall(program, entries) {
  115044. return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, function (entry) { return ts.createTextSpanFromRange(entry.range); }));
  115045. }
  115046. /** Gets the call sites that call out of the provided call hierarchy declaration. */
  115047. function getOutgoingCalls(program, declaration) {
  115048. if (declaration.flags & 8388608 /* Ambient */ || ts.isMethodSignature(declaration)) {
  115049. return [];
  115050. }
  115051. return ts.group(collectCallSites(program, declaration), getCallSiteGroupKey, function (entries) { return convertCallSiteGroupToOutgoingCall(program, entries); });
  115052. }
  115053. CallHierarchy.getOutgoingCalls = getOutgoingCalls;
  115054. })(CallHierarchy = ts.CallHierarchy || (ts.CallHierarchy = {}));
  115055. })(ts || (ts = {}));
  115056. /* @internal */
  115057. var ts;
  115058. (function (ts) {
  115059. function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) {
  115060. var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
  115061. var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  115062. var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
  115063. var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
  115064. return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, function (changeTracker) {
  115065. updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
  115066. updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
  115067. });
  115068. }
  115069. ts.getEditsForFileRename = getEditsForFileRename;
  115070. // exported for tests
  115071. function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) {
  115072. var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
  115073. return function (path) {
  115074. var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 });
  115075. var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path);
  115076. return originalPath
  115077. ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName)
  115078. : updatedPath;
  115079. };
  115080. function getUpdatedPath(pathToUpdate) {
  115081. if (getCanonicalFileName(pathToUpdate) === canonicalOldPath)
  115082. return newFileOrDirPath;
  115083. var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName);
  115084. return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix;
  115085. }
  115086. }
  115087. ts.getPathUpdater = getPathUpdater;
  115088. // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1.
  115089. function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) {
  115090. var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName);
  115091. return combinePathsSafe(ts.getDirectoryPath(a1), rel);
  115092. }
  115093. function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) {
  115094. var configFile = program.getCompilerOptions().configFile;
  115095. if (!configFile)
  115096. return;
  115097. var configDir = ts.getDirectoryPath(configFile.fileName);
  115098. var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
  115099. if (!jsonObjectLiteral)
  115100. return;
  115101. forEachProperty(jsonObjectLiteral, function (property, propertyName) {
  115102. switch (propertyName) {
  115103. case "files":
  115104. case "include":
  115105. case "exclude": {
  115106. var foundExactMatch = updatePaths(property);
  115107. if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) {
  115108. var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; });
  115109. var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory);
  115110. // If there isn't some include for this, add a new one.
  115111. if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) &&
  115112. !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
  115113. changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath)));
  115114. }
  115115. }
  115116. break;
  115117. }
  115118. case "compilerOptions":
  115119. forEachProperty(property.initializer, function (property, propertyName) {
  115120. var option = ts.getOptionFromName(propertyName);
  115121. if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) {
  115122. updatePaths(property);
  115123. }
  115124. else if (propertyName === "paths") {
  115125. forEachProperty(property.initializer, function (pathsProperty) {
  115126. if (!ts.isArrayLiteralExpression(pathsProperty.initializer))
  115127. return;
  115128. for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) {
  115129. var e = _a[_i];
  115130. tryUpdateString(e);
  115131. }
  115132. });
  115133. }
  115134. });
  115135. break;
  115136. }
  115137. });
  115138. function updatePaths(property) {
  115139. // Type annotation needed due to #7294
  115140. var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
  115141. var foundExactMatch = false;
  115142. for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
  115143. var element = elements_1[_i];
  115144. foundExactMatch = tryUpdateString(element) || foundExactMatch;
  115145. }
  115146. return foundExactMatch;
  115147. }
  115148. function tryUpdateString(element) {
  115149. if (!ts.isStringLiteral(element))
  115150. return false;
  115151. var elementFileName = combinePathsSafe(configDir, element.text);
  115152. var updated = oldToNew(elementFileName);
  115153. if (updated !== undefined) {
  115154. changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated));
  115155. return true;
  115156. }
  115157. return false;
  115158. }
  115159. function relativePath(path) {
  115160. return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames);
  115161. }
  115162. }
  115163. function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
  115164. var allFiles = program.getSourceFiles();
  115165. var _loop_4 = function (sourceFile) {
  115166. var newFromOld = oldToNew(sourceFile.path);
  115167. var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
  115168. var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
  115169. var oldFromNew = newToOld(sourceFile.fileName);
  115170. var oldImportFromPath = oldFromNew || sourceFile.fileName;
  115171. var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath);
  115172. var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined;
  115173. updateImportsWorker(sourceFile, changeTracker, function (referenceText) {
  115174. if (!ts.pathIsRelative(referenceText))
  115175. return undefined;
  115176. var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText);
  115177. var newAbsolute = oldToNew(oldAbsolute);
  115178. return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
  115179. }, function (importLiteral) {
  115180. var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
  115181. // No need to update if it's an ambient module^M
  115182. if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); }))
  115183. return undefined;
  115184. var toImport = oldFromNew !== undefined
  115185. // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
  115186. // TODO:GH#18217
  115187. ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles)
  115188. : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
  115189. // Need an update if the imported file moved, or the importing file moved and was using a relative path.
  115190. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
  115191. ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text)
  115192. : undefined;
  115193. });
  115194. };
  115195. for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
  115196. var sourceFile = allFiles_1[_i];
  115197. _loop_4(sourceFile);
  115198. }
  115199. }
  115200. function combineNormal(pathA, pathB) {
  115201. return ts.normalizePath(ts.combinePaths(pathA, pathB));
  115202. }
  115203. function combinePathsSafe(pathA, pathB) {
  115204. return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB));
  115205. }
  115206. function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
  115207. if (importedModuleSymbol) {
  115208. // `find` should succeed because we checked for ambient modules before calling this function.
  115209. var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName;
  115210. var newFileName = oldToNew(oldFileName);
  115211. return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true };
  115212. }
  115213. else {
  115214. var resolved = host.resolveModuleNames
  115215. ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName)
  115216. : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName);
  115217. return getSourceFileToImportFromResolved(resolved, oldToNew, program.getSourceFiles());
  115218. }
  115219. }
  115220. function getSourceFileToImportFromResolved(resolved, oldToNew, sourceFiles) {
  115221. // Search through all locations looking for a moved file, and only then test already existing files.
  115222. // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location.
  115223. if (!resolved)
  115224. return undefined;
  115225. // First try resolved module
  115226. if (resolved.resolvedModule) {
  115227. var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
  115228. if (result_2)
  115229. return result_2;
  115230. }
  115231. // Then failed lookups that are in the list of sources
  115232. var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting)
  115233. // Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
  115234. || ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
  115235. if (result)
  115236. return result;
  115237. // If nothing changed, then result is resolved module file thats not updated
  115238. return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false };
  115239. function tryChangeWithIgnoringPackageJsonExisting(oldFileName) {
  115240. var newFileName = oldToNew(oldFileName);
  115241. return newFileName && ts.find(sourceFiles, function (src) { return src.fileName === newFileName; })
  115242. ? tryChangeWithIgnoringPackageJson(oldFileName) : undefined;
  115243. }
  115244. function tryChangeWithIgnoringPackageJson(oldFileName) {
  115245. return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined;
  115246. }
  115247. function tryChange(oldFileName) {
  115248. var newFileName = oldToNew(oldFileName);
  115249. return newFileName && { newFileName: newFileName, updated: true };
  115250. }
  115251. }
  115252. function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) {
  115253. for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162
  115254. var ref = _a[_i];
  115255. var updated = updateRef(ref.fileName);
  115256. if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end))
  115257. changeTracker.replaceRangeWithText(sourceFile, ref, updated);
  115258. }
  115259. for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) {
  115260. var importStringLiteral = _c[_b];
  115261. var updated = updateImport(importStringLiteral);
  115262. if (updated !== undefined && updated !== importStringLiteral.text)
  115263. changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated);
  115264. }
  115265. }
  115266. function createStringRange(node, sourceFile) {
  115267. return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1);
  115268. }
  115269. function forEachProperty(objectLiteral, cb) {
  115270. if (!ts.isObjectLiteralExpression(objectLiteral))
  115271. return;
  115272. for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) {
  115273. var property = _a[_i];
  115274. if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) {
  115275. cb(property, property.name.text);
  115276. }
  115277. }
  115278. }
  115279. })(ts || (ts = {}));
  115280. /* @internal */
  115281. var ts;
  115282. (function (ts) {
  115283. var GoToDefinition;
  115284. (function (GoToDefinition) {
  115285. function getDefinitionAtPosition(program, sourceFile, position) {
  115286. var reference = getReferenceAtPosition(sourceFile, position, program);
  115287. if (reference) {
  115288. return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)];
  115289. }
  115290. var node = ts.getTouchingPropertyName(sourceFile, position);
  115291. if (node === sourceFile) {
  115292. return undefined;
  115293. }
  115294. var parent = node.parent;
  115295. var typeChecker = program.getTypeChecker();
  115296. // Labels
  115297. if (ts.isJumpStatementTarget(node)) {
  115298. var label = ts.getTargetLabel(node.parent, node.text);
  115299. return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217
  115300. }
  115301. var symbol = getSymbol(node, typeChecker);
  115302. // Could not find a symbol e.g. node is string or number keyword,
  115303. // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
  115304. if (!symbol) {
  115305. return getDefinitionInfoForIndexSignatures(node, typeChecker);
  115306. }
  115307. var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
  115308. // Don't go to the component constructor definition for a JSX element, just go to the component definition.
  115309. if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) {
  115310. var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
  115311. // For a function, if this is the original function definition, return just sigInfo.
  115312. // If this is the original constructor definition, parent is the class.
  115313. if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) ||
  115314. // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias
  115315. symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) {
  115316. return [sigInfo];
  115317. }
  115318. else {
  115319. var defs = getDefinitionFromSymbol(typeChecker, symbol, node, calledDeclaration) || ts.emptyArray;
  115320. // For a 'super()' call, put the signature first, else put the variable first.
  115321. return node.kind === 102 /* SuperKeyword */ ? __spreadArrays([sigInfo], defs) : __spreadArrays(defs, [sigInfo]);
  115322. }
  115323. }
  115324. // Because name in short-hand property assignment has two different meanings: property name and property value,
  115325. // using go-to-definition at such position should go to the variable declaration of the property value rather than
  115326. // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
  115327. // is performed at the location of property access, we would like to go to definition of the property in the short-hand
  115328. // assignment. This case and others are handled by the following code.
  115329. if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
  115330. var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
  115331. return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : [];
  115332. }
  115333. // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the
  115334. // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern
  115335. // and return the property declaration for the referenced property.
  115336. // For example:
  115337. // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo"
  115338. //
  115339. // function bar<T>(onfulfilled: (value: T) => void) { //....}
  115340. // interface Test {
  115341. // pr/*destination*/op1: number
  115342. // }
  115343. // bar<Test>(({pr/*goto*/op1})=>{});
  115344. if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
  115345. (node === (parent.propertyName || parent.name))) {
  115346. var name_3 = ts.getNameFromPropertyName(node);
  115347. var type = typeChecker.getTypeAtLocation(parent.parent);
  115348. return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
  115349. var prop = t.getProperty(name_3);
  115350. return prop && getDefinitionFromSymbol(typeChecker, prop, node);
  115351. });
  115352. }
  115353. // If the current location we want to find its definition is in an object literal, try to get the contextual type for the
  115354. // object literal, lookup the property symbol in the contextual type, and use this for goto-definition.
  115355. // For example
  115356. // interface Props{
  115357. // /*first*/prop1: number
  115358. // prop2: boolean
  115359. // }
  115360. // function Foo(arg: Props) {}
  115361. // Foo( { pr/*1*/op1: 10, prop2: true })
  115362. var element = ts.getContainingObjectLiteralElement(node);
  115363. if (element) {
  115364. var contextualType = element && typeChecker.getContextualType(element.parent);
  115365. if (contextualType) {
  115366. return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) {
  115367. return getDefinitionFromSymbol(typeChecker, propertySymbol, node);
  115368. });
  115369. }
  115370. }
  115371. return getDefinitionFromSymbol(typeChecker, symbol, node);
  115372. }
  115373. GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition;
  115374. /**
  115375. * True if we should not add definitions for both the signature symbol and the definition symbol.
  115376. * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`.
  115377. */
  115378. function symbolMatchesSignature(s, calledDeclaration) {
  115379. return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent ||
  115380. !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
  115381. }
  115382. function getReferenceAtPosition(sourceFile, position, program) {
  115383. var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
  115384. if (referencePath) {
  115385. var file = program.getSourceFileFromReference(sourceFile, referencePath);
  115386. return file && { fileName: referencePath.fileName, file: file };
  115387. }
  115388. var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
  115389. if (typeReferenceDirective) {
  115390. var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
  115391. var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217
  115392. return file && { fileName: typeReferenceDirective.fileName, file: file };
  115393. }
  115394. var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
  115395. if (libReferenceDirective) {
  115396. var file = program.getLibFileFromReference(libReferenceDirective);
  115397. return file && { fileName: libReferenceDirective.fileName, file: file };
  115398. }
  115399. return undefined;
  115400. }
  115401. GoToDefinition.getReferenceAtPosition = getReferenceAtPosition;
  115402. /// Goto type
  115403. function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
  115404. var node = ts.getTouchingPropertyName(sourceFile, position);
  115405. if (node === sourceFile) {
  115406. return undefined;
  115407. }
  115408. var symbol = typeChecker.getSymbolAtLocation(node);
  115409. if (!symbol)
  115410. return undefined;
  115411. var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
  115412. var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
  115413. var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node);
  115414. // If a function returns 'void' or some other type with no definition, just return the function definition.
  115415. return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node);
  115416. }
  115417. GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition;
  115418. function definitionFromType(type, checker, node) {
  115419. return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) {
  115420. return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node);
  115421. });
  115422. }
  115423. function tryGetReturnTypeOfFunction(symbol, type, checker) {
  115424. // If the type is just a function's inferred type,
  115425. // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway.
  115426. if (type.symbol === symbol ||
  115427. // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}`
  115428. symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) {
  115429. var sigs = type.getCallSignatures();
  115430. if (sigs.length === 1)
  115431. return checker.getReturnTypeOfSignature(ts.first(sigs));
  115432. }
  115433. return undefined;
  115434. }
  115435. function getDefinitionAndBoundSpan(program, sourceFile, position) {
  115436. var definitions = getDefinitionAtPosition(program, sourceFile, position);
  115437. if (!definitions || definitions.length === 0) {
  115438. return undefined;
  115439. }
  115440. // Check if position is on triple slash reference.
  115441. var comment = findReferenceInPosition(sourceFile.referencedFiles, position) ||
  115442. findReferenceInPosition(sourceFile.typeReferenceDirectives, position) ||
  115443. findReferenceInPosition(sourceFile.libReferenceDirectives, position);
  115444. if (comment) {
  115445. return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) };
  115446. }
  115447. var node = ts.getTouchingPropertyName(sourceFile, position);
  115448. var textSpan = ts.createTextSpan(node.getStart(), node.getWidth());
  115449. return { definitions: definitions, textSpan: textSpan };
  115450. }
  115451. GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan;
  115452. // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations.
  115453. function getDefinitionInfoForIndexSignatures(node, checker) {
  115454. if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node)
  115455. return;
  115456. var type = checker.getTypeAtLocation(node.parent.expression);
  115457. return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) {
  115458. var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */);
  115459. return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration);
  115460. });
  115461. }
  115462. function getSymbol(node, checker) {
  115463. var symbol = checker.getSymbolAtLocation(node);
  115464. // If this is an alias, and the request came at the declaration location
  115465. // get the aliased symbol instead. This allows for goto def on an import e.g.
  115466. // import {A, B} from "mod";
  115467. // to jump to the implementation directly.
  115468. if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) {
  115469. var aliased = checker.getAliasedSymbol(symbol);
  115470. if (aliased.declarations) {
  115471. return aliased;
  115472. }
  115473. }
  115474. if (symbol && ts.isInJSFile(node)) {
  115475. var requireCall = ts.forEach(symbol.declarations, function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true) ? d.initializer : undefined; });
  115476. if (requireCall) {
  115477. var moduleSymbol = checker.getSymbolAtLocation(requireCall.arguments[0]);
  115478. if (moduleSymbol) {
  115479. return checker.resolveExternalModuleSymbol(moduleSymbol);
  115480. }
  115481. }
  115482. }
  115483. return symbol;
  115484. }
  115485. // Go to the original declaration for cases:
  115486. //
  115487. // (1) when the aliased symbol was declared in the location(parent).
  115488. // (2) when the aliased symbol is originating from an import.
  115489. //
  115490. function shouldSkipAlias(node, declaration) {
  115491. if (node.kind !== 75 /* Identifier */) {
  115492. return false;
  115493. }
  115494. if (node.parent === declaration) {
  115495. return true;
  115496. }
  115497. switch (declaration.kind) {
  115498. case 255 /* ImportClause */:
  115499. case 253 /* ImportEqualsDeclaration */:
  115500. return true;
  115501. case 258 /* ImportSpecifier */:
  115502. return declaration.parent.kind === 257 /* NamedImports */;
  115503. default:
  115504. return false;
  115505. }
  115506. }
  115507. function getDefinitionFromSymbol(typeChecker, symbol, node, declarationNode) {
  115508. // There are cases when you extend a function by adding properties to it afterwards,
  115509. // we want to strip those extra properties.
  115510. // For deduping purposes, we also want to exclude any declarationNodes if provided.
  115511. var filteredDeclarations = ts.filter(symbol.declarations, function (d) { return d !== declarationNode && (!ts.isAssignmentDeclaration(d) || d === symbol.valueDeclaration); }) || undefined;
  115512. return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(filteredDeclarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); });
  115513. function getConstructSignatureDefinition() {
  115514. // Applicable only if we are in a new expression, or we are on a constructor declaration
  115515. // and in either case the symbol has a construct signature definition, i.e. class
  115516. if (symbol.flags & 32 /* Class */ && !(symbol.flags & 16 /* Function */) && (ts.isNewExpressionTarget(node) || node.kind === 129 /* ConstructorKeyword */)) {
  115517. var cls = ts.find(filteredDeclarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration");
  115518. return getSignatureDefinition(cls.members, /*selectConstructors*/ true);
  115519. }
  115520. }
  115521. function getCallSignatureDefinition() {
  115522. return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node)
  115523. ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ false)
  115524. : undefined;
  115525. }
  115526. function getSignatureDefinition(signatureDeclarations, selectConstructors) {
  115527. if (!signatureDeclarations) {
  115528. return undefined;
  115529. }
  115530. var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike);
  115531. var declarationsWithBody = declarations.filter(function (d) { return !!d.body; });
  115532. // declarations defined on the global scope can be defined on multiple files. Get all of them.
  115533. return declarations.length
  115534. ? declarationsWithBody.length !== 0
  115535. ? declarationsWithBody.map(function (x) { return createDefinitionInfo(x, typeChecker, symbol, node); })
  115536. : [createDefinitionInfo(ts.last(declarations), typeChecker, symbol, node)]
  115537. : undefined;
  115538. }
  115539. }
  115540. /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
  115541. function createDefinitionInfo(declaration, checker, symbol, node) {
  115542. var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
  115543. var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node);
  115544. var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : "";
  115545. return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName, containerName);
  115546. }
  115547. /** Creates a DefinitionInfo directly from the name of a declaration. */
  115548. function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName, containerName) {
  115549. var name = ts.getNameOfDeclaration(declaration) || declaration;
  115550. var sourceFile = name.getSourceFile();
  115551. var textSpan = ts.createTextSpanFromNode(name, sourceFile);
  115552. return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217
  115553. containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) });
  115554. }
  115555. function createDefinitionFromSignatureDeclaration(typeChecker, decl) {
  115556. return createDefinitionInfo(decl, typeChecker, decl.symbol, decl);
  115557. }
  115558. function findReferenceInPosition(refs, pos) {
  115559. return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); });
  115560. }
  115561. GoToDefinition.findReferenceInPosition = findReferenceInPosition;
  115562. function getDefinitionInfoForFileReference(name, targetFileName) {
  115563. return {
  115564. fileName: targetFileName,
  115565. textSpan: ts.createTextSpanFromBounds(0, 0),
  115566. kind: "script" /* scriptElement */,
  115567. name: name,
  115568. containerName: undefined,
  115569. containerKind: undefined,
  115570. };
  115571. }
  115572. /** Returns a CallLikeExpression where `node` is the target being invoked. */
  115573. function getAncestorCallLikeExpression(node) {
  115574. var target = climbPastManyPropertyAccesses(node);
  115575. var callLike = target.parent;
  115576. return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined;
  115577. }
  115578. function climbPastManyPropertyAccesses(node) {
  115579. return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node;
  115580. }
  115581. function tryGetSignatureDeclaration(typeChecker, node) {
  115582. var callLike = getAncestorCallLikeExpression(node);
  115583. var signature = callLike && typeChecker.getResolvedSignature(callLike);
  115584. // Don't go to a function type, go to the value having that type.
  115585. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); });
  115586. }
  115587. function isConstructorLike(node) {
  115588. switch (node.kind) {
  115589. case 162 /* Constructor */:
  115590. case 171 /* ConstructorType */:
  115591. case 166 /* ConstructSignature */:
  115592. return true;
  115593. default:
  115594. return false;
  115595. }
  115596. }
  115597. })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
  115598. })(ts || (ts = {}));
  115599. /* @internal */
  115600. var ts;
  115601. (function (ts) {
  115602. var JsDoc;
  115603. (function (JsDoc) {
  115604. var jsDocTagNames = [
  115605. "abstract",
  115606. "access",
  115607. "alias",
  115608. "argument",
  115609. "async",
  115610. "augments",
  115611. "author",
  115612. "borrows",
  115613. "callback",
  115614. "class",
  115615. "classdesc",
  115616. "constant",
  115617. "constructor",
  115618. "constructs",
  115619. "copyright",
  115620. "default",
  115621. "deprecated",
  115622. "description",
  115623. "emits",
  115624. "enum",
  115625. "event",
  115626. "example",
  115627. "exports",
  115628. "extends",
  115629. "external",
  115630. "field",
  115631. "file",
  115632. "fileoverview",
  115633. "fires",
  115634. "function",
  115635. "generator",
  115636. "global",
  115637. "hideconstructor",
  115638. "host",
  115639. "ignore",
  115640. "implements",
  115641. "inheritdoc",
  115642. "inner",
  115643. "instance",
  115644. "interface",
  115645. "kind",
  115646. "lends",
  115647. "license",
  115648. "listens",
  115649. "member",
  115650. "memberof",
  115651. "method",
  115652. "mixes",
  115653. "module",
  115654. "name",
  115655. "namespace",
  115656. "override",
  115657. "package",
  115658. "param",
  115659. "private",
  115660. "property",
  115661. "protected",
  115662. "public",
  115663. "readonly",
  115664. "requires",
  115665. "returns",
  115666. "see",
  115667. "since",
  115668. "static",
  115669. "summary",
  115670. "template",
  115671. "this",
  115672. "throws",
  115673. "todo",
  115674. "tutorial",
  115675. "type",
  115676. "typedef",
  115677. "var",
  115678. "variation",
  115679. "version",
  115680. "virtual",
  115681. "yields"
  115682. ];
  115683. var jsDocTagNameCompletionEntries;
  115684. var jsDocTagCompletionEntries;
  115685. function getJsDocCommentsFromDeclarations(declarations) {
  115686. // Only collect doc comments from duplicate declarations once:
  115687. // In case of a union property there might be same declaration multiple times
  115688. // which only varies in type parameter
  115689. // Eg. const a: Array<string> | Array<number>; a.length
  115690. // The property length will have two declarations of property length coming
  115691. // from Array<T> - Array<string> and Array<number>
  115692. var documentationComment = [];
  115693. ts.forEachUnique(declarations, function (declaration) {
  115694. for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) {
  115695. var comment = _a[_i].comment;
  115696. if (comment === undefined)
  115697. continue;
  115698. if (documentationComment.length) {
  115699. documentationComment.push(ts.lineBreakPart());
  115700. }
  115701. documentationComment.push(ts.textPart(comment));
  115702. }
  115703. });
  115704. return documentationComment;
  115705. }
  115706. JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
  115707. function getCommentHavingNodes(declaration) {
  115708. switch (declaration.kind) {
  115709. case 316 /* JSDocParameterTag */:
  115710. case 322 /* JSDocPropertyTag */:
  115711. return [declaration];
  115712. case 314 /* JSDocCallbackTag */:
  115713. case 321 /* JSDocTypedefTag */:
  115714. return [declaration, declaration.parent];
  115715. default:
  115716. return ts.getJSDocCommentsAndTags(declaration);
  115717. }
  115718. }
  115719. function getJsDocTagsFromDeclarations(declarations) {
  115720. // Only collect doc comments from duplicate declarations once.
  115721. var tags = [];
  115722. ts.forEachUnique(declarations, function (declaration) {
  115723. for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) {
  115724. var tag = _a[_i];
  115725. tags.push({ name: tag.tagName.text, text: getCommentText(tag) });
  115726. }
  115727. });
  115728. return tags;
  115729. }
  115730. JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations;
  115731. function getCommentText(tag) {
  115732. var comment = tag.comment;
  115733. switch (tag.kind) {
  115734. case 307 /* JSDocAugmentsTag */:
  115735. return withNode(tag.class);
  115736. case 320 /* JSDocTemplateTag */:
  115737. return withList(tag.typeParameters);
  115738. case 319 /* JSDocTypeTag */:
  115739. return withNode(tag.typeExpression);
  115740. case 321 /* JSDocTypedefTag */:
  115741. case 314 /* JSDocCallbackTag */:
  115742. case 322 /* JSDocPropertyTag */:
  115743. case 316 /* JSDocParameterTag */:
  115744. var name = tag.name;
  115745. return name ? withNode(name) : comment;
  115746. default:
  115747. return comment;
  115748. }
  115749. function withNode(node) {
  115750. return addComment(node.getText());
  115751. }
  115752. function withList(list) {
  115753. return addComment(list.map(function (x) { return x.getText(); }).join(", "));
  115754. }
  115755. function addComment(s) {
  115756. return comment === undefined ? s : s + " " + comment;
  115757. }
  115758. }
  115759. function getJSDocTagNameCompletions() {
  115760. return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
  115761. return {
  115762. name: tagName,
  115763. kind: "keyword" /* keyword */,
  115764. kindModifiers: "",
  115765. sortText: "0",
  115766. };
  115767. }));
  115768. }
  115769. JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions;
  115770. JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
  115771. function getJSDocTagCompletions() {
  115772. return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
  115773. return {
  115774. name: "@" + tagName,
  115775. kind: "keyword" /* keyword */,
  115776. kindModifiers: "",
  115777. sortText: "0"
  115778. };
  115779. }));
  115780. }
  115781. JsDoc.getJSDocTagCompletions = getJSDocTagCompletions;
  115782. function getJSDocTagCompletionDetails(name) {
  115783. return {
  115784. name: name,
  115785. kind: "" /* unknown */,
  115786. kindModifiers: "",
  115787. displayParts: [ts.textPart(name)],
  115788. documentation: ts.emptyArray,
  115789. tags: undefined,
  115790. codeActions: undefined,
  115791. };
  115792. }
  115793. JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails;
  115794. function getJSDocParameterNameCompletions(tag) {
  115795. if (!ts.isIdentifier(tag.name)) {
  115796. return ts.emptyArray;
  115797. }
  115798. var nameThusFar = tag.name.text;
  115799. var jsdoc = tag.parent;
  115800. var fn = jsdoc.parent;
  115801. if (!ts.isFunctionLike(fn))
  115802. return [];
  115803. return ts.mapDefined(fn.parameters, function (param) {
  115804. if (!ts.isIdentifier(param.name))
  115805. return undefined;
  115806. var name = param.name.text;
  115807. if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217
  115808. || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) {
  115809. return undefined;
  115810. }
  115811. return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" };
  115812. });
  115813. }
  115814. JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions;
  115815. function getJSDocParameterNameCompletionDetails(name) {
  115816. return {
  115817. name: name,
  115818. kind: "parameter" /* parameterElement */,
  115819. kindModifiers: "",
  115820. displayParts: [ts.textPart(name)],
  115821. documentation: ts.emptyArray,
  115822. tags: undefined,
  115823. codeActions: undefined,
  115824. };
  115825. }
  115826. JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails;
  115827. /**
  115828. * Checks if position points to a valid position to add JSDoc comments, and if so,
  115829. * returns the appropriate template. Otherwise returns an empty string.
  115830. * Valid positions are
  115831. * - outside of comments, statements, and expressions, and
  115832. * - preceding a:
  115833. * - function/constructor/method declaration
  115834. * - class declarations
  115835. * - variable statements
  115836. * - namespace declarations
  115837. * - interface declarations
  115838. * - method signatures
  115839. * - type alias declarations
  115840. *
  115841. * Hosts should ideally check that:
  115842. * - The line is all whitespace up to 'position' before performing the insertion.
  115843. * - If the keystroke sequence "/\*\*" induced the call, we also check that the next
  115844. * non-whitespace character is '*', which (approximately) indicates whether we added
  115845. * the second '*' to complete an existing (JSDoc) comment.
  115846. * @param fileName The file in which to perform the check.
  115847. * @param position The (character-indexed) position in the file where the check should
  115848. * be performed.
  115849. */
  115850. function getDocCommentTemplateAtPosition(newLine, sourceFile, position) {
  115851. var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
  115852. var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc);
  115853. if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) {
  115854. // Non-empty comment already exists.
  115855. return undefined;
  115856. }
  115857. var tokenStart = tokenAtPos.getStart(sourceFile);
  115858. // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.)
  115859. if (!existingDocComment && tokenStart < position) {
  115860. return undefined;
  115861. }
  115862. var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos);
  115863. if (!commentOwnerInfo) {
  115864. return undefined;
  115865. }
  115866. var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters;
  115867. if (commentOwner.getStart(sourceFile) < position) {
  115868. return undefined;
  115869. }
  115870. if (!parameters || parameters.length === 0) {
  115871. // if there are no parameters, just complete to a single line JSDoc comment
  115872. var singleLineResult = "/** */";
  115873. return { newText: singleLineResult, caretOffset: 3 };
  115874. }
  115875. var indentationStr = getIndentationStringAtPosition(sourceFile, position);
  115876. // A doc comment consists of the following
  115877. // * The opening comment line
  115878. // * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
  115879. // * the '@param'-tagged lines
  115880. // * TODO: other tags.
  115881. // * the closing comment line
  115882. // * if the caret was directly in front of the object, then we add an extra line and indentation.
  115883. var preamble = "/**" + newLine + indentationStr + " * ";
  115884. var result = preamble + newLine +
  115885. parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) +
  115886. indentationStr + " */" +
  115887. (tokenStart === position ? newLine + indentationStr : "");
  115888. return { newText: result, caretOffset: preamble.length };
  115889. }
  115890. JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition;
  115891. function getIndentationStringAtPosition(sourceFile, position) {
  115892. var text = sourceFile.text;
  115893. var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
  115894. var pos = lineStart;
  115895. for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++)
  115896. ;
  115897. return text.slice(lineStart, pos);
  115898. }
  115899. function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
  115900. return parameters.map(function (_a, i) {
  115901. var name = _a.name, dotDotDotToken = _a.dotDotDotToken;
  115902. var paramName = name.kind === 75 /* Identifier */ ? name.text : "param" + i;
  115903. var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : "";
  115904. return indentationStr + " * @param " + type + paramName + newLine;
  115905. }).join("");
  115906. }
  115907. function getCommentOwnerInfo(tokenAtPos) {
  115908. return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker);
  115909. }
  115910. function getCommentOwnerInfoWorker(commentOwner) {
  115911. switch (commentOwner.kind) {
  115912. case 244 /* FunctionDeclaration */:
  115913. case 201 /* FunctionExpression */:
  115914. case 161 /* MethodDeclaration */:
  115915. case 162 /* Constructor */:
  115916. case 160 /* MethodSignature */:
  115917. var parameters = commentOwner.parameters;
  115918. return { commentOwner: commentOwner, parameters: parameters };
  115919. case 281 /* PropertyAssignment */:
  115920. return getCommentOwnerInfoWorker(commentOwner.initializer);
  115921. case 245 /* ClassDeclaration */:
  115922. case 246 /* InterfaceDeclaration */:
  115923. case 158 /* PropertySignature */:
  115924. case 248 /* EnumDeclaration */:
  115925. case 284 /* EnumMember */:
  115926. case 247 /* TypeAliasDeclaration */:
  115927. return { commentOwner: commentOwner };
  115928. case 225 /* VariableStatement */: {
  115929. var varStatement = commentOwner;
  115930. var varDeclarations = varStatement.declarationList.declarations;
  115931. var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
  115932. ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer)
  115933. : undefined;
  115934. return { commentOwner: commentOwner, parameters: parameters_1 };
  115935. }
  115936. case 290 /* SourceFile */:
  115937. return "quit";
  115938. case 249 /* ModuleDeclaration */:
  115939. // If in walking up the tree, we hit a a nested namespace declaration,
  115940. // then we must be somewhere within a dotted namespace name; however we don't
  115941. // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
  115942. return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
  115943. case 209 /* BinaryExpression */: {
  115944. var be = commentOwner;
  115945. if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) {
  115946. return "quit";
  115947. }
  115948. var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray;
  115949. return { commentOwner: commentOwner, parameters: parameters_2 };
  115950. }
  115951. }
  115952. }
  115953. /**
  115954. * Digs into an an initializer or RHS operand of an assignment operation
  115955. * to get the parameters of an apt signature corresponding to a
  115956. * function expression or a class expression.
  115957. *
  115958. * @param rightHandSide the expression which may contain an appropriate set of parameters
  115959. * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
  115960. */
  115961. function getParametersFromRightHandSideOfAssignment(rightHandSide) {
  115962. while (rightHandSide.kind === 200 /* ParenthesizedExpression */) {
  115963. rightHandSide = rightHandSide.expression;
  115964. }
  115965. switch (rightHandSide.kind) {
  115966. case 201 /* FunctionExpression */:
  115967. case 202 /* ArrowFunction */:
  115968. return rightHandSide.parameters;
  115969. case 214 /* ClassExpression */: {
  115970. var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration);
  115971. return ctr ? ctr.parameters : ts.emptyArray;
  115972. }
  115973. }
  115974. return ts.emptyArray;
  115975. }
  115976. })(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
  115977. })(ts || (ts = {}));
  115978. /* @internal */
  115979. var ts;
  115980. (function (ts) {
  115981. var NavigateTo;
  115982. (function (NavigateTo) {
  115983. function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
  115984. var patternMatcher = ts.createPatternMatcher(searchValue);
  115985. if (!patternMatcher)
  115986. return ts.emptyArray;
  115987. var rawItems = [];
  115988. var _loop_5 = function (sourceFile) {
  115989. cancellationToken.throwIfCancellationRequested();
  115990. if (excludeDtsFiles && sourceFile.isDeclarationFile) {
  115991. return "continue";
  115992. }
  115993. sourceFile.getNamedDeclarations().forEach(function (declarations, name) {
  115994. getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems);
  115995. });
  115996. };
  115997. // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
  115998. for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
  115999. var sourceFile = sourceFiles_4[_i];
  116000. _loop_5(sourceFile);
  116001. }
  116002. rawItems.sort(compareNavigateToItems);
  116003. return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
  116004. }
  116005. NavigateTo.getNavigateToItems = getNavigateToItems;
  116006. function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) {
  116007. // First do a quick check to see if the name of the declaration matches the
  116008. // last portion of the (possibly) dotted name they're searching for.
  116009. var match = patternMatcher.getMatchForLastSegmentOfPattern(name);
  116010. if (!match) {
  116011. return; // continue to next named declarations
  116012. }
  116013. for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
  116014. var declaration = declarations_3[_i];
  116015. if (!shouldKeepItem(declaration, checker))
  116016. continue;
  116017. if (patternMatcher.patternContainsDots) {
  116018. // If the pattern has dots in it, then also see if the declaration container matches as well.
  116019. var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
  116020. if (fullMatch) {
  116021. rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration });
  116022. }
  116023. }
  116024. else {
  116025. rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration });
  116026. }
  116027. }
  116028. }
  116029. function shouldKeepItem(declaration, checker) {
  116030. switch (declaration.kind) {
  116031. case 255 /* ImportClause */:
  116032. case 258 /* ImportSpecifier */:
  116033. case 253 /* ImportEqualsDeclaration */:
  116034. var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217
  116035. var imported = checker.getAliasedSymbol(importer);
  116036. return importer.escapedName !== imported.escapedName;
  116037. default:
  116038. return true;
  116039. }
  116040. }
  116041. function tryAddSingleDeclarationName(declaration, containers) {
  116042. var name = ts.getNameOfDeclaration(declaration);
  116043. return !!name && (pushLiteral(name, containers) || name.kind === 154 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers));
  116044. }
  116045. // Only added the names of computed properties if they're simple dotted expressions, like:
  116046. //
  116047. // [X.Y.Z]() { }
  116048. function tryAddComputedPropertyName(expression, containers) {
  116049. return pushLiteral(expression, containers)
  116050. || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers);
  116051. }
  116052. function pushLiteral(node, containers) {
  116053. return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true);
  116054. }
  116055. function getContainers(declaration) {
  116056. var containers = [];
  116057. // First, if we started with a computed property name, then add all but the last
  116058. // portion into the container array.
  116059. var name = ts.getNameOfDeclaration(declaration);
  116060. if (name && name.kind === 154 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) {
  116061. return ts.emptyArray;
  116062. }
  116063. // Don't include the last portion.
  116064. containers.shift();
  116065. // Now, walk up our containers, adding all their names to the container array.
  116066. var container = ts.getContainerNode(declaration);
  116067. while (container) {
  116068. if (!tryAddSingleDeclarationName(container, containers)) {
  116069. return ts.emptyArray;
  116070. }
  116071. container = ts.getContainerNode(container);
  116072. }
  116073. return containers.reverse();
  116074. }
  116075. function compareNavigateToItems(i1, i2) {
  116076. // TODO(cyrusn): get the gamut of comparisons that VS already uses here.
  116077. return ts.compareValues(i1.matchKind, i2.matchKind)
  116078. || ts.compareStringsCaseSensitiveUI(i1.name, i2.name);
  116079. }
  116080. function createNavigateToItem(rawItem) {
  116081. var declaration = rawItem.declaration;
  116082. var container = ts.getContainerNode(declaration);
  116083. var containerName = container && ts.getNameOfDeclaration(container);
  116084. return {
  116085. name: rawItem.name,
  116086. kind: ts.getNodeKind(declaration),
  116087. kindModifiers: ts.getNodeModifiers(declaration),
  116088. matchKind: ts.PatternMatchKind[rawItem.matchKind],
  116089. isCaseSensitive: rawItem.isCaseSensitive,
  116090. fileName: rawItem.fileName,
  116091. textSpan: ts.createTextSpanFromNode(declaration),
  116092. // TODO(jfreeman): What should be the containerName when the container has a computed name?
  116093. containerName: containerName ? containerName.text : "",
  116094. containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */,
  116095. };
  116096. }
  116097. })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {}));
  116098. })(ts || (ts = {}));
  116099. /* @internal */
  116100. var ts;
  116101. (function (ts) {
  116102. var NavigationBar;
  116103. (function (NavigationBar) {
  116104. var _a;
  116105. /**
  116106. * Matches all whitespace characters in a string. Eg:
  116107. *
  116108. * "app.
  116109. *
  116110. * onactivated"
  116111. *
  116112. * matches because of the newline, whereas
  116113. *
  116114. * "app.onactivated"
  116115. *
  116116. * does not match.
  116117. */
  116118. var whiteSpaceRegex = /\s+/g;
  116119. /**
  116120. * Maximum amount of characters to return
  116121. * The amount was chosen arbitrarily.
  116122. */
  116123. var maxLength = 150;
  116124. // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
  116125. var curCancellationToken;
  116126. var curSourceFile;
  116127. /**
  116128. * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion.
  116129. * `parent` is the current parent and is *not* stored in parentsStack.
  116130. * `startNode` sets a new parent and `endNode` returns to the previous parent.
  116131. */
  116132. var parentsStack = [];
  116133. var parent;
  116134. var trackedEs5ClassesStack = [];
  116135. var trackedEs5Classes;
  116136. // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
  116137. var emptyChildItemArray = [];
  116138. function getNavigationBarItems(sourceFile, cancellationToken) {
  116139. curCancellationToken = cancellationToken;
  116140. curSourceFile = sourceFile;
  116141. try {
  116142. return ts.map(primaryNavBarMenuItems(rootNavigationBarNode(sourceFile)), convertToPrimaryNavBarMenuItem);
  116143. }
  116144. finally {
  116145. reset();
  116146. }
  116147. }
  116148. NavigationBar.getNavigationBarItems = getNavigationBarItems;
  116149. function getNavigationTree(sourceFile, cancellationToken) {
  116150. curCancellationToken = cancellationToken;
  116151. curSourceFile = sourceFile;
  116152. try {
  116153. return convertToTree(rootNavigationBarNode(sourceFile));
  116154. }
  116155. finally {
  116156. reset();
  116157. }
  116158. }
  116159. NavigationBar.getNavigationTree = getNavigationTree;
  116160. function reset() {
  116161. curSourceFile = undefined;
  116162. curCancellationToken = undefined;
  116163. parentsStack = [];
  116164. parent = undefined;
  116165. emptyChildItemArray = [];
  116166. }
  116167. function nodeText(node) {
  116168. return cleanText(node.getText(curSourceFile));
  116169. }
  116170. function navigationBarNodeKind(n) {
  116171. return n.node.kind;
  116172. }
  116173. function pushChild(parent, child) {
  116174. if (parent.children) {
  116175. parent.children.push(child);
  116176. }
  116177. else {
  116178. parent.children = [child];
  116179. }
  116180. }
  116181. function rootNavigationBarNode(sourceFile) {
  116182. ts.Debug.assert(!parentsStack.length);
  116183. var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 };
  116184. parent = root;
  116185. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  116186. var statement = _a[_i];
  116187. addChildrenRecursively(statement);
  116188. }
  116189. endNode();
  116190. ts.Debug.assert(!parent && !parentsStack.length);
  116191. return root;
  116192. }
  116193. function addLeafNode(node, name) {
  116194. pushChild(parent, emptyNavigationBarNode(node, name));
  116195. }
  116196. function emptyNavigationBarNode(node, name) {
  116197. return {
  116198. node: node,
  116199. name: name || (ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined),
  116200. additionalNodes: undefined,
  116201. parent: parent,
  116202. children: undefined,
  116203. indent: parent.indent + 1
  116204. };
  116205. }
  116206. function addTrackedEs5Class(name) {
  116207. if (!trackedEs5Classes) {
  116208. trackedEs5Classes = ts.createMap();
  116209. }
  116210. trackedEs5Classes.set(name, true);
  116211. }
  116212. function endNestedNodes(depth) {
  116213. for (var i = 0; i < depth; i++)
  116214. endNode();
  116215. }
  116216. function startNestedNodes(targetNode, entityName) {
  116217. var names = [];
  116218. while (!ts.isPropertyNameLiteral(entityName)) {
  116219. var name = ts.getNameOrArgument(entityName);
  116220. var nameText = ts.getElementOrPropertyAccessName(entityName);
  116221. entityName = entityName.expression;
  116222. if (nameText === "prototype" || ts.isPrivateIdentifier(name))
  116223. continue;
  116224. names.push(name);
  116225. }
  116226. names.push(entityName);
  116227. for (var i = names.length - 1; i > 0; i--) {
  116228. var name = names[i];
  116229. startNode(targetNode, name);
  116230. }
  116231. return [names.length - 1, names[0]];
  116232. }
  116233. /**
  116234. * Add a new level of NavigationBarNodes.
  116235. * This pushes to the stack, so you must call `endNode` when you are done adding to this node.
  116236. */
  116237. function startNode(node, name) {
  116238. var navNode = emptyNavigationBarNode(node, name);
  116239. pushChild(parent, navNode);
  116240. // Save the old parent
  116241. parentsStack.push(parent);
  116242. trackedEs5ClassesStack.push(trackedEs5Classes);
  116243. parent = navNode;
  116244. }
  116245. /** Call after calling `startNode` and adding children to it. */
  116246. function endNode() {
  116247. if (parent.children) {
  116248. mergeChildren(parent.children, parent);
  116249. sortChildren(parent.children);
  116250. }
  116251. parent = parentsStack.pop();
  116252. trackedEs5Classes = trackedEs5ClassesStack.pop();
  116253. }
  116254. function addNodeWithRecursiveChild(node, child, name) {
  116255. startNode(node, name);
  116256. addChildrenRecursively(child);
  116257. endNode();
  116258. }
  116259. /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */
  116260. function addChildrenRecursively(node) {
  116261. var _a;
  116262. curCancellationToken.throwIfCancellationRequested();
  116263. if (!node || ts.isToken(node)) {
  116264. return;
  116265. }
  116266. switch (node.kind) {
  116267. case 162 /* Constructor */:
  116268. // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it.
  116269. var ctr = node;
  116270. addNodeWithRecursiveChild(ctr, ctr.body);
  116271. // Parameter properties are children of the class, not the constructor.
  116272. for (var _i = 0, _b = ctr.parameters; _i < _b.length; _i++) {
  116273. var param = _b[_i];
  116274. if (ts.isParameterPropertyDeclaration(param, ctr)) {
  116275. addLeafNode(param);
  116276. }
  116277. }
  116278. break;
  116279. case 161 /* MethodDeclaration */:
  116280. case 163 /* GetAccessor */:
  116281. case 164 /* SetAccessor */:
  116282. case 160 /* MethodSignature */:
  116283. if (!ts.hasDynamicName(node)) {
  116284. addNodeWithRecursiveChild(node, node.body);
  116285. }
  116286. break;
  116287. case 159 /* PropertyDeclaration */:
  116288. case 158 /* PropertySignature */:
  116289. if (!ts.hasDynamicName(node)) {
  116290. addLeafNode(node);
  116291. }
  116292. break;
  116293. case 255 /* ImportClause */:
  116294. var importClause = node;
  116295. // Handle default import case e.g.:
  116296. // import d from "mod";
  116297. if (importClause.name) {
  116298. addLeafNode(importClause.name);
  116299. }
  116300. // Handle named bindings in imports e.g.:
  116301. // import * as NS from "mod";
  116302. // import {a, b as B} from "mod";
  116303. var namedBindings = importClause.namedBindings;
  116304. if (namedBindings) {
  116305. if (namedBindings.kind === 256 /* NamespaceImport */) {
  116306. addLeafNode(namedBindings);
  116307. }
  116308. else {
  116309. for (var _c = 0, _d = namedBindings.elements; _c < _d.length; _c++) {
  116310. var element = _d[_c];
  116311. addLeafNode(element);
  116312. }
  116313. }
  116314. }
  116315. break;
  116316. case 282 /* ShorthandPropertyAssignment */:
  116317. addNodeWithRecursiveChild(node, node.name);
  116318. break;
  116319. case 283 /* SpreadAssignment */:
  116320. var expression = node.expression;
  116321. // Use the expression as the name of the SpreadAssignment, otherwise show as <unknown>.
  116322. ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node);
  116323. break;
  116324. case 191 /* BindingElement */:
  116325. case 281 /* PropertyAssignment */:
  116326. case 242 /* VariableDeclaration */:
  116327. var _e = node, name = _e.name, initializer = _e.initializer;
  116328. if (ts.isBindingPattern(name)) {
  116329. addChildrenRecursively(name);
  116330. }
  116331. else if (initializer && isFunctionOrClassExpression(initializer)) {
  116332. // Add a node for the VariableDeclaration, but not for the initializer.
  116333. startNode(node);
  116334. ts.forEachChild(initializer, addChildrenRecursively);
  116335. endNode();
  116336. }
  116337. else {
  116338. addNodeWithRecursiveChild(node, initializer);
  116339. }
  116340. break;
  116341. case 244 /* FunctionDeclaration */:
  116342. var nameNode = node.name;
  116343. // If we see a function declaration track as a possible ES5 class
  116344. if (nameNode && ts.isIdentifier(nameNode)) {
  116345. addTrackedEs5Class(nameNode.text);
  116346. }
  116347. addNodeWithRecursiveChild(node, node.body);
  116348. break;
  116349. case 202 /* ArrowFunction */:
  116350. case 201 /* FunctionExpression */:
  116351. addNodeWithRecursiveChild(node, node.body);
  116352. break;
  116353. case 248 /* EnumDeclaration */:
  116354. startNode(node);
  116355. for (var _f = 0, _g = node.members; _f < _g.length; _f++) {
  116356. var member = _g[_f];
  116357. if (!isComputedProperty(member)) {
  116358. addLeafNode(member);
  116359. }
  116360. }
  116361. endNode();
  116362. break;
  116363. case 245 /* ClassDeclaration */:
  116364. case 214 /* ClassExpression */:
  116365. case 246 /* InterfaceDeclaration */:
  116366. startNode(node);
  116367. for (var _h = 0, _j = node.members; _h < _j.length; _h++) {
  116368. var member = _j[_h];
  116369. addChildrenRecursively(member);
  116370. }
  116371. endNode();
  116372. break;
  116373. case 249 /* ModuleDeclaration */:
  116374. addNodeWithRecursiveChild(node, getInteriorModule(node).body);
  116375. break;
  116376. case 259 /* ExportAssignment */:
  116377. case 263 /* ExportSpecifier */:
  116378. case 253 /* ImportEqualsDeclaration */:
  116379. case 167 /* IndexSignature */:
  116380. case 165 /* CallSignature */:
  116381. case 166 /* ConstructSignature */:
  116382. case 247 /* TypeAliasDeclaration */:
  116383. addLeafNode(node);
  116384. break;
  116385. case 196 /* CallExpression */:
  116386. case 209 /* BinaryExpression */: {
  116387. var special = ts.getAssignmentDeclarationKind(node);
  116388. switch (special) {
  116389. case 1 /* ExportsProperty */:
  116390. case 2 /* ModuleExports */:
  116391. addNodeWithRecursiveChild(node, node.right);
  116392. return;
  116393. case 6 /* Prototype */:
  116394. case 3 /* PrototypeProperty */: {
  116395. var binaryExpression = node;
  116396. var assignmentTarget = binaryExpression.left;
  116397. var prototypeAccess = special === 3 /* PrototypeProperty */ ?
  116398. assignmentTarget.expression :
  116399. assignmentTarget;
  116400. var depth = 0;
  116401. var className = void 0;
  116402. // If we see a prototype assignment, start tracking the target as a class
  116403. // This is only done for simple classes not nested assignments.
  116404. if (ts.isIdentifier(prototypeAccess.expression)) {
  116405. addTrackedEs5Class(prototypeAccess.expression.text);
  116406. className = prototypeAccess.expression;
  116407. }
  116408. else {
  116409. _a = startNestedNodes(binaryExpression, prototypeAccess.expression), depth = _a[0], className = _a[1];
  116410. }
  116411. if (special === 6 /* Prototype */) {
  116412. if (ts.isObjectLiteralExpression(binaryExpression.right)) {
  116413. if (binaryExpression.right.properties.length > 0) {
  116414. startNode(binaryExpression, className);
  116415. ts.forEachChild(binaryExpression.right, addChildrenRecursively);
  116416. endNode();
  116417. }
  116418. }
  116419. }
  116420. else if (ts.isFunctionExpression(binaryExpression.right) || ts.isArrowFunction(binaryExpression.right)) {
  116421. addNodeWithRecursiveChild(node, binaryExpression.right, className);
  116422. }
  116423. else {
  116424. startNode(binaryExpression, className);
  116425. addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name);
  116426. endNode();
  116427. }
  116428. endNestedNodes(depth);
  116429. return;
  116430. }
  116431. case 7 /* ObjectDefinePropertyValue */:
  116432. case 9 /* ObjectDefinePrototypeProperty */: {
  116433. var defineCall = node;
  116434. var className = special === 7 /* ObjectDefinePropertyValue */ ?
  116435. defineCall.arguments[0] :
  116436. defineCall.arguments[0].expression;
  116437. var memberName = defineCall.arguments[1];
  116438. var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1];
  116439. startNode(node, classNameIdentifier);
  116440. startNode(node, ts.setTextRange(ts.createIdentifier(memberName.text), memberName));
  116441. addChildrenRecursively(node.arguments[2]);
  116442. endNode();
  116443. endNode();
  116444. endNestedNodes(depth);
  116445. return;
  116446. }
  116447. case 5 /* Property */: {
  116448. var binaryExpression = node;
  116449. var assignmentTarget = binaryExpression.left;
  116450. var targetFunction = assignmentTarget.expression;
  116451. if (ts.isIdentifier(targetFunction) && ts.getElementOrPropertyAccessName(assignmentTarget) !== "prototype" &&
  116452. trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) {
  116453. if (ts.isFunctionExpression(binaryExpression.right) || ts.isArrowFunction(binaryExpression.right)) {
  116454. addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction);
  116455. }
  116456. else if (ts.isBindableStaticAccessExpression(assignmentTarget)) {
  116457. startNode(binaryExpression, targetFunction);
  116458. addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, ts.getNameOrArgument(assignmentTarget));
  116459. endNode();
  116460. }
  116461. return;
  116462. }
  116463. break;
  116464. }
  116465. case 4 /* ThisProperty */:
  116466. case 0 /* None */:
  116467. case 8 /* ObjectDefinePropertyExports */:
  116468. break;
  116469. default:
  116470. ts.Debug.assertNever(special);
  116471. }
  116472. }
  116473. // falls through
  116474. default:
  116475. if (ts.hasJSDocNodes(node)) {
  116476. ts.forEach(node.jsDoc, function (jsDoc) {
  116477. ts.forEach(jsDoc.tags, function (tag) {
  116478. if (ts.isJSDocTypeAlias(tag)) {
  116479. addLeafNode(tag);
  116480. }
  116481. });
  116482. });
  116483. }
  116484. ts.forEachChild(node, addChildrenRecursively);
  116485. }
  116486. }
  116487. /** Merge declarations of the same kind. */
  116488. function mergeChildren(children, node) {
  116489. var nameToItems = ts.createMap();
  116490. ts.filterMutate(children, function (child, index) {
  116491. var declName = child.name || ts.getNameOfDeclaration(child.node);
  116492. var name = declName && nodeText(declName);
  116493. if (!name) {
  116494. // Anonymous items are never merged.
  116495. return true;
  116496. }
  116497. var itemsWithSameName = nameToItems.get(name);
  116498. if (!itemsWithSameName) {
  116499. nameToItems.set(name, child);
  116500. return true;
  116501. }
  116502. if (itemsWithSameName instanceof Array) {
  116503. for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) {
  116504. var itemWithSameName = itemsWithSameName_1[_i];
  116505. if (tryMerge(itemWithSameName, child, index, node)) {
  116506. return false;
  116507. }
  116508. }
  116509. itemsWithSameName.push(child);
  116510. return true;
  116511. }
  116512. else {
  116513. var itemWithSameName = itemsWithSameName;
  116514. if (tryMerge(itemWithSameName, child, index, node)) {
  116515. return false;
  116516. }
  116517. nameToItems.set(name, [itemWithSameName, child]);
  116518. return true;
  116519. }
  116520. });
  116521. }
  116522. var isEs5ClassMember = (_a = {},
  116523. _a[5 /* Property */] = true,
  116524. _a[3 /* PrototypeProperty */] = true,
  116525. _a[7 /* ObjectDefinePropertyValue */] = true,
  116526. _a[9 /* ObjectDefinePrototypeProperty */] = true,
  116527. _a[0 /* None */] = false,
  116528. _a[1 /* ExportsProperty */] = false,
  116529. _a[2 /* ModuleExports */] = false,
  116530. _a[8 /* ObjectDefinePropertyExports */] = false,
  116531. _a[6 /* Prototype */] = true,
  116532. _a[4 /* ThisProperty */] = false,
  116533. _a);
  116534. function tryMergeEs5Class(a, b, bIndex, parent) {
  116535. function isPossibleConstructor(node) {
  116536. return ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node);
  116537. }
  116538. var bAssignmentDeclarationKind = ts.isBinaryExpression(b.node) || ts.isCallExpression(b.node) ?
  116539. ts.getAssignmentDeclarationKind(b.node) :
  116540. 0 /* None */;
  116541. var aAssignmentDeclarationKind = ts.isBinaryExpression(a.node) || ts.isCallExpression(a.node) ?
  116542. ts.getAssignmentDeclarationKind(a.node) :
  116543. 0 /* None */;
  116544. // We treat this as an es5 class and merge the nodes in in one of several cases
  116545. if ((isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind]) // merge two class elements
  116546. || (isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // ctor function & member
  116547. || (isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & ctor function
  116548. || (ts.isClassDeclaration(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // class (generated) & member
  116549. || (ts.isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & class (generated)
  116550. || (ts.isClassDeclaration(a.node) && isPossibleConstructor(b.node)) // class (generated) & ctor
  116551. || (ts.isClassDeclaration(b.node) && isPossibleConstructor(a.node)) // ctor & class (generated)
  116552. ) {
  116553. var lastANode = a.additionalNodes && ts.lastOrUndefined(a.additionalNodes) || a.node;
  116554. if ((!ts.isClassDeclaration(a.node) && !ts.isClassDeclaration(b.node)) // If neither outline node is a class
  116555. || isPossibleConstructor(a.node) || isPossibleConstructor(b.node) // If either function is a constructor function
  116556. ) {
  116557. var ctorFunction = isPossibleConstructor(a.node) ? a.node :
  116558. isPossibleConstructor(b.node) ? b.node :
  116559. undefined;
  116560. if (ctorFunction !== undefined) {
  116561. var ctorNode = ts.setTextRange(ts.createConstructor(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction);
  116562. var ctor = emptyNavigationBarNode(ctorNode);
  116563. ctor.indent = a.indent + 1;
  116564. ctor.children = a.node === ctorFunction ? a.children : b.children;
  116565. a.children = a.node === ctorFunction ? ts.concatenate([ctor], b.children || [b]) : ts.concatenate(a.children || [a], [ctor]);
  116566. }
  116567. else {
  116568. if (a.children || b.children) {
  116569. a.children = ts.concatenate(a.children || [a], b.children || [b]);
  116570. if (a.children) {
  116571. mergeChildren(a.children, a);
  116572. sortChildren(a.children);
  116573. }
  116574. }
  116575. }
  116576. lastANode = a.node = ts.setTextRange(ts.createClassDeclaration(
  116577. /* decorators */ undefined,
  116578. /* modifiers */ undefined, a.name || ts.createIdentifier("__class__"),
  116579. /* typeParameters */ undefined,
  116580. /* heritageClauses */ undefined, []), a.node);
  116581. }
  116582. else {
  116583. a.children = ts.concatenate(a.children, b.children);
  116584. if (a.children) {
  116585. mergeChildren(a.children, a);
  116586. }
  116587. }
  116588. var bNode = b.node;
  116589. // We merge if the outline node previous to b (bIndex - 1) is already part of the current class
  116590. // We do this so that statements between class members that do not generate outline nodes do not split up the class outline:
  116591. // Ex This should produce one outline node C:
  116592. // function C() {}; a = 1; C.prototype.m = function () {}
  116593. // Ex This will produce 3 outline nodes: C, a, C
  116594. // function C() {}; let a = 1; C.prototype.m = function () {}
  116595. if (parent.children[bIndex - 1].node.end === lastANode.end) {
  116596. ts.setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end });
  116597. }
  116598. else {
  116599. if (!a.additionalNodes)
  116600. a.additionalNodes = [];
  116601. a.additionalNodes.push(ts.setTextRange(ts.createClassDeclaration(
  116602. /* decorators */ undefined,
  116603. /* modifiers */ undefined, a.name || ts.createIdentifier("__class__"),
  116604. /* typeParameters */ undefined,
  116605. /* heritageClauses */ undefined, []), b.node));
  116606. }
  116607. return true;
  116608. }
  116609. return bAssignmentDeclarationKind === 0 /* None */ ? false : true;
  116610. }
  116611. function tryMerge(a, b, bIndex, parent) {
  116612. // const v = false as boolean;
  116613. if (tryMergeEs5Class(a, b, bIndex, parent)) {
  116614. return true;
  116615. }
  116616. if (shouldReallyMerge(a.node, b.node, parent)) {
  116617. merge(a, b);
  116618. return true;
  116619. }
  116620. return false;
  116621. }
  116622. /** a and b have the same name, but they may not be mergeable. */
  116623. function shouldReallyMerge(a, b, parent) {
  116624. if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) {
  116625. return false;
  116626. }
  116627. switch (a.kind) {
  116628. case 159 /* PropertyDeclaration */:
  116629. case 161 /* MethodDeclaration */:
  116630. case 163 /* GetAccessor */:
  116631. case 164 /* SetAccessor */:
  116632. return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */);
  116633. case 249 /* ModuleDeclaration */:
  116634. return areSameModule(a, b);
  116635. default:
  116636. return true;
  116637. }
  116638. }
  116639. // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }`
  116640. // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };`
  116641. function isOwnChild(n, parent) {
  116642. var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent;
  116643. return par === parent.node || ts.contains(parent.additionalNodes, par);
  116644. }
  116645. // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes.
  116646. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
  116647. function areSameModule(a, b) {
  116648. // TODO: GH#18217
  116649. return a.body.kind === b.body.kind && (a.body.kind !== 249 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
  116650. }
  116651. /** Merge source into target. Source should be thrown away after this is called. */
  116652. function merge(target, source) {
  116653. var _a;
  116654. target.additionalNodes = target.additionalNodes || [];
  116655. target.additionalNodes.push(source.node);
  116656. if (source.additionalNodes) {
  116657. (_a = target.additionalNodes).push.apply(_a, source.additionalNodes);
  116658. }
  116659. target.children = ts.concatenate(target.children, source.children);
  116660. if (target.children) {
  116661. mergeChildren(target.children, target);
  116662. sortChildren(target.children);
  116663. }
  116664. }
  116665. /** Recursively ensure that each NavNode's children are in sorted order. */
  116666. function sortChildren(children) {
  116667. children.sort(compareChildren);
  116668. }
  116669. function compareChildren(child1, child2) {
  116670. return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217
  116671. || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2));
  116672. }
  116673. /**
  116674. * This differs from getItemName because this is just used for sorting.
  116675. * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like.
  116676. * So `new()` can still come before an `aardvark` method.
  116677. */
  116678. function tryGetName(node) {
  116679. if (node.kind === 249 /* ModuleDeclaration */) {
  116680. return getModuleName(node);
  116681. }
  116682. var declName = ts.getNameOfDeclaration(node);
  116683. if (declName && ts.isPropertyName(declName)) {
  116684. var propertyName = ts.getPropertyNameForPropertyNameNode(declName);
  116685. return propertyName && ts.unescapeLeadingUnderscores(propertyName);
  116686. }
  116687. switch (node.kind) {
  116688. case 201 /* FunctionExpression */:
  116689. case 202 /* ArrowFunction */:
  116690. case 214 /* ClassExpression */:
  116691. return getFunctionOrClassName(node);
  116692. default:
  116693. return undefined;
  116694. }
  116695. }
  116696. function getItemName(node, name) {
  116697. if (node.kind === 249 /* ModuleDeclaration */) {
  116698. return cleanText(getModuleName(node));
  116699. }
  116700. if (name) {
  116701. var text = ts.isIdentifier(name) ? name.text
  116702. : ts.isElementAccessExpression(name) ? "[" + nodeText(name.argumentExpression) + "]"
  116703. : nodeText(name);
  116704. if (text.length > 0) {
  116705. return cleanText(text);
  116706. }
  116707. }
  116708. switch (node.kind) {
  116709. case 290 /* SourceFile */:
  116710. var sourceFile = node;
  116711. return ts.isExternalModule(sourceFile)
  116712. ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
  116713. : "<global>";
  116714. case 259 /* ExportAssignment */:
  116715. return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
  116716. case 202 /* ArrowFunction */:
  116717. case 244 /* FunctionDeclaration */:
  116718. case 201 /* FunctionExpression */:
  116719. case 245 /* ClassDeclaration */:
  116720. case 214 /* ClassExpression */:
  116721. if (ts.getModifierFlags(node) & 512 /* Default */) {
  116722. return "default";
  116723. }
  116724. // We may get a string with newlines or other whitespace in the case of an object dereference
  116725. // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
  116726. // navigation bar.
  116727. return getFunctionOrClassName(node);
  116728. case 162 /* Constructor */:
  116729. return "constructor";
  116730. case 166 /* ConstructSignature */:
  116731. return "new()";
  116732. case 165 /* CallSignature */:
  116733. return "()";
  116734. case 167 /* IndexSignature */:
  116735. return "[]";
  116736. default:
  116737. return "<unknown>";
  116738. }
  116739. }
  116740. /** Flattens the NavNode tree to a list of items to appear in the primary navbar menu. */
  116741. function primaryNavBarMenuItems(root) {
  116742. // The primary (middle) navbar menu displays the general code navigation hierarchy, similar to the navtree.
  116743. // The secondary (right) navbar menu displays the child items of whichever primary item is selected.
  116744. // Some less interesting items without their own child navigation items (e.g. a local variable declaration) only show up in the secondary menu.
  116745. var primaryNavBarMenuItems = [];
  116746. function recur(item) {
  116747. if (shouldAppearInPrimaryNavBarMenu(item)) {
  116748. primaryNavBarMenuItems.push(item);
  116749. if (item.children) {
  116750. for (var _i = 0, _a = item.children; _i < _a.length; _i++) {
  116751. var child = _a[_i];
  116752. recur(child);
  116753. }
  116754. }
  116755. }
  116756. }
  116757. recur(root);
  116758. return primaryNavBarMenuItems;
  116759. /** Determines if a node should appear in the primary navbar menu. */
  116760. function shouldAppearInPrimaryNavBarMenu(item) {
  116761. // Items with children should always appear in the primary navbar menu.
  116762. if (item.children) {
  116763. return true;
  116764. }
  116765. // Some nodes are otherwise important enough to always include in the primary navigation menu.
  116766. switch (navigationBarNodeKind(item)) {
  116767. case 245 /* ClassDeclaration */:
  116768. case 214 /* ClassExpression */:
  116769. case 248 /* EnumDeclaration */:
  116770. case 246 /* InterfaceDeclaration */:
  116771. case 249 /* ModuleDeclaration */:
  116772. case 290 /* SourceFile */:
  116773. case 247 /* TypeAliasDeclaration */:
  116774. case 321 /* JSDocTypedefTag */:
  116775. case 314 /* JSDocCallbackTag */:
  116776. return true;
  116777. case 202 /* ArrowFunction */:
  116778. case 244 /* FunctionDeclaration */:
  116779. case 201 /* FunctionExpression */:
  116780. return isTopLevelFunctionDeclaration(item);
  116781. default:
  116782. return false;
  116783. }
  116784. function isTopLevelFunctionDeclaration(item) {
  116785. if (!item.node.body) {
  116786. return false;
  116787. }
  116788. switch (navigationBarNodeKind(item.parent)) {
  116789. case 250 /* ModuleBlock */:
  116790. case 290 /* SourceFile */:
  116791. case 161 /* MethodDeclaration */:
  116792. case 162 /* Constructor */:
  116793. return true;
  116794. default:
  116795. return false;
  116796. }
  116797. }
  116798. }
  116799. }
  116800. function convertToTree(n) {
  116801. return {
  116802. text: getItemName(n.node, n.name),
  116803. kind: ts.getNodeKind(n.node),
  116804. kindModifiers: getModifiers(n.node),
  116805. spans: getSpans(n),
  116806. nameSpan: n.name && getNodeSpan(n.name),
  116807. childItems: ts.map(n.children, convertToTree)
  116808. };
  116809. }
  116810. function convertToPrimaryNavBarMenuItem(n) {
  116811. return {
  116812. text: getItemName(n.node, n.name),
  116813. kind: ts.getNodeKind(n.node),
  116814. kindModifiers: getModifiers(n.node),
  116815. spans: getSpans(n),
  116816. childItems: ts.map(n.children, convertToSecondaryNavBarMenuItem) || emptyChildItemArray,
  116817. indent: n.indent,
  116818. bolded: false,
  116819. grayed: false
  116820. };
  116821. function convertToSecondaryNavBarMenuItem(n) {
  116822. return {
  116823. text: getItemName(n.node, n.name),
  116824. kind: ts.getNodeKind(n.node),
  116825. kindModifiers: ts.getNodeModifiers(n.node),
  116826. spans: getSpans(n),
  116827. childItems: emptyChildItemArray,
  116828. indent: 0,
  116829. bolded: false,
  116830. grayed: false
  116831. };
  116832. }
  116833. }
  116834. function getSpans(n) {
  116835. var spans = [getNodeSpan(n.node)];
  116836. if (n.additionalNodes) {
  116837. for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) {
  116838. var node = _a[_i];
  116839. spans.push(getNodeSpan(node));
  116840. }
  116841. }
  116842. return spans;
  116843. }
  116844. function getModuleName(moduleDeclaration) {
  116845. // We want to maintain quotation marks.
  116846. if (ts.isAmbientModule(moduleDeclaration)) {
  116847. return ts.getTextOfNode(moduleDeclaration.name);
  116848. }
  116849. // Otherwise, we need to aggregate each identifier to build up the qualified name.
  116850. var result = [];
  116851. result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
  116852. while (moduleDeclaration.body && moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
  116853. moduleDeclaration = moduleDeclaration.body;
  116854. result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
  116855. }
  116856. return result.join(".");
  116857. }
  116858. /**
  116859. * For 'module A.B.C', we want to get the node for 'C'.
  116860. * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again.
  116861. */
  116862. function getInteriorModule(decl) {
  116863. return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl;
  116864. }
  116865. function isComputedProperty(member) {
  116866. return !member.name || member.name.kind === 154 /* ComputedPropertyName */;
  116867. }
  116868. function getNodeSpan(node) {
  116869. return node.kind === 290 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
  116870. }
  116871. function getModifiers(node) {
  116872. if (node.parent && node.parent.kind === 242 /* VariableDeclaration */) {
  116873. node = node.parent;
  116874. }
  116875. return ts.getNodeModifiers(node);
  116876. }
  116877. function getFunctionOrClassName(node) {
  116878. var parent = node.parent;
  116879. if (node.name && ts.getFullWidth(node.name) > 0) {
  116880. return cleanText(ts.declarationNameToString(node.name));
  116881. }
  116882. // See if it is a var initializer. If so, use the var name.
  116883. else if (ts.isVariableDeclaration(parent)) {
  116884. return cleanText(ts.declarationNameToString(parent.name));
  116885. }
  116886. // See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
  116887. else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */) {
  116888. return nodeText(parent.left).replace(whiteSpaceRegex, "");
  116889. }
  116890. // See if it is a property assignment, and if so use the property name
  116891. else if (ts.isPropertyAssignment(parent)) {
  116892. return nodeText(parent.name);
  116893. }
  116894. // Default exports are named "default"
  116895. else if (ts.getModifierFlags(node) & 512 /* Default */) {
  116896. return "default";
  116897. }
  116898. else if (ts.isClassLike(node)) {
  116899. return "<class>";
  116900. }
  116901. else if (ts.isCallExpression(parent)) {
  116902. var name = getCalledExpressionName(parent.expression);
  116903. if (name !== undefined) {
  116904. name = cleanText(name);
  116905. if (name.length > maxLength) {
  116906. return name + " callback";
  116907. }
  116908. var args = cleanText(ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "));
  116909. return name + "(" + args + ") callback";
  116910. }
  116911. }
  116912. return "<function>";
  116913. }
  116914. // See also 'tryGetPropertyAccessOrIdentifierToString'
  116915. function getCalledExpressionName(expr) {
  116916. if (ts.isIdentifier(expr)) {
  116917. return expr.text;
  116918. }
  116919. else if (ts.isPropertyAccessExpression(expr)) {
  116920. var left = getCalledExpressionName(expr.expression);
  116921. var right = expr.name.text;
  116922. return left === undefined ? right : left + "." + right;
  116923. }
  116924. else {
  116925. return undefined;
  116926. }
  116927. }
  116928. function isFunctionOrClassExpression(node) {
  116929. switch (node.kind) {
  116930. case 202 /* ArrowFunction */:
  116931. case 201 /* FunctionExpression */:
  116932. case 214 /* ClassExpression */:
  116933. return true;
  116934. default:
  116935. return false;
  116936. }
  116937. }
  116938. function cleanText(text) {
  116939. // Truncate to maximum amount of characters as we don't want to do a big replace operation.
  116940. text = text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
  116941. // Replaces ECMAScript line terminators and removes the trailing `\` from each line:
  116942. // \n - Line Feed
  116943. // \r - Carriage Return
  116944. // \u2028 - Line separator
  116945. // \u2029 - Paragraph separator
  116946. return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, "");
  116947. }
  116948. })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {}));
  116949. })(ts || (ts = {}));
  116950. /* @internal */
  116951. var ts;
  116952. (function (ts) {
  116953. var OrganizeImports;
  116954. (function (OrganizeImports) {
  116955. /**
  116956. * Organize imports by:
  116957. * 1) Removing unused imports
  116958. * 2) Coalescing imports from the same module
  116959. * 3) Sorting imports
  116960. */
  116961. function organizeImports(sourceFile, formatContext, host, program, preferences) {
  116962. var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences });
  116963. var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
  116964. // All of the old ImportDeclarations in the file, in syntactic order.
  116965. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
  116966. organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
  116967. // All of the old ExportDeclarations in the file, in syntactic order.
  116968. var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
  116969. organizeImportsWorker(topLevelExportDecls, coalesceExports);
  116970. for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
  116971. var ambientModule = _a[_i];
  116972. if (!ambientModule.body) {
  116973. continue;
  116974. }
  116975. var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration);
  116976. organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
  116977. var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration);
  116978. organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
  116979. }
  116980. return changeTracker.getChanges();
  116981. function organizeImportsWorker(oldImportDecls, coalesce) {
  116982. if (ts.length(oldImportDecls) === 0) {
  116983. return;
  116984. }
  116985. // Special case: normally, we'd expect leading and trailing trivia to follow each import
  116986. // around as it's sorted. However, we do not want this to happen for leading trivia
  116987. // on the first import because it is probably the header comment for the file.
  116988. // Consider: we could do a more careful check that this trivia is actually a header,
  116989. // but the consequences of being wrong are very minor.
  116990. ts.suppressLeadingTrivia(oldImportDecls[0]);
  116991. var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
  116992. var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
  116993. var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
  116994. return getExternalModuleName(importGroup[0].moduleSpecifier)
  116995. ? coalesce(importGroup)
  116996. : importGroup;
  116997. });
  116998. // Delete or replace the first import.
  116999. if (newImportDecls.length === 0) {
  117000. changeTracker.delete(sourceFile, oldImportDecls[0]);
  117001. }
  117002. else {
  117003. // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
  117004. changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
  117005. leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
  117006. trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
  117007. suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
  117008. });
  117009. }
  117010. // Delete any subsequent imports.
  117011. for (var i = 1; i < oldImportDecls.length; i++) {
  117012. changeTracker.delete(sourceFile, oldImportDecls[i]);
  117013. }
  117014. }
  117015. }
  117016. OrganizeImports.organizeImports = organizeImports;
  117017. function removeUnusedImports(oldImports, sourceFile, program) {
  117018. var typeChecker = program.getTypeChecker();
  117019. var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
  117020. var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
  117021. var usedImports = [];
  117022. for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
  117023. var importDecl = oldImports_1[_i];
  117024. var importClause = importDecl.importClause, moduleSpecifier = importDecl.moduleSpecifier;
  117025. if (!importClause) {
  117026. // Imports without import clauses are assumed to be included for their side effects and are not removed.
  117027. usedImports.push(importDecl);
  117028. continue;
  117029. }
  117030. var name = importClause.name, namedBindings = importClause.namedBindings;
  117031. // Default import
  117032. if (name && !isDeclarationUsed(name)) {
  117033. name = undefined;
  117034. }
  117035. if (namedBindings) {
  117036. if (ts.isNamespaceImport(namedBindings)) {
  117037. // Namespace import
  117038. if (!isDeclarationUsed(namedBindings.name)) {
  117039. namedBindings = undefined;
  117040. }
  117041. }
  117042. else {
  117043. // List of named imports
  117044. var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); });
  117045. if (newElements.length < namedBindings.elements.length) {
  117046. namedBindings = newElements.length
  117047. ? ts.updateNamedImports(namedBindings, newElements)
  117048. : undefined;
  117049. }
  117050. }
  117051. }
  117052. if (name || namedBindings) {
  117053. usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
  117054. }
  117055. // If a module is imported to be augmented, it’s used
  117056. else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
  117057. // If we’re in a declaration file, it’s safe to remove the import clause from it
  117058. if (sourceFile.isDeclarationFile) {
  117059. usedImports.push(ts.createImportDeclaration(importDecl.decorators, importDecl.modifiers,
  117060. /*importClause*/ undefined, moduleSpecifier));
  117061. }
  117062. // If we’re not in a declaration file, we can’t remove the import clause even though
  117063. // the imported symbols are unused, because removing them makes it look like the import
  117064. // declaration has side effects, which will cause it to be preserved in the JS emit.
  117065. else {
  117066. usedImports.push(importDecl);
  117067. }
  117068. }
  117069. }
  117070. return usedImports;
  117071. function isDeclarationUsed(identifier) {
  117072. // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
  117073. return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
  117074. }
  117075. }
  117076. function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) {
  117077. var moduleSpecifierText = ts.isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
  117078. return ts.isString(moduleSpecifierText) && ts.some(sourceFile.moduleAugmentations, function (moduleName) {
  117079. return ts.isStringLiteral(moduleName)
  117080. && moduleName.text === moduleSpecifierText;
  117081. });
  117082. }
  117083. function getExternalModuleName(specifier) {
  117084. return specifier !== undefined && ts.isStringLiteralLike(specifier)
  117085. ? specifier.text
  117086. : undefined;
  117087. }
  117088. // Internal for testing
  117089. /**
  117090. * @param importGroup a list of ImportDeclarations, all with the same module name.
  117091. */
  117092. function coalesceImports(importGroup) {
  117093. var _a;
  117094. if (importGroup.length === 0) {
  117095. return importGroup;
  117096. }
  117097. var _b = getCategorizedImports(importGroup), importWithoutClause = _b.importWithoutClause, typeOnlyImports = _b.typeOnlyImports, regularImports = _b.regularImports;
  117098. var coalescedImports = [];
  117099. if (importWithoutClause) {
  117100. coalescedImports.push(importWithoutClause);
  117101. }
  117102. for (var _i = 0, _c = [regularImports, typeOnlyImports]; _i < _c.length; _i++) {
  117103. var group_2 = _c[_i];
  117104. var isTypeOnly = group_2 === typeOnlyImports;
  117105. var defaultImports = group_2.defaultImports, namespaceImports = group_2.namespaceImports, namedImports = group_2.namedImports;
  117106. // Normally, we don't combine default and namespace imports, but it would be silly to
  117107. // produce two import declarations in this special case.
  117108. if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
  117109. // Add the namespace import to the existing default ImportDeclaration.
  117110. var defaultImport = defaultImports[0];
  117111. coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217
  117112. continue;
  117113. }
  117114. var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
  117115. return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
  117116. }); // TODO: GH#18217
  117117. for (var _d = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _d < sortedNamespaceImports_1.length; _d++) {
  117118. var namespaceImport = sortedNamespaceImports_1[_d];
  117119. // Drop the name, if any
  117120. coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217
  117121. }
  117122. if (defaultImports.length === 0 && namedImports.length === 0) {
  117123. continue;
  117124. }
  117125. var newDefaultImport = void 0;
  117126. var newImportSpecifiers = [];
  117127. if (defaultImports.length === 1) {
  117128. newDefaultImport = defaultImports[0].importClause.name;
  117129. }
  117130. else {
  117131. for (var _e = 0, defaultImports_1 = defaultImports; _e < defaultImports_1.length; _e++) {
  117132. var defaultImport = defaultImports_1[_e];
  117133. newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217
  117134. }
  117135. }
  117136. newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217
  117137. var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
  117138. var importDecl = defaultImports.length > 0
  117139. ? defaultImports[0]
  117140. : namedImports[0];
  117141. var newNamedImports = sortedImportSpecifiers.length === 0
  117142. ? newDefaultImport
  117143. ? undefined
  117144. : ts.createNamedImports(ts.emptyArray)
  117145. : namedImports.length === 0
  117146. ? ts.createNamedImports(sortedImportSpecifiers)
  117147. : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217
  117148. // Type-only imports are not allowed to combine
  117149. if (isTypeOnly && newDefaultImport && newNamedImports) {
  117150. coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined));
  117151. coalescedImports.push(updateImportDeclarationAndClause((_a = namedImports[0]) !== null && _a !== void 0 ? _a : importDecl, /*name*/ undefined, newNamedImports));
  117152. }
  117153. else {
  117154. coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
  117155. }
  117156. }
  117157. return coalescedImports;
  117158. }
  117159. OrganizeImports.coalesceImports = coalesceImports;
  117160. /*
  117161. * Returns entire import declarations because they may already have been rewritten and
  117162. * may lack parent pointers. The desired parts can easily be recovered based on the
  117163. * categorization.
  117164. *
  117165. * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
  117166. */
  117167. function getCategorizedImports(importGroup) {
  117168. var importWithoutClause;
  117169. var typeOnlyImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
  117170. var regularImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
  117171. for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) {
  117172. var importDeclaration = importGroup_1[_i];
  117173. if (importDeclaration.importClause === undefined) {
  117174. // Only the first such import is interesting - the others are redundant.
  117175. // Note: Unfortunately, we will lose trivia that was on this node.
  117176. importWithoutClause = importWithoutClause || importDeclaration;
  117177. continue;
  117178. }
  117179. var group_3 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports;
  117180. var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
  117181. if (name) {
  117182. group_3.defaultImports.push(importDeclaration);
  117183. }
  117184. if (namedBindings) {
  117185. if (ts.isNamespaceImport(namedBindings)) {
  117186. group_3.namespaceImports.push(importDeclaration);
  117187. }
  117188. else {
  117189. group_3.namedImports.push(importDeclaration);
  117190. }
  117191. }
  117192. }
  117193. return {
  117194. importWithoutClause: importWithoutClause,
  117195. typeOnlyImports: typeOnlyImports,
  117196. regularImports: regularImports,
  117197. };
  117198. }
  117199. // Internal for testing
  117200. /**
  117201. * @param exportGroup a list of ExportDeclarations, all with the same module name.
  117202. */
  117203. function coalesceExports(exportGroup) {
  117204. if (exportGroup.length === 0) {
  117205. return exportGroup;
  117206. }
  117207. var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports, typeOnlyExports = _a.typeOnlyExports;
  117208. var coalescedExports = [];
  117209. if (exportWithoutClause) {
  117210. coalescedExports.push(exportWithoutClause);
  117211. }
  117212. for (var _i = 0, _b = [namedExports, typeOnlyExports]; _i < _b.length; _i++) {
  117213. var exportGroup_1 = _b[_i];
  117214. if (exportGroup_1.length === 0) {
  117215. continue;
  117216. }
  117217. var newExportSpecifiers = [];
  117218. newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; }));
  117219. var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
  117220. var exportDecl = exportGroup_1[0];
  117221. coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ?
  117222. ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) :
  117223. ts.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.isTypeOnly));
  117224. }
  117225. return coalescedExports;
  117226. /*
  117227. * Returns entire export declarations because they may already have been rewritten and
  117228. * may lack parent pointers. The desired parts can easily be recovered based on the
  117229. * categorization.
  117230. */
  117231. function getCategorizedExports(exportGroup) {
  117232. var exportWithoutClause;
  117233. var namedExports = [];
  117234. var typeOnlyExports = [];
  117235. for (var _i = 0, exportGroup_2 = exportGroup; _i < exportGroup_2.length; _i++) {
  117236. var exportDeclaration = exportGroup_2[_i];
  117237. if (exportDeclaration.exportClause === undefined) {
  117238. // Only the first such export is interesting - the others are redundant.
  117239. // Note: Unfortunately, we will lose trivia that was on this node.
  117240. exportWithoutClause = exportWithoutClause || exportDeclaration;
  117241. }
  117242. else if (exportDeclaration.isTypeOnly) {
  117243. typeOnlyExports.push(exportDeclaration);
  117244. }
  117245. else {
  117246. namedExports.push(exportDeclaration);
  117247. }
  117248. }
  117249. return {
  117250. exportWithoutClause: exportWithoutClause,
  117251. namedExports: namedExports,
  117252. typeOnlyExports: typeOnlyExports,
  117253. };
  117254. }
  117255. }
  117256. OrganizeImports.coalesceExports = coalesceExports;
  117257. function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
  117258. return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings, importDeclaration.importClause.isTypeOnly), // TODO: GH#18217
  117259. importDeclaration.moduleSpecifier);
  117260. }
  117261. function sortSpecifiers(specifiers) {
  117262. return ts.stableSort(specifiers, function (s1, s2) {
  117263. return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
  117264. compareIdentifiers(s1.name, s2.name);
  117265. });
  117266. }
  117267. /* internal */ // Exported for testing
  117268. function compareModuleSpecifiers(m1, m2) {
  117269. var name1 = getExternalModuleName(m1);
  117270. var name2 = getExternalModuleName(m2);
  117271. return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
  117272. ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
  117273. ts.compareStringsCaseInsensitive(name1, name2);
  117274. }
  117275. OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
  117276. function compareIdentifiers(s1, s2) {
  117277. return ts.compareStringsCaseInsensitive(s1.text, s2.text);
  117278. }
  117279. })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
  117280. })(ts || (ts = {}));
  117281. /* @internal */
  117282. var ts;
  117283. (function (ts) {
  117284. var OutliningElementsCollector;
  117285. (function (OutliningElementsCollector) {
  117286. function collectElements(sourceFile, cancellationToken) {
  117287. var res = [];
  117288. addNodeOutliningSpans(sourceFile, cancellationToken, res);
  117289. addRegionOutliningSpans(sourceFile, res);
  117290. return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; });
  117291. }
  117292. OutliningElementsCollector.collectElements = collectElements;
  117293. function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
  117294. var depthRemaining = 40;
  117295. var current = 0;
  117296. // Includes the EOF Token so that comments which aren't attached to statements are included
  117297. var statements = __spreadArrays(sourceFile.statements, [sourceFile.endOfFileToken]);
  117298. var n = statements.length;
  117299. while (current < n) {
  117300. while (current < n && !ts.isAnyImportSyntax(statements[current])) {
  117301. visitNonImportNode(statements[current]);
  117302. current++;
  117303. }
  117304. if (current === n)
  117305. break;
  117306. var firstImport = current;
  117307. while (current < n && ts.isAnyImportSyntax(statements[current])) {
  117308. addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
  117309. current++;
  117310. }
  117311. var lastImport = current - 1;
  117312. if (lastImport !== firstImport) {
  117313. out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 96 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
  117314. }
  117315. }
  117316. function visitNonImportNode(n) {
  117317. var _a;
  117318. if (depthRemaining === 0)
  117319. return;
  117320. cancellationToken.throwIfCancellationRequested();
  117321. if (ts.isDeclaration(n) || n.kind === 1 /* EndOfFileToken */) {
  117322. addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out);
  117323. }
  117324. if (isFunctionExpressionAssignedToVariable(n)) {
  117325. addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out);
  117326. }
  117327. var span = getOutliningSpanForNode(n, sourceFile);
  117328. if (span)
  117329. out.push(span);
  117330. depthRemaining--;
  117331. if (ts.isCallExpression(n)) {
  117332. depthRemaining++;
  117333. visitNonImportNode(n.expression);
  117334. depthRemaining--;
  117335. n.arguments.forEach(visitNonImportNode);
  117336. (_a = n.typeArguments) === null || _a === void 0 ? void 0 : _a.forEach(visitNonImportNode);
  117337. }
  117338. else if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
  117339. // Consider an 'else if' to be on the same depth as the 'if'.
  117340. visitNonImportNode(n.expression);
  117341. visitNonImportNode(n.thenStatement);
  117342. depthRemaining++;
  117343. visitNonImportNode(n.elseStatement);
  117344. depthRemaining--;
  117345. }
  117346. else {
  117347. n.forEachChild(visitNonImportNode);
  117348. }
  117349. depthRemaining++;
  117350. }
  117351. function isFunctionExpressionAssignedToVariable(n) {
  117352. if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) {
  117353. return false;
  117354. }
  117355. var ancestor = ts.findAncestor(n, ts.isVariableStatement);
  117356. return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n;
  117357. }
  117358. }
  117359. function addRegionOutliningSpans(sourceFile, out) {
  117360. var regions = [];
  117361. var lineStarts = sourceFile.getLineStarts();
  117362. for (var _i = 0, lineStarts_1 = lineStarts; _i < lineStarts_1.length; _i++) {
  117363. var currentLineStart = lineStarts_1[_i];
  117364. var lineEnd = sourceFile.getLineEndOfPosition(currentLineStart);
  117365. var lineText = sourceFile.text.substring(currentLineStart, lineEnd);
  117366. var result = isRegionDelimiter(lineText);
  117367. if (!result || ts.isInComment(sourceFile, currentLineStart)) {
  117368. continue;
  117369. }
  117370. if (!result[1]) {
  117371. var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
  117372. regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
  117373. }
  117374. else {
  117375. var region = regions.pop();
  117376. if (region) {
  117377. region.textSpan.length = lineEnd - region.textSpan.start;
  117378. region.hintSpan.length = lineEnd - region.textSpan.start;
  117379. out.push(region);
  117380. }
  117381. }
  117382. }
  117383. }
  117384. var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/;
  117385. function isRegionDelimiter(lineText) {
  117386. return regionDelimiterRegExp.exec(lineText);
  117387. }
  117388. function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
  117389. var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
  117390. if (!comments)
  117391. return;
  117392. var firstSingleLineCommentStart = -1;
  117393. var lastSingleLineCommentEnd = -1;
  117394. var singleLineCommentCount = 0;
  117395. var sourceText = sourceFile.getFullText();
  117396. for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
  117397. var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
  117398. cancellationToken.throwIfCancellationRequested();
  117399. switch (kind) {
  117400. case 2 /* SingleLineCommentTrivia */:
  117401. // never fold region delimiters into single-line comment regions
  117402. var commentText = sourceText.slice(pos, end);
  117403. if (isRegionDelimiter(commentText)) {
  117404. combineAndAddMultipleSingleLineComments();
  117405. singleLineCommentCount = 0;
  117406. break;
  117407. }
  117408. // For single line comments, combine consecutive ones (2 or more) into
  117409. // a single span from the start of the first till the end of the last
  117410. if (singleLineCommentCount === 0) {
  117411. firstSingleLineCommentStart = pos;
  117412. }
  117413. lastSingleLineCommentEnd = end;
  117414. singleLineCommentCount++;
  117415. break;
  117416. case 3 /* MultiLineCommentTrivia */:
  117417. combineAndAddMultipleSingleLineComments();
  117418. out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
  117419. singleLineCommentCount = 0;
  117420. break;
  117421. default:
  117422. ts.Debug.assertNever(kind);
  117423. }
  117424. }
  117425. combineAndAddMultipleSingleLineComments();
  117426. function combineAndAddMultipleSingleLineComments() {
  117427. // Only outline spans of two or more consecutive single line comments
  117428. if (singleLineCommentCount > 1) {
  117429. out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
  117430. }
  117431. }
  117432. }
  117433. function createOutliningSpanFromBounds(pos, end, kind) {
  117434. return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
  117435. }
  117436. function getOutliningSpanForNode(n, sourceFile) {
  117437. switch (n.kind) {
  117438. case 223 /* Block */:
  117439. if (ts.isFunctionLike(n.parent)) {
  117440. return functionSpan(n.parent, n, sourceFile);
  117441. }
  117442. // Check if the block is standalone, or 'attached' to some parent statement.
  117443. // If the latter, we want to collapse the block, but consider its hint span
  117444. // to be the entire span of the parent.
  117445. switch (n.parent.kind) {
  117446. case 228 /* DoStatement */:
  117447. case 231 /* ForInStatement */:
  117448. case 232 /* ForOfStatement */:
  117449. case 230 /* ForStatement */:
  117450. case 227 /* IfStatement */:
  117451. case 229 /* WhileStatement */:
  117452. case 236 /* WithStatement */:
  117453. case 280 /* CatchClause */:
  117454. return spanForNode(n.parent);
  117455. case 240 /* TryStatement */:
  117456. // Could be the try-block, or the finally-block.
  117457. var tryStatement = n.parent;
  117458. if (tryStatement.tryBlock === n) {
  117459. return spanForNode(n.parent);
  117460. }
  117461. else if (tryStatement.finallyBlock === n) {
  117462. var node = ts.findChildOfKind(tryStatement, 92 /* FinallyKeyword */, sourceFile);
  117463. if (node)
  117464. return spanForNode(node);
  117465. }
  117466. // falls through
  117467. default:
  117468. // Block was a standalone block. In this case we want to only collapse
  117469. // the span of the block, independent of any parent span.
  117470. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
  117471. }
  117472. case 250 /* ModuleBlock */:
  117473. return spanForNode(n.parent);
  117474. case 245 /* ClassDeclaration */:
  117475. case 214 /* ClassExpression */:
  117476. case 246 /* InterfaceDeclaration */:
  117477. case 248 /* EnumDeclaration */:
  117478. case 251 /* CaseBlock */:
  117479. return spanForNode(n);
  117480. case 193 /* ObjectLiteralExpression */:
  117481. return spanForObjectOrArrayLiteral(n);
  117482. case 192 /* ArrayLiteralExpression */:
  117483. return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */);
  117484. case 266 /* JsxElement */:
  117485. return spanForJSXElement(n);
  117486. case 270 /* JsxFragment */:
  117487. return spanForJSXFragment(n);
  117488. case 267 /* JsxSelfClosingElement */:
  117489. case 268 /* JsxOpeningElement */:
  117490. return spanForJSXAttributes(n.attributes);
  117491. case 211 /* TemplateExpression */:
  117492. case 14 /* NoSubstitutionTemplateLiteral */:
  117493. return spanForTemplateLiteral(n);
  117494. }
  117495. function spanForJSXElement(node) {
  117496. var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd());
  117497. var tagName = node.openingElement.tagName.getText(sourceFile);
  117498. var bannerText = "<" + tagName + ">...</" + tagName + ">";
  117499. return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
  117500. }
  117501. function spanForJSXFragment(node) {
  117502. var textSpan = ts.createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd());
  117503. var bannerText = "<>...</>";
  117504. return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
  117505. }
  117506. function spanForJSXAttributes(node) {
  117507. if (node.properties.length === 0) {
  117508. return undefined;
  117509. }
  117510. return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
  117511. }
  117512. function spanForTemplateLiteral(node) {
  117513. if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) {
  117514. return undefined;
  117515. }
  117516. return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
  117517. }
  117518. function spanForObjectOrArrayLiteral(node, open) {
  117519. if (open === void 0) { open = 18 /* OpenBraceToken */; }
  117520. // If the block has no leading keywords and is inside an array literal or call expression,
  117521. // we only want to collapse the span of the block.
  117522. // Otherwise, the collapsed section will include the end of the previous line.
  117523. return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open);
  117524. }
  117525. function spanForNode(hintSpanNode, autoCollapse, useFullStart, open, close) {
  117526. if (autoCollapse === void 0) { autoCollapse = false; }
  117527. if (useFullStart === void 0) { useFullStart = true; }
  117528. if (open === void 0) { open = 18 /* OpenBraceToken */; }
  117529. if (close === void 0) { close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; }
  117530. var openToken = ts.findChildOfKind(n, open, sourceFile);
  117531. var closeToken = ts.findChildOfKind(n, close, sourceFile);
  117532. return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart);
  117533. }
  117534. }
  117535. function functionSpan(node, body, sourceFile) {
  117536. var openToken = ts.isNodeArrayMultiLine(node.parameters, sourceFile)
  117537. ? ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile)
  117538. : ts.findChildOfKind(body, 18 /* OpenBraceToken */, sourceFile);
  117539. var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile);
  117540. return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 202 /* ArrowFunction */);
  117541. }
  117542. function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) {
  117543. if (autoCollapse === void 0) { autoCollapse = false; }
  117544. if (useFullStart === void 0) { useFullStart = true; }
  117545. var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
  117546. return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
  117547. }
  117548. function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
  117549. if (hintSpan === void 0) { hintSpan = textSpan; }
  117550. if (autoCollapse === void 0) { autoCollapse = false; }
  117551. if (bannerText === void 0) { bannerText = "..."; }
  117552. return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
  117553. }
  117554. })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
  117555. })(ts || (ts = {}));
  117556. /* @internal */
  117557. var ts;
  117558. (function (ts) {
  117559. // Note(cyrusn): this enum is ordered from strongest match type to weakest match type.
  117560. var PatternMatchKind;
  117561. (function (PatternMatchKind) {
  117562. PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact";
  117563. PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix";
  117564. PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring";
  117565. PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase";
  117566. })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {}));
  117567. function createPatternMatch(kind, isCaseSensitive) {
  117568. return {
  117569. kind: kind,
  117570. isCaseSensitive: isCaseSensitive
  117571. };
  117572. }
  117573. function createPatternMatcher(pattern) {
  117574. // We'll often see the same candidate string many times when searching (For example, when
  117575. // we see the name of a module that is used everywhere, or the name of an overload). As
  117576. // such, we cache the information we compute about the candidate for the life of this
  117577. // pattern matcher so we don't have to compute it multiple times.
  117578. var stringToWordSpans = ts.createMap();
  117579. var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); });
  117580. // A segment is considered invalid if we couldn't find any words in it.
  117581. if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; }))
  117582. return undefined;
  117583. return {
  117584. getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); },
  117585. getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); },
  117586. patternContainsDots: dotSeparatedSegments.length > 1
  117587. };
  117588. }
  117589. ts.createPatternMatcher = createPatternMatcher;
  117590. function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) {
  117591. // First, check that the last part of the dot separated pattern matches the name of the
  117592. // candidate. If not, then there's no point in proceeding and doing the more
  117593. // expensive work.
  117594. var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans);
  117595. if (!candidateMatch) {
  117596. return undefined;
  117597. }
  117598. // -1 because the last part was checked against the name, and only the rest
  117599. // of the parts are checked against the container.
  117600. if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
  117601. // There weren't enough container parts to match against the pattern parts.
  117602. // So this definitely doesn't match.
  117603. return undefined;
  117604. }
  117605. var bestMatch;
  117606. for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
  117607. bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
  117608. }
  117609. return bestMatch;
  117610. }
  117611. function getWordSpans(word, stringToWordSpans) {
  117612. var spans = stringToWordSpans.get(word);
  117613. if (!spans) {
  117614. stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
  117615. }
  117616. return spans;
  117617. }
  117618. function matchTextChunk(candidate, chunk, stringToWordSpans) {
  117619. var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
  117620. if (index === 0) {
  117621. // a) Check if the word is a prefix of the candidate, in a case insensitive or
  117622. // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match.
  117623. return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
  117624. }
  117625. if (chunk.isLowerCase) {
  117626. if (index === -1)
  117627. return undefined;
  117628. // b) If the part is entirely lowercase, then check if it is contained anywhere in the
  117629. // candidate in a case insensitive manner. If so, return that there was a substring
  117630. // match.
  117631. //
  117632. // Note: We only have a substring match if the lowercase part is prefix match of some
  117633. // word part. That way we don't match something like 'Class' when the user types 'a'.
  117634. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
  117635. var wordSpans = getWordSpans(candidate, stringToWordSpans);
  117636. for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
  117637. var span = wordSpans_1[_i];
  117638. if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) {
  117639. return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false));
  117640. }
  117641. }
  117642. // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
  117643. // We could check every character boundary start of the candidate for the pattern. However, that's
  117644. // an m * n operation in the wost case. Instead, find the first instance of the pattern
  117645. // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
  117646. // filter the list based on a substring that starts on a capital letter and also with a lowercase one.
  117647. // (Pattern: fogbar, Candidate: quuxfogbarFogBar).
  117648. if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) {
  117649. return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false);
  117650. }
  117651. }
  117652. else {
  117653. // d) If the part was not entirely lowercase, then check if it is contained in the
  117654. // candidate in a case *sensitive* manner. If so, return that there was a substring
  117655. // match.
  117656. if (candidate.indexOf(chunk.text) > 0) {
  117657. return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true);
  117658. }
  117659. // e) If the part was not entirely lowercase, then attempt a camel cased match as well.
  117660. if (chunk.characterSpans.length > 0) {
  117661. var candidateParts = getWordSpans(candidate, stringToWordSpans);
  117662. var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true
  117663. : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined;
  117664. if (isCaseSensitive !== undefined) {
  117665. return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive);
  117666. }
  117667. }
  117668. }
  117669. }
  117670. function matchSegment(candidate, segment, stringToWordSpans) {
  117671. // First check if the segment matches as is. This is also useful if the segment contains
  117672. // characters we would normally strip when splitting into parts that we also may want to
  117673. // match in the candidate. For example if the segment is "@int" and the candidate is
  117674. // "@int", then that will show up as an exact match here.
  117675. //
  117676. // Note: if the segment contains a space or an asterisk then we must assume that it's a
  117677. // multi-word segment.
  117678. if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) {
  117679. var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
  117680. if (match)
  117681. return match;
  117682. }
  117683. // The logic for pattern matching is now as follows:
  117684. //
  117685. // 1) Break the segment passed in into words. Breaking is rather simple and a
  117686. // good way to think about it that if gives you all the individual alphanumeric words
  117687. // of the pattern.
  117688. //
  117689. // 2) For each word try to match the word against the candidate value.
  117690. //
  117691. // 3) Matching is as follows:
  117692. //
  117693. // a) Check if the word is a prefix of the candidate, in a case insensitive or
  117694. // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match.
  117695. //
  117696. // If the word is entirely lowercase:
  117697. // b) Then check if it is contained anywhere in the
  117698. // candidate in a case insensitive manner. If so, return that there was a substring
  117699. // match.
  117700. //
  117701. // Note: We only have a substring match if the lowercase part is prefix match of
  117702. // some word part. That way we don't match something like 'Class' when the user
  117703. // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
  117704. // 'a').
  117705. //
  117706. // c) The word is all lower case. Is it a case insensitive substring of the candidate starting
  117707. // on a part boundary of the candidate?
  117708. //
  117709. // Else:
  117710. // d) If the word was not entirely lowercase, then check if it is contained in the
  117711. // candidate in a case *sensitive* manner. If so, return that there was a substring
  117712. // match.
  117713. //
  117714. // e) If the word was not entirely lowercase, then attempt a camel cased match as
  117715. // well.
  117716. //
  117717. // Only if all words have some sort of match is the pattern considered matched.
  117718. var subWordTextChunks = segment.subWordTextChunks;
  117719. var bestMatch;
  117720. for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
  117721. var subWordTextChunk = subWordTextChunks_1[_i];
  117722. bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
  117723. }
  117724. return bestMatch;
  117725. }
  117726. function betterMatch(a, b) {
  117727. return ts.min(a, b, compareMatches);
  117728. }
  117729. function compareMatches(a, b) {
  117730. return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */
  117731. : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
  117732. }
  117733. function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) {
  117734. if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; }
  117735. return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match.
  117736. && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); });
  117737. }
  117738. function equalChars(ch1, ch2, ignoreCase) {
  117739. return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2;
  117740. }
  117741. function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
  117742. var chunkCharacterSpans = chunk.characterSpans;
  117743. // Note: we may have more pattern parts than candidate parts. This is because multiple
  117744. // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI".
  117745. // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U
  117746. // and I will both match in UI.
  117747. var currentCandidate = 0;
  117748. var currentChunkSpan = 0;
  117749. var firstMatch;
  117750. var contiguous;
  117751. while (true) {
  117752. // Let's consider our termination cases
  117753. if (currentChunkSpan === chunkCharacterSpans.length) {
  117754. return true;
  117755. }
  117756. else if (currentCandidate === candidateParts.length) {
  117757. // No match, since we still have more of the pattern to hit
  117758. return false;
  117759. }
  117760. var candidatePart = candidateParts[currentCandidate];
  117761. var gotOneMatchThisCandidate = false;
  117762. // Consider the case of matching SiUI against SimpleUIElement. The candidate parts
  117763. // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si'
  117764. // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to
  117765. // still keep matching pattern parts against that candidate part.
  117766. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
  117767. var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
  117768. if (gotOneMatchThisCandidate) {
  117769. // We've already gotten one pattern part match in this candidate. We will
  117770. // only continue trying to consumer pattern parts if the last part and this
  117771. // part are both upper case.
  117772. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) ||
  117773. !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
  117774. break;
  117775. }
  117776. }
  117777. if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
  117778. break;
  117779. }
  117780. gotOneMatchThisCandidate = true;
  117781. firstMatch = firstMatch === undefined ? currentCandidate : firstMatch;
  117782. // If we were contiguous, then keep that value. If we weren't, then keep that
  117783. // value. If we don't know, then set the value to 'true' as an initial match is
  117784. // obviously contiguous.
  117785. contiguous = contiguous === undefined ? true : contiguous;
  117786. candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
  117787. }
  117788. // Check if we matched anything at all. If we didn't, then we need to unset the
  117789. // contiguous bit if we currently had it set.
  117790. // If we haven't set the bit yet, then that means we haven't matched anything so
  117791. // far, and we don't want to change that.
  117792. if (!gotOneMatchThisCandidate && contiguous !== undefined) {
  117793. contiguous = false;
  117794. }
  117795. // Move onto the next candidate.
  117796. currentCandidate++;
  117797. }
  117798. }
  117799. function createSegment(text) {
  117800. return {
  117801. totalTextChunk: createTextChunk(text),
  117802. subWordTextChunks: breakPatternIntoTextChunks(text)
  117803. };
  117804. }
  117805. function isUpperCaseLetter(ch) {
  117806. // Fast check for the ascii range.
  117807. if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
  117808. return true;
  117809. }
  117810. if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
  117811. return false;
  117812. }
  117813. // TODO: find a way to determine this for any unicode characters in a
  117814. // non-allocating manner.
  117815. var str = String.fromCharCode(ch);
  117816. return str === str.toUpperCase();
  117817. }
  117818. function isLowerCaseLetter(ch) {
  117819. // Fast check for the ascii range.
  117820. if (ch >= 97 /* a */ && ch <= 122 /* z */) {
  117821. return true;
  117822. }
  117823. if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
  117824. return false;
  117825. }
  117826. // TODO: find a way to determine this for any unicode characters in a
  117827. // non-allocating manner.
  117828. var str = String.fromCharCode(ch);
  117829. return str === str.toLowerCase();
  117830. }
  117831. // Assumes 'value' is already lowercase.
  117832. function indexOfIgnoringCase(str, value) {
  117833. var n = str.length - value.length;
  117834. var _loop_6 = function (start) {
  117835. if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
  117836. return { value: start };
  117837. }
  117838. };
  117839. for (var start = 0; start <= n; start++) {
  117840. var state_1 = _loop_6(start);
  117841. if (typeof state_1 === "object")
  117842. return state_1.value;
  117843. }
  117844. return -1;
  117845. }
  117846. function toLowerCase(ch) {
  117847. // Fast convert for the ascii range.
  117848. if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
  117849. return 97 /* a */ + (ch - 65 /* A */);
  117850. }
  117851. if (ch < 127 /* maxAsciiCharacter */) {
  117852. return ch;
  117853. }
  117854. // TODO: find a way to compute this for any unicode characters in a
  117855. // non-allocating manner.
  117856. return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
  117857. }
  117858. function isDigit(ch) {
  117859. // TODO(cyrusn): Find a way to support this for unicode digits.
  117860. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  117861. }
  117862. function isWordChar(ch) {
  117863. return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */;
  117864. }
  117865. function breakPatternIntoTextChunks(pattern) {
  117866. var result = [];
  117867. var wordStart = 0;
  117868. var wordLength = 0;
  117869. for (var i = 0; i < pattern.length; i++) {
  117870. var ch = pattern.charCodeAt(i);
  117871. if (isWordChar(ch)) {
  117872. if (wordLength === 0) {
  117873. wordStart = i;
  117874. }
  117875. wordLength++;
  117876. }
  117877. else {
  117878. if (wordLength > 0) {
  117879. result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
  117880. wordLength = 0;
  117881. }
  117882. }
  117883. }
  117884. if (wordLength > 0) {
  117885. result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
  117886. }
  117887. return result;
  117888. }
  117889. function createTextChunk(text) {
  117890. var textLowerCase = text.toLowerCase();
  117891. return {
  117892. text: text,
  117893. textLowerCase: textLowerCase,
  117894. isLowerCase: text === textLowerCase,
  117895. characterSpans: breakIntoCharacterSpans(text)
  117896. };
  117897. }
  117898. function breakIntoCharacterSpans(identifier) {
  117899. return breakIntoSpans(identifier, /*word:*/ false);
  117900. }
  117901. ts.breakIntoCharacterSpans = breakIntoCharacterSpans;
  117902. function breakIntoWordSpans(identifier) {
  117903. return breakIntoSpans(identifier, /*word:*/ true);
  117904. }
  117905. ts.breakIntoWordSpans = breakIntoWordSpans;
  117906. function breakIntoSpans(identifier, word) {
  117907. var result = [];
  117908. var wordStart = 0;
  117909. for (var i = 1; i < identifier.length; i++) {
  117910. var lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
  117911. var currentIsDigit = isDigit(identifier.charCodeAt(i));
  117912. var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
  117913. var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart);
  117914. if (charIsPunctuation(identifier.charCodeAt(i - 1)) ||
  117915. charIsPunctuation(identifier.charCodeAt(i)) ||
  117916. lastIsDigit !== currentIsDigit ||
  117917. hasTransitionFromLowerToUpper ||
  117918. hasTransitionFromUpperToLower) {
  117919. if (!isAllPunctuation(identifier, wordStart, i)) {
  117920. result.push(ts.createTextSpan(wordStart, i - wordStart));
  117921. }
  117922. wordStart = i;
  117923. }
  117924. }
  117925. if (!isAllPunctuation(identifier, wordStart, identifier.length)) {
  117926. result.push(ts.createTextSpan(wordStart, identifier.length - wordStart));
  117927. }
  117928. return result;
  117929. }
  117930. function charIsPunctuation(ch) {
  117931. switch (ch) {
  117932. case 33 /* exclamation */:
  117933. case 34 /* doubleQuote */:
  117934. case 35 /* hash */:
  117935. case 37 /* percent */:
  117936. case 38 /* ampersand */:
  117937. case 39 /* singleQuote */:
  117938. case 40 /* openParen */:
  117939. case 41 /* closeParen */:
  117940. case 42 /* asterisk */:
  117941. case 44 /* comma */:
  117942. case 45 /* minus */:
  117943. case 46 /* dot */:
  117944. case 47 /* slash */:
  117945. case 58 /* colon */:
  117946. case 59 /* semicolon */:
  117947. case 63 /* question */:
  117948. case 64 /* at */:
  117949. case 91 /* openBracket */:
  117950. case 92 /* backslash */:
  117951. case 93 /* closeBracket */:
  117952. case 95 /* _ */:
  117953. case 123 /* openBrace */:
  117954. case 125 /* closeBrace */:
  117955. return true;
  117956. }
  117957. return false;
  117958. }
  117959. function isAllPunctuation(identifier, start, end) {
  117960. return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end);
  117961. }
  117962. function transitionFromUpperToLower(identifier, index, wordStart) {
  117963. // Cases this supports:
  117964. // 1) IDisposable -> I, Disposable
  117965. // 2) UIElement -> UI, Element
  117966. // 3) HTMLDocument -> HTML, Document
  117967. //
  117968. // etc.
  117969. // We have a transition from an upper to a lower letter here. But we only
  117970. // want to break if all the letters that preceded are uppercase. i.e. if we
  117971. // have "Foo" we don't want to break that into "F, oo". But if we have
  117972. // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI,
  117973. // Foo". i.e. the last uppercase letter belongs to the lowercase letters
  117974. // that follows. Note: this will make the following not split properly:
  117975. // "HELLOthere". However, these sorts of names do not show up in .Net
  117976. // programs.
  117977. return index !== wordStart
  117978. && index + 1 < identifier.length
  117979. && isUpperCaseLetter(identifier.charCodeAt(index))
  117980. && isLowerCaseLetter(identifier.charCodeAt(index + 1))
  117981. && every(identifier, isUpperCaseLetter, wordStart, index);
  117982. }
  117983. function transitionFromLowerToUpper(identifier, word, index) {
  117984. var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
  117985. var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
  117986. // See if the casing indicates we're starting a new word. Note: if we're breaking on
  117987. // words, then just seeing an upper case character isn't enough. Instead, it has to
  117988. // be uppercase and the previous character can't be uppercase.
  117989. //
  117990. // For example, breaking "AddMetadata" on words would make: Add Metadata
  117991. //
  117992. // on characters would be: A dd M etadata
  117993. //
  117994. // Break "AM" on words would be: AM
  117995. //
  117996. // on characters would be: A M
  117997. //
  117998. // We break the search string on characters. But we break the symbol name on words.
  117999. return currentIsUpper && (!word || !lastIsUpper);
  118000. }
  118001. function everyInRange(start, end, pred) {
  118002. for (var i = start; i < end; i++) {
  118003. if (!pred(i)) {
  118004. return false;
  118005. }
  118006. }
  118007. return true;
  118008. }
  118009. function every(s, pred, start, end) {
  118010. if (start === void 0) { start = 0; }
  118011. if (end === void 0) { end = s.length; }
  118012. return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); });
  118013. }
  118014. })(ts || (ts = {}));
  118015. var ts;
  118016. (function (ts) {
  118017. function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
  118018. if (readImportFiles === void 0) { readImportFiles = true; }
  118019. if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
  118020. var pragmaContext = {
  118021. languageVersion: 1 /* ES5 */,
  118022. pragmas: undefined,
  118023. checkJsDirective: undefined,
  118024. referencedFiles: [],
  118025. typeReferenceDirectives: [],
  118026. libReferenceDirectives: [],
  118027. amdDependencies: [],
  118028. hasNoDefaultLib: undefined,
  118029. moduleName: undefined
  118030. };
  118031. var importedFiles = [];
  118032. var ambientExternalModules;
  118033. var lastToken;
  118034. var currentToken;
  118035. var braceNesting = 0;
  118036. // assume that text represent an external module if it contains at least one top level import/export
  118037. // ambient modules that are found inside external modules are interpreted as module augmentations
  118038. var externalModule = false;
  118039. function nextToken() {
  118040. lastToken = currentToken;
  118041. currentToken = ts.scanner.scan();
  118042. if (currentToken === 18 /* OpenBraceToken */) {
  118043. braceNesting++;
  118044. }
  118045. else if (currentToken === 19 /* CloseBraceToken */) {
  118046. braceNesting--;
  118047. }
  118048. return currentToken;
  118049. }
  118050. function getFileReference() {
  118051. var fileName = ts.scanner.getTokenValue();
  118052. var pos = ts.scanner.getTokenPos();
  118053. return { fileName: fileName, pos: pos, end: pos + fileName.length };
  118054. }
  118055. function recordAmbientExternalModule() {
  118056. if (!ambientExternalModules) {
  118057. ambientExternalModules = [];
  118058. }
  118059. ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
  118060. }
  118061. function recordModuleName() {
  118062. importedFiles.push(getFileReference());
  118063. markAsExternalModuleIfTopLevel();
  118064. }
  118065. function markAsExternalModuleIfTopLevel() {
  118066. if (braceNesting === 0) {
  118067. externalModule = true;
  118068. }
  118069. }
  118070. /**
  118071. * Returns true if at least one token was consumed from the stream
  118072. */
  118073. function tryConsumeDeclare() {
  118074. var token = ts.scanner.getToken();
  118075. if (token === 130 /* DeclareKeyword */) {
  118076. // declare module "mod"
  118077. token = nextToken();
  118078. if (token === 135 /* ModuleKeyword */) {
  118079. token = nextToken();
  118080. if (token === 10 /* StringLiteral */) {
  118081. recordAmbientExternalModule();
  118082. }
  118083. }
  118084. return true;
  118085. }
  118086. return false;
  118087. }
  118088. /**
  118089. * Returns true if at least one token was consumed from the stream
  118090. */
  118091. function tryConsumeImport() {
  118092. if (lastToken === 24 /* DotToken */) {
  118093. return false;
  118094. }
  118095. var token = ts.scanner.getToken();
  118096. if (token === 96 /* ImportKeyword */) {
  118097. token = nextToken();
  118098. if (token === 20 /* OpenParenToken */) {
  118099. token = nextToken();
  118100. if (token === 10 /* StringLiteral */) {
  118101. // import("mod");
  118102. recordModuleName();
  118103. return true;
  118104. }
  118105. }
  118106. else if (token === 10 /* StringLiteral */) {
  118107. // import "mod";
  118108. recordModuleName();
  118109. return true;
  118110. }
  118111. else {
  118112. if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
  118113. token = nextToken();
  118114. if (token === 149 /* FromKeyword */) {
  118115. token = nextToken();
  118116. if (token === 10 /* StringLiteral */) {
  118117. // import d from "mod";
  118118. recordModuleName();
  118119. return true;
  118120. }
  118121. }
  118122. else if (token === 62 /* EqualsToken */) {
  118123. if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
  118124. return true;
  118125. }
  118126. }
  118127. else if (token === 27 /* CommaToken */) {
  118128. // consume comma and keep going
  118129. token = nextToken();
  118130. }
  118131. else {
  118132. // unknown syntax
  118133. return true;
  118134. }
  118135. }
  118136. if (token === 18 /* OpenBraceToken */) {
  118137. token = nextToken();
  118138. // consume "{ a as B, c, d as D}" clauses
  118139. // make sure that it stops on EOF
  118140. while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
  118141. token = nextToken();
  118142. }
  118143. if (token === 19 /* CloseBraceToken */) {
  118144. token = nextToken();
  118145. if (token === 149 /* FromKeyword */) {
  118146. token = nextToken();
  118147. if (token === 10 /* StringLiteral */) {
  118148. // import {a as A} from "mod";
  118149. // import d, {a, b as B} from "mod"
  118150. recordModuleName();
  118151. }
  118152. }
  118153. }
  118154. }
  118155. else if (token === 41 /* AsteriskToken */) {
  118156. token = nextToken();
  118157. if (token === 123 /* AsKeyword */) {
  118158. token = nextToken();
  118159. if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
  118160. token = nextToken();
  118161. if (token === 149 /* FromKeyword */) {
  118162. token = nextToken();
  118163. if (token === 10 /* StringLiteral */) {
  118164. // import * as NS from "mod"
  118165. // import d, * as NS from "mod"
  118166. recordModuleName();
  118167. }
  118168. }
  118169. }
  118170. }
  118171. }
  118172. }
  118173. return true;
  118174. }
  118175. return false;
  118176. }
  118177. function tryConsumeExport() {
  118178. var token = ts.scanner.getToken();
  118179. if (token === 89 /* ExportKeyword */) {
  118180. markAsExternalModuleIfTopLevel();
  118181. token = nextToken();
  118182. if (token === 18 /* OpenBraceToken */) {
  118183. token = nextToken();
  118184. // consume "{ a as B, c, d as D}" clauses
  118185. // make sure it stops on EOF
  118186. while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
  118187. token = nextToken();
  118188. }
  118189. if (token === 19 /* CloseBraceToken */) {
  118190. token = nextToken();
  118191. if (token === 149 /* FromKeyword */) {
  118192. token = nextToken();
  118193. if (token === 10 /* StringLiteral */) {
  118194. // export {a as A} from "mod";
  118195. // export {a, b as B} from "mod"
  118196. recordModuleName();
  118197. }
  118198. }
  118199. }
  118200. }
  118201. else if (token === 41 /* AsteriskToken */) {
  118202. token = nextToken();
  118203. if (token === 149 /* FromKeyword */) {
  118204. token = nextToken();
  118205. if (token === 10 /* StringLiteral */) {
  118206. // export * from "mod"
  118207. recordModuleName();
  118208. }
  118209. }
  118210. }
  118211. else if (token === 96 /* ImportKeyword */) {
  118212. token = nextToken();
  118213. if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
  118214. token = nextToken();
  118215. if (token === 62 /* EqualsToken */) {
  118216. if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
  118217. return true;
  118218. }
  118219. }
  118220. }
  118221. }
  118222. return true;
  118223. }
  118224. return false;
  118225. }
  118226. function tryConsumeRequireCall(skipCurrentToken) {
  118227. var token = skipCurrentToken ? nextToken() : ts.scanner.getToken();
  118228. if (token === 139 /* RequireKeyword */) {
  118229. token = nextToken();
  118230. if (token === 20 /* OpenParenToken */) {
  118231. token = nextToken();
  118232. if (token === 10 /* StringLiteral */) {
  118233. // require("mod");
  118234. recordModuleName();
  118235. }
  118236. }
  118237. return true;
  118238. }
  118239. return false;
  118240. }
  118241. function tryConsumeDefine() {
  118242. var token = ts.scanner.getToken();
  118243. if (token === 75 /* Identifier */ && ts.scanner.getTokenValue() === "define") {
  118244. token = nextToken();
  118245. if (token !== 20 /* OpenParenToken */) {
  118246. return true;
  118247. }
  118248. token = nextToken();
  118249. if (token === 10 /* StringLiteral */) {
  118250. // looks like define ("modname", ... - skip string literal and comma
  118251. token = nextToken();
  118252. if (token === 27 /* CommaToken */) {
  118253. token = nextToken();
  118254. }
  118255. else {
  118256. // unexpected token
  118257. return true;
  118258. }
  118259. }
  118260. // should be start of dependency list
  118261. if (token !== 22 /* OpenBracketToken */) {
  118262. return true;
  118263. }
  118264. // skip open bracket
  118265. token = nextToken();
  118266. // scan until ']' or EOF
  118267. while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
  118268. // record string literals as module names
  118269. if (token === 10 /* StringLiteral */) {
  118270. recordModuleName();
  118271. }
  118272. token = nextToken();
  118273. }
  118274. return true;
  118275. }
  118276. return false;
  118277. }
  118278. function processImports() {
  118279. ts.scanner.setText(sourceText);
  118280. nextToken();
  118281. // Look for:
  118282. // import "mod";
  118283. // import d from "mod"
  118284. // import {a as A } from "mod";
  118285. // import * as NS from "mod"
  118286. // import d, {a, b as B} from "mod"
  118287. // import i = require("mod");
  118288. // import("mod");
  118289. // export * from "mod"
  118290. // export {a as b} from "mod"
  118291. // export import i = require("mod")
  118292. // (for JavaScript files) require("mod")
  118293. // Do not look for:
  118294. // AnySymbol.import("mod")
  118295. // AnySymbol.nested.import("mod")
  118296. while (true) {
  118297. if (ts.scanner.getToken() === 1 /* EndOfFileToken */) {
  118298. break;
  118299. }
  118300. // check if at least one of alternative have moved scanner forward
  118301. if (tryConsumeDeclare() ||
  118302. tryConsumeImport() ||
  118303. tryConsumeExport() ||
  118304. (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) {
  118305. continue;
  118306. }
  118307. else {
  118308. nextToken();
  118309. }
  118310. }
  118311. ts.scanner.setText(undefined);
  118312. }
  118313. if (readImportFiles) {
  118314. processImports();
  118315. }
  118316. ts.processCommentPragmas(pragmaContext, sourceText);
  118317. ts.processPragmasIntoFields(pragmaContext, ts.noop);
  118318. if (externalModule) {
  118319. // for external modules module all nested ambient modules are augmentations
  118320. if (ambientExternalModules) {
  118321. // move all detected ambient modules to imported files since they need to be resolved
  118322. for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) {
  118323. var decl = ambientExternalModules_1[_i];
  118324. importedFiles.push(decl.ref);
  118325. }
  118326. }
  118327. return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
  118328. }
  118329. else {
  118330. // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
  118331. var ambientModuleNames = void 0;
  118332. if (ambientExternalModules) {
  118333. for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) {
  118334. var decl = ambientExternalModules_2[_a];
  118335. if (decl.depth === 0) {
  118336. if (!ambientModuleNames) {
  118337. ambientModuleNames = [];
  118338. }
  118339. ambientModuleNames.push(decl.ref.fileName);
  118340. }
  118341. else {
  118342. importedFiles.push(decl.ref);
  118343. }
  118344. }
  118345. }
  118346. return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
  118347. }
  118348. }
  118349. ts.preProcessFile = preProcessFile;
  118350. })(ts || (ts = {}));
  118351. /* @internal */
  118352. var ts;
  118353. (function (ts) {
  118354. var Rename;
  118355. (function (Rename) {
  118356. function getRenameInfo(program, sourceFile, position, options) {
  118357. var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position));
  118358. if (nodeIsEligibleForRename(node)) {
  118359. var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options);
  118360. if (renameInfo) {
  118361. return renameInfo;
  118362. }
  118363. }
  118364. return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
  118365. }
  118366. Rename.getRenameInfo = getRenameInfo;
  118367. function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) {
  118368. var symbol = typeChecker.getSymbolAtLocation(node);
  118369. if (!symbol)
  118370. return;
  118371. // Only allow a symbol to be renamed if it actually has at least one declaration.
  118372. var declarations = symbol.declarations;
  118373. if (!declarations || declarations.length === 0)
  118374. return;
  118375. // Disallow rename for elements that are defined in the standard TypeScript library.
  118376. if (declarations.some(isDefinedInLibraryFile)) {
  118377. return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
  118378. }
  118379. // Cannot rename `default` as in `import { default as foo } from "./someModule";
  118380. if (ts.isIdentifier(node) && node.originalKeywordKind === 84 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
  118381. return undefined;
  118382. }
  118383. if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) {
  118384. return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined;
  118385. }
  118386. var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
  118387. var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 154 /* ComputedPropertyName */)
  118388. ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
  118389. : undefined;
  118390. var displayName = specifierName || typeChecker.symbolToString(symbol);
  118391. var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
  118392. return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
  118393. }
  118394. function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
  118395. if (!ts.isExternalModuleNameRelative(node.text)) {
  118396. return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import);
  118397. }
  118398. var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile);
  118399. if (!moduleSourceFile)
  118400. return undefined;
  118401. var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index");
  118402. var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;
  118403. var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */;
  118404. var indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
  118405. // Span should only be the last component of the path. + 1 to account for the quote character.
  118406. var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
  118407. return {
  118408. canRename: true,
  118409. fileToRename: name,
  118410. kind: kind,
  118411. displayName: name,
  118412. fullDisplayName: name,
  118413. kindModifiers: "" /* none */,
  118414. triggerSpan: triggerSpan,
  118415. };
  118416. }
  118417. function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
  118418. return {
  118419. canRename: true,
  118420. fileToRename: undefined,
  118421. kind: kind,
  118422. displayName: displayName,
  118423. fullDisplayName: fullDisplayName,
  118424. kindModifiers: kindModifiers,
  118425. triggerSpan: createTriggerSpanForNode(node, sourceFile)
  118426. };
  118427. }
  118428. function getRenameInfoError(diagnostic) {
  118429. return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) };
  118430. }
  118431. function createTriggerSpanForNode(node, sourceFile) {
  118432. var start = node.getStart(sourceFile);
  118433. var width = node.getWidth(sourceFile);
  118434. if (ts.isStringLiteralLike(node)) {
  118435. // Exclude the quotes
  118436. start += 1;
  118437. width -= 2;
  118438. }
  118439. return ts.createTextSpan(start, width);
  118440. }
  118441. function nodeIsEligibleForRename(node) {
  118442. switch (node.kind) {
  118443. case 75 /* Identifier */:
  118444. case 76 /* PrivateIdentifier */:
  118445. case 10 /* StringLiteral */:
  118446. case 14 /* NoSubstitutionTemplateLiteral */:
  118447. case 104 /* ThisKeyword */:
  118448. return true;
  118449. case 8 /* NumericLiteral */:
  118450. return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node);
  118451. default:
  118452. return false;
  118453. }
  118454. }
  118455. })(Rename = ts.Rename || (ts.Rename = {}));
  118456. })(ts || (ts = {}));
  118457. /* @internal */
  118458. var ts;
  118459. (function (ts) {
  118460. var SmartSelectionRange;
  118461. (function (SmartSelectionRange) {
  118462. function getSmartSelectionRange(pos, sourceFile) {
  118463. var selectionRange = {
  118464. textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd())
  118465. };
  118466. var parentNode = sourceFile;
  118467. outer: while (true) {
  118468. var children = getSelectionChildren(parentNode);
  118469. if (!children.length)
  118470. break;
  118471. for (var i = 0; i < children.length; i++) {
  118472. var prevNode = children[i - 1];
  118473. var node = children[i];
  118474. var nextNode = children[i + 1];
  118475. if (node.getStart(sourceFile) > pos) {
  118476. break outer;
  118477. }
  118478. if (positionShouldSnapToNode(sourceFile, pos, node)) {
  118479. // 1. Blocks are effectively redundant with SyntaxLists.
  118480. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping
  118481. // of things that should be considered independently.
  118482. // 3. A VariableStatement’s children are just a VaraiableDeclarationList and a semicolon.
  118483. // 4. A lone VariableDeclaration in a VaraibleDeclaration feels redundant with the VariableStatement.
  118484. //
  118485. // Dive in without pushing a selection range.
  118486. if (ts.isBlock(node)
  118487. || ts.isTemplateSpan(node) || ts.isTemplateHead(node) || ts.isTemplateTail(node)
  118488. || prevNode && ts.isTemplateHead(prevNode)
  118489. || ts.isVariableDeclarationList(node) && ts.isVariableStatement(parentNode)
  118490. || ts.isSyntaxList(node) && ts.isVariableDeclarationList(parentNode)
  118491. || ts.isVariableDeclaration(node) && ts.isSyntaxList(parentNode) && children.length === 1) {
  118492. parentNode = node;
  118493. break;
  118494. }
  118495. // Synthesize a stop for '${ ... }' since '${' and '}' actually belong to siblings.
  118496. if (ts.isTemplateSpan(parentNode) && nextNode && ts.isTemplateMiddleOrTemplateTail(nextNode)) {
  118497. var start_2 = node.getFullStart() - "${".length;
  118498. var end_2 = nextNode.getStart() + "}".length;
  118499. pushSelectionRange(start_2, end_2);
  118500. }
  118501. // Blocks with braces, brackets, parens, or JSX tags on separate lines should be
  118502. // selected from open to close, including whitespace but not including the braces/etc. themselves.
  118503. var isBetweenMultiLineBookends = ts.isSyntaxList(node)
  118504. && isListOpener(prevNode)
  118505. && isListCloser(nextNode)
  118506. && !ts.positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
  118507. var jsDocCommentStart = ts.hasJSDocNodes(node) && node.jsDoc[0].getStart();
  118508. var start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
  118509. var end = isBetweenMultiLineBookends ? nextNode.getStart() : node.getEnd();
  118510. if (ts.isNumber(jsDocCommentStart)) {
  118511. pushSelectionRange(jsDocCommentStart, end);
  118512. }
  118513. pushSelectionRange(start, end);
  118514. // String literals should have a stop both inside and outside their quotes.
  118515. if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) {
  118516. pushSelectionRange(start + 1, end - 1);
  118517. }
  118518. parentNode = node;
  118519. break;
  118520. }
  118521. // If we made it to the end of the for loop, we’re done.
  118522. // In practice, I’ve only seen this happen at the very end
  118523. // of a SourceFile.
  118524. if (i === children.length - 1) {
  118525. break outer;
  118526. }
  118527. }
  118528. }
  118529. return selectionRange;
  118530. function pushSelectionRange(start, end) {
  118531. // Skip empty ranges
  118532. if (start !== end) {
  118533. var textSpan = ts.createTextSpanFromBounds(start, end);
  118534. if (!selectionRange || (
  118535. // Skip ranges that are identical to the parent
  118536. !ts.textSpansEqual(textSpan, selectionRange.textSpan) &&
  118537. // Skip ranges that don’t contain the original position
  118538. ts.textSpanIntersectsWithPosition(textSpan, pos))) {
  118539. selectionRange = __assign({ textSpan: textSpan }, selectionRange && { parent: selectionRange });
  118540. }
  118541. }
  118542. }
  118543. }
  118544. SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange;
  118545. /**
  118546. * Like `ts.positionBelongsToNode`, except positions immediately after nodes
  118547. * count too, unless that position belongs to the next node. In effect, makes
  118548. * selections able to snap to preceding tokens when the cursor is on the tail
  118549. * end of them with only whitespace ahead.
  118550. * @param sourceFile The source file containing the nodes.
  118551. * @param pos The position to check.
  118552. * @param node The candidate node to snap to.
  118553. */
  118554. function positionShouldSnapToNode(sourceFile, pos, node) {
  118555. // Can’t use 'ts.positionBelongsToNode()' here because it cleverly accounts
  118556. // for missing nodes, which can’t really be considered when deciding what
  118557. // to select.
  118558. ts.Debug.assert(node.pos <= pos);
  118559. if (pos < node.end) {
  118560. return true;
  118561. }
  118562. var nodeEnd = node.getEnd();
  118563. if (nodeEnd === pos) {
  118564. return ts.getTouchingPropertyName(sourceFile, pos).pos < node.end;
  118565. }
  118566. return false;
  118567. }
  118568. var isImport = ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration);
  118569. /**
  118570. * Gets the children of a node to be considered for selection ranging,
  118571. * transforming them into an artificial tree according to their intuitive
  118572. * grouping where no grouping actually exists in the parse tree. For example,
  118573. * top-level imports are grouped into their own SyntaxList so they can be
  118574. * selected all together, even though in the AST they’re just siblings of each
  118575. * other as well as of other top-level statements and declarations.
  118576. */
  118577. function getSelectionChildren(node) {
  118578. // Group top-level imports
  118579. if (ts.isSourceFile(node)) {
  118580. return groupChildren(node.getChildAt(0).getChildren(), isImport);
  118581. }
  118582. // Mapped types _look_ like ObjectTypes with a single member,
  118583. // but in fact don’t contain a SyntaxList or a node containing
  118584. // the “key/value” pair like ObjectTypes do, but it seems intuitive
  118585. // that the selection would snap to those points. The philosophy
  118586. // of choosing a selection range is not so much about what the
  118587. // syntax currently _is_ as what the syntax might easily become
  118588. // if the user is making a selection; e.g., we synthesize a selection
  118589. // around the “key/value” pair not because there’s a node there, but
  118590. // because it allows the mapped type to become an object type with a
  118591. // few keystrokes.
  118592. if (ts.isMappedTypeNode(node)) {
  118593. var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1);
  118594. var closeBraceToken = ts.Debug.assertDefined(children.pop());
  118595. ts.Debug.assertEqual(openBraceToken.kind, 18 /* OpenBraceToken */);
  118596. ts.Debug.assertEqual(closeBraceToken.kind, 19 /* CloseBraceToken */);
  118597. // Group `-/+readonly` and `-/+?`
  118598. var groupedWithPlusMinusTokens = groupChildren(children, function (child) {
  118599. return child === node.readonlyToken || child.kind === 138 /* ReadonlyKeyword */ ||
  118600. child === node.questionToken || child.kind === 57 /* QuestionToken */;
  118601. });
  118602. // Group type parameter with surrounding brackets
  118603. var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) {
  118604. var kind = _a.kind;
  118605. return kind === 22 /* OpenBracketToken */ ||
  118606. kind === 155 /* TypeParameter */ ||
  118607. kind === 23 /* CloseBracketToken */;
  118608. });
  118609. return [
  118610. openBraceToken,
  118611. // Pivot on `:`
  118612. createSyntaxList(splitChildren(groupedWithBrackets, function (_a) {
  118613. var kind = _a.kind;
  118614. return kind === 58 /* ColonToken */;
  118615. })),
  118616. closeBraceToken,
  118617. ];
  118618. }
  118619. // Group modifiers and property name, then pivot on `:`.
  118620. if (ts.isPropertySignature(node)) {
  118621. var children = groupChildren(node.getChildren(), function (child) {
  118622. return child === node.name || ts.contains(node.modifiers, child);
  118623. });
  118624. return splitChildren(children, function (_a) {
  118625. var kind = _a.kind;
  118626. return kind === 58 /* ColonToken */;
  118627. });
  118628. }
  118629. // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`.
  118630. if (ts.isParameter(node)) {
  118631. var groupedDotDotDotAndName_1 = groupChildren(node.getChildren(), function (child) {
  118632. return child === node.dotDotDotToken || child === node.name;
  118633. });
  118634. var groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName_1, function (child) {
  118635. return child === groupedDotDotDotAndName_1[0] || child === node.questionToken;
  118636. });
  118637. return splitChildren(groupedWithQuestionToken, function (_a) {
  118638. var kind = _a.kind;
  118639. return kind === 62 /* EqualsToken */;
  118640. });
  118641. }
  118642. // Pivot on '='
  118643. if (ts.isBindingElement(node)) {
  118644. return splitChildren(node.getChildren(), function (_a) {
  118645. var kind = _a.kind;
  118646. return kind === 62 /* EqualsToken */;
  118647. });
  118648. }
  118649. return node.getChildren();
  118650. }
  118651. /**
  118652. * Groups sibling nodes together into their own SyntaxList if they
  118653. * a) are adjacent, AND b) match a predicate function.
  118654. */
  118655. function groupChildren(children, groupOn) {
  118656. var result = [];
  118657. var group;
  118658. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  118659. var child = children_1[_i];
  118660. if (groupOn(child)) {
  118661. group = group || [];
  118662. group.push(child);
  118663. }
  118664. else {
  118665. if (group) {
  118666. result.push(createSyntaxList(group));
  118667. group = undefined;
  118668. }
  118669. result.push(child);
  118670. }
  118671. }
  118672. if (group) {
  118673. result.push(createSyntaxList(group));
  118674. }
  118675. return result;
  118676. }
  118677. /**
  118678. * Splits sibling nodes into up to four partitions:
  118679. * 1) everything left of the first node matched by `pivotOn`,
  118680. * 2) the first node matched by `pivotOn`,
  118681. * 3) everything right of the first node matched by `pivotOn`,
  118682. * 4) a trailing semicolon, if `separateTrailingSemicolon` is enabled.
  118683. * The left and right groups, if not empty, will each be grouped into their own containing SyntaxList.
  118684. * @param children The sibling nodes to split.
  118685. * @param pivotOn The predicate function to match the node to be the pivot. The first node that matches
  118686. * the predicate will be used; any others that may match will be included into the right-hand group.
  118687. * @param separateTrailingSemicolon If the last token is a semicolon, it will be returned as a separate
  118688. * child rather than be included in the right-hand group.
  118689. */
  118690. function splitChildren(children, pivotOn, separateTrailingSemicolon) {
  118691. if (separateTrailingSemicolon === void 0) { separateTrailingSemicolon = true; }
  118692. if (children.length < 2) {
  118693. return children;
  118694. }
  118695. var splitTokenIndex = ts.findIndex(children, pivotOn);
  118696. if (splitTokenIndex === -1) {
  118697. return children;
  118698. }
  118699. var leftChildren = children.slice(0, splitTokenIndex);
  118700. var splitToken = children[splitTokenIndex];
  118701. var lastToken = ts.last(children);
  118702. var separateLastToken = separateTrailingSemicolon && lastToken.kind === 26 /* SemicolonToken */;
  118703. var rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : undefined);
  118704. var result = ts.compact([
  118705. leftChildren.length ? createSyntaxList(leftChildren) : undefined,
  118706. splitToken,
  118707. rightChildren.length ? createSyntaxList(rightChildren) : undefined,
  118708. ]);
  118709. return separateLastToken ? result.concat(lastToken) : result;
  118710. }
  118711. function createSyntaxList(children) {
  118712. ts.Debug.assertGreaterThanOrEqual(children.length, 1);
  118713. var syntaxList = ts.createNode(323 /* SyntaxList */, children[0].pos, ts.last(children).end);
  118714. syntaxList._children = children;
  118715. return syntaxList;
  118716. }
  118717. function isListOpener(token) {
  118718. var kind = token && token.kind;
  118719. return kind === 18 /* OpenBraceToken */
  118720. || kind === 22 /* OpenBracketToken */
  118721. || kind === 20 /* OpenParenToken */
  118722. || kind === 268 /* JsxOpeningElement */;
  118723. }
  118724. function isListCloser(token) {
  118725. var kind = token && token.kind;
  118726. return kind === 19 /* CloseBraceToken */
  118727. || kind === 23 /* CloseBracketToken */
  118728. || kind === 21 /* CloseParenToken */
  118729. || kind === 269 /* JsxClosingElement */;
  118730. }
  118731. })(SmartSelectionRange = ts.SmartSelectionRange || (ts.SmartSelectionRange = {}));
  118732. })(ts || (ts = {}));
  118733. /* @internal */
  118734. var ts;
  118735. (function (ts) {
  118736. var SignatureHelp;
  118737. (function (SignatureHelp) {
  118738. var InvocationKind;
  118739. (function (InvocationKind) {
  118740. InvocationKind[InvocationKind["Call"] = 0] = "Call";
  118741. InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs";
  118742. InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual";
  118743. })(InvocationKind || (InvocationKind = {}));
  118744. function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
  118745. var typeChecker = program.getTypeChecker();
  118746. // Decide whether to show signature help
  118747. var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position);
  118748. if (!startingToken) {
  118749. // We are at the beginning of the file
  118750. return undefined;
  118751. }
  118752. // Only need to be careful if the user typed a character and signature help wasn't showing.
  118753. var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped";
  118754. // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it.
  118755. if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) {
  118756. return undefined;
  118757. }
  118758. var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked";
  118759. var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked);
  118760. if (!argumentInfo)
  118761. return undefined;
  118762. cancellationToken.throwIfCancellationRequested();
  118763. // Extra syntactic and semantic filtering of signature help
  118764. var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
  118765. cancellationToken.throwIfCancellationRequested();
  118766. if (!candidateInfo) {
  118767. // We didn't have any sig help items produced by the TS compiler. If this is a JS
  118768. // file, then see if we can figure out anything better.
  118769. return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
  118770. }
  118771. return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
  118772. return candidateInfo.kind === 0 /* Candidate */
  118773. ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker)
  118774. : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker);
  118775. });
  118776. }
  118777. SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
  118778. var CandidateOrTypeKind;
  118779. (function (CandidateOrTypeKind) {
  118780. CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate";
  118781. CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type";
  118782. })(CandidateOrTypeKind || (CandidateOrTypeKind = {}));
  118783. function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
  118784. var invocation = _a.invocation, argumentCount = _a.argumentCount;
  118785. switch (invocation.kind) {
  118786. case 0 /* Call */: {
  118787. if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) {
  118788. return undefined;
  118789. }
  118790. var candidates = [];
  118791. var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217
  118792. return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature };
  118793. }
  118794. case 1 /* TypeArgs */: {
  118795. var called = invocation.called;
  118796. if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) {
  118797. return undefined;
  118798. }
  118799. var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker);
  118800. if (candidates.length !== 0)
  118801. return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) };
  118802. var symbol = checker.getSymbolAtLocation(called);
  118803. return symbol && { kind: 1 /* Type */, symbol: symbol };
  118804. }
  118805. case 2 /* Contextual */:
  118806. return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
  118807. default:
  118808. return ts.Debug.assertNever(invocation);
  118809. }
  118810. }
  118811. function isSyntacticOwner(startingToken, node, sourceFile) {
  118812. if (!ts.isCallOrNewExpression(node))
  118813. return false;
  118814. var invocationChildren = node.getChildren(sourceFile);
  118815. switch (startingToken.kind) {
  118816. case 20 /* OpenParenToken */:
  118817. return ts.contains(invocationChildren, startingToken);
  118818. case 27 /* CommaToken */: {
  118819. var containingList = ts.findContainingList(startingToken);
  118820. return !!containingList && ts.contains(invocationChildren, containingList);
  118821. }
  118822. case 29 /* LessThanToken */:
  118823. return containsPrecedingToken(startingToken, sourceFile, node.expression);
  118824. default:
  118825. return false;
  118826. }
  118827. }
  118828. function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) {
  118829. if (argumentInfo.invocation.kind === 2 /* Contextual */)
  118830. return undefined;
  118831. // See if we can find some symbol with the call expression name that has call signatures.
  118832. var expression = getExpressionFromInvocation(argumentInfo.invocation);
  118833. var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined;
  118834. var typeChecker = program.getTypeChecker();
  118835. return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) {
  118836. return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) {
  118837. var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration);
  118838. var callSignatures = type && type.getCallSignatures();
  118839. if (callSignatures && callSignatures.length) {
  118840. return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); });
  118841. }
  118842. });
  118843. });
  118844. }
  118845. function containsPrecedingToken(startingToken, sourceFile, container) {
  118846. var pos = startingToken.getFullStart();
  118847. // There’s a possibility that `startingToken.parent` contains only `startingToken` and
  118848. // missing nodes, none of which are valid to be returned by `findPrecedingToken`. In that
  118849. // case, the preceding token we want is actually higher up the tree—almost definitely the
  118850. // next parent, but theoretically the situation with missing nodes might be happening on
  118851. // multiple nested levels.
  118852. var currentParent = startingToken.parent;
  118853. while (currentParent) {
  118854. var precedingToken = ts.findPrecedingToken(pos, sourceFile, currentParent, /*excludeJsdoc*/ true);
  118855. if (precedingToken) {
  118856. return ts.rangeContainsRange(container, precedingToken);
  118857. }
  118858. currentParent = currentParent.parent;
  118859. }
  118860. return ts.Debug.fail("Could not find preceding token");
  118861. }
  118862. function getArgumentInfoForCompletions(node, position, sourceFile) {
  118863. var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile);
  118864. return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined
  118865. : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex };
  118866. }
  118867. SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions;
  118868. function getArgumentOrParameterListInfo(node, sourceFile) {
  118869. var info = getArgumentOrParameterListAndIndex(node, sourceFile);
  118870. if (!info)
  118871. return undefined;
  118872. var list = info.list, argumentIndex = info.argumentIndex;
  118873. var argumentCount = getArgumentCount(list);
  118874. if (argumentIndex !== 0) {
  118875. ts.Debug.assertLessThan(argumentIndex, argumentCount);
  118876. }
  118877. var argumentsSpan = getApplicableSpanForArguments(list, sourceFile);
  118878. return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
  118879. }
  118880. function getArgumentOrParameterListAndIndex(node, sourceFile) {
  118881. if (node.kind === 29 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) {
  118882. // Find the list that starts right *after* the < or ( token.
  118883. // If the user has just opened a list, consider this item 0.
  118884. return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 };
  118885. }
  118886. else {
  118887. // findListItemInfo can return undefined if we are not in parent's argument list
  118888. // or type argument list. This includes cases where the cursor is:
  118889. // - To the right of the closing parenthesis, non-substitution template, or template tail.
  118890. // - Between the type arguments and the arguments (greater than token)
  118891. // - On the target of the call (parent.func)
  118892. // - On the 'new' keyword in a 'new' expression
  118893. var list = ts.findContainingList(node);
  118894. return list && { list: list, argumentIndex: getArgumentIndex(list, node) };
  118895. }
  118896. }
  118897. /**
  118898. * Returns relevant information for the argument list and the current argument if we are
  118899. * in the argument of an invocation; returns undefined otherwise.
  118900. */
  118901. function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
  118902. var parent = node.parent;
  118903. if (ts.isCallOrNewExpression(parent)) {
  118904. var invocation = parent;
  118905. // There are 3 cases to handle:
  118906. // 1. The token introduces a list, and should begin a signature help session
  118907. // 2. The token is either not associated with a list, or ends a list, so the session should end
  118908. // 3. The token is buried inside a list, and should give signature help
  118909. //
  118910. // The following are examples of each:
  118911. //
  118912. // Case 1:
  118913. // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session
  118914. // Case 2:
  118915. // fo#o<T, U>#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end
  118916. // Case 3:
  118917. // foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give signature help
  118918. // Find out if 'node' is an argument, a type argument, or neither
  118919. var info = getArgumentOrParameterListInfo(node, sourceFile);
  118920. if (!info)
  118921. return undefined;
  118922. var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
  118923. var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos;
  118924. return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
  118925. }
  118926. else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) {
  118927. // Check if we're actually inside the template;
  118928. // otherwise we'll fall out and return undefined.
  118929. if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
  118930. return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile);
  118931. }
  118932. return undefined;
  118933. }
  118934. else if (ts.isTemplateHead(node) && parent.parent.kind === 198 /* TaggedTemplateExpression */) {
  118935. var templateExpression = parent;
  118936. var tagExpression = templateExpression.parent;
  118937. ts.Debug.assert(templateExpression.kind === 211 /* TemplateExpression */);
  118938. var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
  118939. return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
  118940. }
  118941. else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) {
  118942. var templateSpan = parent;
  118943. var tagExpression = parent.parent.parent;
  118944. // If we're just after a template tail, don't show signature help.
  118945. if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) {
  118946. return undefined;
  118947. }
  118948. var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan);
  118949. var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile);
  118950. return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
  118951. }
  118952. else if (ts.isJsxOpeningLikeElement(parent)) {
  118953. // Provide a signature help for JSX opening element or JSX self-closing element.
  118954. // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems")
  118955. // i.e
  118956. // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... }
  118957. // <MainButton /*signatureHelp*/
  118958. var attributeSpanStart = parent.attributes.pos;
  118959. var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false);
  118960. return {
  118961. isTypeParameterList: false,
  118962. invocation: { kind: 0 /* Call */, node: parent },
  118963. argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
  118964. argumentIndex: 0,
  118965. argumentCount: 1
  118966. };
  118967. }
  118968. else {
  118969. var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile);
  118970. if (typeArgInfo) {
  118971. var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments;
  118972. var invocation = { kind: 1 /* TypeArgs */, called: called };
  118973. var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end);
  118974. return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 };
  118975. }
  118976. return undefined;
  118977. }
  118978. }
  118979. function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) {
  118980. return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile);
  118981. }
  118982. function getHighestBinary(b) {
  118983. return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b;
  118984. }
  118985. function countBinaryExpressionParameters(b) {
  118986. return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2;
  118987. }
  118988. function tryGetParameterInfo(startingToken, _position, sourceFile, checker) {
  118989. var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker);
  118990. if (!info)
  118991. return undefined;
  118992. var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
  118993. var signatures = contextualType.getCallSignatures();
  118994. if (signatures.length !== 1)
  118995. return undefined;
  118996. var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) };
  118997. return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
  118998. }
  118999. function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) {
  119000. if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */)
  119001. return undefined;
  119002. var parent = startingToken.parent;
  119003. switch (parent.kind) {
  119004. case 200 /* ParenthesizedExpression */:
  119005. case 161 /* MethodDeclaration */:
  119006. case 201 /* FunctionExpression */:
  119007. case 202 /* ArrowFunction */:
  119008. var info = getArgumentOrParameterListInfo(startingToken, sourceFile);
  119009. if (!info)
  119010. return undefined;
  119011. var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
  119012. var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent);
  119013. return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
  119014. case 209 /* BinaryExpression */: {
  119015. var highestBinary = getHighestBinary(parent);
  119016. var contextualType_1 = checker.getContextualType(highestBinary);
  119017. var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1;
  119018. var argumentCount_1 = countBinaryExpressionParameters(highestBinary);
  119019. return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) };
  119020. }
  119021. default:
  119022. return undefined;
  119023. }
  119024. }
  119025. // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias.
  119026. function chooseBetterSymbol(s) {
  119027. return s.name === "__type" /* Type */
  119028. ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s
  119029. : s;
  119030. }
  119031. function getArgumentIndex(argumentsList, node) {
  119032. // The list we got back can include commas. In the presence of errors it may
  119033. // also just have nodes without commas. For example "Foo(a b c)" will have 3
  119034. // args without commas. We want to find what index we're at. So we count
  119035. // forward until we hit ourselves, only incrementing the index if it isn't a
  119036. // comma.
  119037. //
  119038. // Note: the subtlety around trailing commas (in getArgumentCount) does not apply
  119039. // here. That's because we're only walking forward until we hit the node we're
  119040. // on. In that case, even if we're after the trailing comma, we'll still see
  119041. // that trailing comma in the list, and we'll have generated the appropriate
  119042. // arg index.
  119043. var argumentIndex = 0;
  119044. for (var _i = 0, _a = argumentsList.getChildren(); _i < _a.length; _i++) {
  119045. var child = _a[_i];
  119046. if (child === node) {
  119047. break;
  119048. }
  119049. if (child.kind !== 27 /* CommaToken */) {
  119050. argumentIndex++;
  119051. }
  119052. }
  119053. return argumentIndex;
  119054. }
  119055. function getArgumentCount(argumentsList) {
  119056. // The argument count for a list is normally the number of non-comma children it has.
  119057. // For example, if you have "Foo(a,b)" then there will be three children of the arg
  119058. // list 'a' '<comma>' 'b'. So, in this case the arg count will be 2. However, there
  119059. // is a small subtlety. If you have "Foo(a,)", then the child list will just have
  119060. // 'a' '<comma>'. So, in the case where the last child is a comma, we increase the
  119061. // arg count by one to compensate.
  119062. //
  119063. // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then
  119064. // we'll have: 'a' '<comma>' '<missing>'
  119065. // That will give us 2 non-commas. We then add one for the last comma, giving us an
  119066. // arg count of 3.
  119067. var listChildren = argumentsList.getChildren();
  119068. var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; });
  119069. if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) {
  119070. argumentCount++;
  119071. }
  119072. return argumentCount;
  119073. }
  119074. // spanIndex is either the index for a given template span.
  119075. // This does not give appropriate results for a NoSubstitutionTemplateLiteral
  119076. function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) {
  119077. // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1.
  119078. // There are three cases we can encounter:
  119079. // 1. We are precisely in the template literal (argIndex = 0).
  119080. // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1).
  119081. // 3. We are directly to the right of the template literal, but because we look for the token on the left,
  119082. // not enough to put us in the substitution expression; we should consider ourselves part of
  119083. // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1).
  119084. //
  119085. /* eslint-disable no-double-space */
  119086. // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # `
  119087. // ^ ^ ^ ^ ^ ^ ^ ^ ^
  119088. // Case: 1 1 3 2 1 3 2 2 1
  119089. /* eslint-enable no-double-space */
  119090. ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node.");
  119091. if (ts.isTemplateLiteralToken(node)) {
  119092. if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
  119093. return 0;
  119094. }
  119095. return spanIndex + 2;
  119096. }
  119097. return spanIndex + 1;
  119098. }
  119099. function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) {
  119100. // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument.
  119101. var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
  119102. if (argumentIndex !== 0) {
  119103. ts.Debug.assertLessThan(argumentIndex, argumentCount);
  119104. }
  119105. return {
  119106. isTypeParameterList: false,
  119107. invocation: { kind: 0 /* Call */, node: tagExpression },
  119108. argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile),
  119109. argumentIndex: argumentIndex,
  119110. argumentCount: argumentCount
  119111. };
  119112. }
  119113. function getApplicableSpanForArguments(argumentsList, sourceFile) {
  119114. // We use full start and skip trivia on the end because we want to include trivia on
  119115. // both sides. For example,
  119116. //
  119117. // foo( /*comment */ a, b, c /*comment*/ )
  119118. // | |
  119119. //
  119120. // The applicable span is from the first bar to the second bar (inclusive,
  119121. // but not including parentheses)
  119122. var applicableSpanStart = argumentsList.getFullStart();
  119123. var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
  119124. return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
  119125. }
  119126. function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) {
  119127. var template = taggedTemplate.template;
  119128. var applicableSpanStart = template.getStart();
  119129. var applicableSpanEnd = template.getEnd();
  119130. // We need to adjust the end position for the case where the template does not have a tail.
  119131. // Otherwise, we will not show signature help past the expression.
  119132. // For example,
  119133. //
  119134. // ` ${ 1 + 1 foo(10)
  119135. // | |
  119136. // This is because a Missing node has no width. However, what we actually want is to include trivia
  119137. // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
  119138. if (template.kind === 211 /* TemplateExpression */) {
  119139. var lastSpan = ts.last(template.templateSpans);
  119140. if (lastSpan.literal.getFullWidth() === 0) {
  119141. applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
  119142. }
  119143. }
  119144. return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
  119145. }
  119146. function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
  119147. var _loop_7 = function (n) {
  119148. // If the node is not a subspan of its parent, this is a big problem.
  119149. // There have been crashes that might be caused by this violation.
  119150. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); });
  119151. var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
  119152. if (argumentInfo) {
  119153. return { value: argumentInfo };
  119154. }
  119155. };
  119156. for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
  119157. var state_2 = _loop_7(n);
  119158. if (typeof state_2 === "object")
  119159. return state_2.value;
  119160. }
  119161. return undefined;
  119162. }
  119163. function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) {
  119164. var children = parent.getChildren(sourceFile);
  119165. var indexOfOpenerToken = children.indexOf(openerToken);
  119166. ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
  119167. return children[indexOfOpenerToken + 1];
  119168. }
  119169. function getExpressionFromInvocation(invocation) {
  119170. return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called;
  119171. }
  119172. function getEnclosingDeclarationFromInvocation(invocation) {
  119173. return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
  119174. }
  119175. var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
  119176. function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
  119177. var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
  119178. var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
  119179. var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation));
  119180. var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray;
  119181. var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); });
  119182. if (argumentIndex !== 0) {
  119183. ts.Debug.assertLessThan(argumentIndex, argumentCount);
  119184. }
  119185. var selectedItemIndex = candidates.indexOf(resolvedSignature);
  119186. ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function.
  119187. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
  119188. }
  119189. function createTypeHelpItems(symbol, _a, sourceFile, checker) {
  119190. var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
  119191. var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  119192. if (!typeParameters)
  119193. return undefined;
  119194. var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
  119195. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount };
  119196. }
  119197. function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
  119198. var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol);
  119199. var printer = ts.createPrinter({ removeComments: true });
  119200. var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
  119201. var documentation = symbol.getDocumentationComment(checker);
  119202. var tags = symbol.getJsDocTags();
  119203. var prefixDisplayParts = __spreadArrays(typeSymbolDisplay, [ts.punctuationPart(29 /* LessThanToken */)]);
  119204. return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
  119205. }
  119206. var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()];
  119207. function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
  119208. var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix;
  119209. var prefixDisplayParts = __spreadArrays(callTargetDisplayParts, prefix);
  119210. var suffixDisplayParts = __spreadArrays(suffix, returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
  119211. var documentation = candidateSignature.getDocumentationComment(checker);
  119212. var tags = candidateSignature.getJsDocTags();
  119213. return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
  119214. }
  119215. function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) {
  119216. return ts.mapToDisplayParts(function (writer) {
  119217. writer.writePunctuation(":");
  119218. writer.writeSpace(" ");
  119219. var predicate = checker.getTypePredicateOfSignature(candidateSignature);
  119220. if (predicate) {
  119221. checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer);
  119222. }
  119223. else {
  119224. checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer);
  119225. }
  119226. });
  119227. }
  119228. function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
  119229. var typeParameters = (candidateSignature.target || candidateSignature).typeParameters;
  119230. var printer = ts.createPrinter({ removeComments: true });
  119231. var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
  119232. var parameterParts = ts.mapToDisplayParts(function (writer) {
  119233. var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
  119234. var params = ts.createNodeArray(__spreadArrays(thisParameter, checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
  119235. printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
  119236. });
  119237. return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(29 /* LessThanToken */)], suffix: __spreadArrays([ts.punctuationPart(31 /* GreaterThanToken */)], parameterParts) };
  119238. }
  119239. function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
  119240. var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
  119241. var printer = ts.createPrinter({ removeComments: true });
  119242. var typeParameterParts = ts.mapToDisplayParts(function (writer) {
  119243. if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
  119244. var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); }));
  119245. printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
  119246. }
  119247. });
  119248. var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
  119249. return { isVariadic: isVariadic, parameters: parameters, prefix: __spreadArrays(typeParameterParts, [ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
  119250. }
  119251. function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
  119252. var displayParts = ts.mapToDisplayParts(function (writer) {
  119253. var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
  119254. printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
  119255. });
  119256. var isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
  119257. return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional };
  119258. }
  119259. function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
  119260. var displayParts = ts.mapToDisplayParts(function (writer) {
  119261. var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration);
  119262. printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
  119263. });
  119264. return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false };
  119265. }
  119266. })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
  119267. })(ts || (ts = {}));
  119268. /* @internal */
  119269. var ts;
  119270. (function (ts) {
  119271. var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
  119272. function getSourceMapper(host) {
  119273. var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  119274. var currentDirectory = host.getCurrentDirectory();
  119275. var sourceFileLike = ts.createMap();
  119276. var documentPositionMappers = ts.createMap();
  119277. return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache };
  119278. function toPath(fileName) {
  119279. return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  119280. }
  119281. function getDocumentPositionMapper(generatedFileName, sourceFileName) {
  119282. var path = toPath(generatedFileName);
  119283. var value = documentPositionMappers.get(path);
  119284. if (value)
  119285. return value;
  119286. var mapper;
  119287. if (host.getDocumentPositionMapper) {
  119288. mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName);
  119289. }
  119290. else if (host.readFile) {
  119291. var file = getSourceFileLike(generatedFileName);
  119292. mapper = file && ts.getDocumentPositionMapper({ getSourceFileLike: getSourceFileLike, getCanonicalFileName: getCanonicalFileName, log: function (s) { return host.log(s); } }, generatedFileName, ts.getLineInfo(file.text, ts.getLineStarts(file)), function (f) { return !host.fileExists || host.fileExists(f) ? host.readFile(f) : undefined; });
  119293. }
  119294. documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer);
  119295. return mapper || ts.identitySourceMapConsumer;
  119296. }
  119297. function tryGetSourcePosition(info) {
  119298. if (!ts.isDeclarationFileName(info.fileName))
  119299. return undefined;
  119300. var file = getSourceFile(info.fileName);
  119301. if (!file)
  119302. return undefined;
  119303. var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info);
  119304. return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc;
  119305. }
  119306. function tryGetGeneratedPosition(info) {
  119307. if (ts.isDeclarationFileName(info.fileName))
  119308. return undefined;
  119309. var sourceFile = getSourceFile(info.fileName);
  119310. if (!sourceFile)
  119311. return undefined;
  119312. var program = host.getProgram();
  119313. // If this is source file of project reference source (instead of redirect) there is no generated position
  119314. if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) {
  119315. return undefined;
  119316. }
  119317. var options = program.getCompilerOptions();
  119318. var outPath = options.outFile || options.out;
  119319. var declarationPath = outPath ?
  119320. ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ :
  119321. ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName);
  119322. if (declarationPath === undefined)
  119323. return undefined;
  119324. var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info);
  119325. return newLoc === info ? undefined : newLoc;
  119326. }
  119327. function getSourceFile(fileName) {
  119328. var program = host.getProgram();
  119329. if (!program)
  119330. return undefined;
  119331. var path = toPath(fileName);
  119332. // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file
  119333. var file = program.getSourceFileByPath(path);
  119334. return file && file.resolvedPath === path ? file : undefined;
  119335. }
  119336. function getOrCreateSourceFileLike(fileName) {
  119337. var path = toPath(fileName);
  119338. var fileFromCache = sourceFileLike.get(path);
  119339. if (fileFromCache !== undefined)
  119340. return fileFromCache ? fileFromCache : undefined;
  119341. if (!host.readFile || host.fileExists && !host.fileExists(path)) {
  119342. sourceFileLike.set(path, false);
  119343. return undefined;
  119344. }
  119345. // And failing that, check the disk
  119346. var text = host.readFile(path);
  119347. var file = text ? createSourceFileLike(text) : false;
  119348. sourceFileLike.set(path, file);
  119349. return file ? file : undefined;
  119350. }
  119351. // This can be called from source mapper in either source program or program that includes generated file
  119352. function getSourceFileLike(fileName) {
  119353. return !host.getSourceFileLike ?
  119354. getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) :
  119355. host.getSourceFileLike(fileName);
  119356. }
  119357. function toLineColumnOffset(fileName, position) {
  119358. var file = getSourceFileLike(fileName); // TODO: GH#18217
  119359. return file.getLineAndCharacterOfPosition(position);
  119360. }
  119361. function clearCache() {
  119362. sourceFileLike.clear();
  119363. documentPositionMappers.clear();
  119364. }
  119365. }
  119366. ts.getSourceMapper = getSourceMapper;
  119367. function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) {
  119368. var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo);
  119369. if (mapFileName) {
  119370. var match = base64UrlRegExp.exec(mapFileName);
  119371. if (match) {
  119372. if (match[1]) {
  119373. var base64Object = match[1];
  119374. return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName);
  119375. }
  119376. // Not a data URL we can parse, skip it
  119377. mapFileName = undefined;
  119378. }
  119379. }
  119380. var possibleMapLocations = [];
  119381. if (mapFileName) {
  119382. possibleMapLocations.push(mapFileName);
  119383. }
  119384. possibleMapLocations.push(generatedFileName + ".map");
  119385. var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName));
  119386. for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) {
  119387. var location = possibleMapLocations_1[_i];
  119388. var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName));
  119389. var mapFileContents = readMapFile(mapFileName_1, originalMapFileName);
  119390. if (ts.isString(mapFileContents)) {
  119391. return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1);
  119392. }
  119393. if (mapFileContents !== undefined) {
  119394. return mapFileContents || undefined;
  119395. }
  119396. }
  119397. return undefined;
  119398. }
  119399. ts.getDocumentPositionMapper = getDocumentPositionMapper;
  119400. function convertDocumentToSourceMapper(host, contents, mapFileName) {
  119401. var map = ts.tryParseRawSourceMap(contents);
  119402. if (!map || !map.sources || !map.file || !map.mappings) {
  119403. // obviously invalid map
  119404. return undefined;
  119405. }
  119406. // Dont support sourcemaps that contain inlined sources
  119407. if (map.sourcesContent && map.sourcesContent.some(ts.isString))
  119408. return undefined;
  119409. return ts.createDocumentPositionMapper(host, map, mapFileName);
  119410. }
  119411. function createSourceFileLike(text, lineMap) {
  119412. return {
  119413. text: text,
  119414. lineMap: lineMap,
  119415. getLineAndCharacterOfPosition: function (pos) {
  119416. return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos);
  119417. }
  119418. };
  119419. }
  119420. })(ts || (ts = {}));
  119421. /* @internal */
  119422. var ts;
  119423. (function (ts) {
  119424. var visitedNestedConvertibleFunctions = ts.createMap();
  119425. function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
  119426. program.getSemanticDiagnostics(sourceFile, cancellationToken);
  119427. var diags = [];
  119428. var checker = program.getTypeChecker();
  119429. if (sourceFile.commonJsModuleIndicator &&
  119430. (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
  119431. containsTopLevelCommonjs(sourceFile)) {
  119432. diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
  119433. }
  119434. var isJsFile = ts.isSourceFileJS(sourceFile);
  119435. visitedNestedConvertibleFunctions.clear();
  119436. check(sourceFile);
  119437. if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
  119438. for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
  119439. var moduleSpecifier = _a[_i];
  119440. var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
  119441. var name = importNameForConvertToDefaultImport(importNode);
  119442. if (!name)
  119443. continue;
  119444. var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
  119445. var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName);
  119446. if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
  119447. diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
  119448. }
  119449. }
  119450. }
  119451. ts.addRange(diags, sourceFile.bindSuggestionDiagnostics);
  119452. ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
  119453. return diags.sort(function (d1, d2) { return d1.start - d2.start; });
  119454. function check(node) {
  119455. if (isJsFile) {
  119456. switch (node.kind) {
  119457. case 201 /* FunctionExpression */:
  119458. var decl = ts.getDeclarationOfExpando(node);
  119459. if (decl) {
  119460. var symbol_1 = decl.symbol;
  119461. if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) {
  119462. diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
  119463. break;
  119464. }
  119465. }
  119466. // falls through if no diagnostic was created
  119467. case 244 /* FunctionDeclaration */:
  119468. var symbol = node.symbol;
  119469. if (symbol.members && (symbol.members.size > 0)) {
  119470. diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
  119471. }
  119472. break;
  119473. }
  119474. }
  119475. else {
  119476. if (ts.isVariableStatement(node) &&
  119477. node.parent === sourceFile &&
  119478. node.declarationList.flags & 2 /* Const */ &&
  119479. node.declarationList.declarations.length === 1) {
  119480. var init = node.declarationList.declarations[0].initializer;
  119481. if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) {
  119482. diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import));
  119483. }
  119484. }
  119485. if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
  119486. diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
  119487. }
  119488. }
  119489. if (ts.isFunctionLikeDeclaration(node)) {
  119490. addConvertToAsyncFunctionDiagnostics(node, checker, diags);
  119491. }
  119492. node.forEachChild(check);
  119493. }
  119494. }
  119495. ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
  119496. // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
  119497. function containsTopLevelCommonjs(sourceFile) {
  119498. return sourceFile.statements.some(function (statement) {
  119499. switch (statement.kind) {
  119500. case 225 /* VariableStatement */:
  119501. return statement.declarationList.declarations.some(function (decl) {
  119502. return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
  119503. });
  119504. case 226 /* ExpressionStatement */: {
  119505. var expression = statement.expression;
  119506. if (!ts.isBinaryExpression(expression))
  119507. return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
  119508. var kind = ts.getAssignmentDeclarationKind(expression);
  119509. return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
  119510. }
  119511. default:
  119512. return false;
  119513. }
  119514. });
  119515. }
  119516. function propertyAccessLeftHandSide(node) {
  119517. return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
  119518. }
  119519. function importNameForConvertToDefaultImport(node) {
  119520. switch (node.kind) {
  119521. case 254 /* ImportDeclaration */:
  119522. var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
  119523. return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 256 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
  119524. ? importClause.namedBindings.name
  119525. : undefined;
  119526. case 253 /* ImportEqualsDeclaration */:
  119527. return node.name;
  119528. default:
  119529. return undefined;
  119530. }
  119531. }
  119532. function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
  119533. // need to check function before checking map so that deeper levels of nested callbacks are checked
  119534. if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) {
  119535. diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function));
  119536. }
  119537. }
  119538. function isConvertibleFunction(node, checker) {
  119539. return !ts.isAsyncFunction(node) &&
  119540. node.body &&
  119541. ts.isBlock(node.body) &&
  119542. hasReturnStatementWithPromiseHandler(node.body) &&
  119543. returnsPromise(node, checker);
  119544. }
  119545. function returnsPromise(node, checker) {
  119546. var functionType = checker.getTypeAtLocation(node);
  119547. var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */);
  119548. var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined;
  119549. return !!returnType && !!checker.getPromisedTypeOfPromise(returnType);
  119550. }
  119551. function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
  119552. return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
  119553. }
  119554. function hasReturnStatementWithPromiseHandler(body) {
  119555. return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler);
  119556. }
  119557. function isReturnStatementWithFixablePromiseHandler(node) {
  119558. return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression);
  119559. }
  119560. ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler;
  119561. // Should be kept up to date with transformExpression in convertToAsyncFunction.ts
  119562. function isFixablePromiseHandler(node) {
  119563. // ensure outermost call exists and is a promise handler
  119564. if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
  119565. return false;
  119566. }
  119567. // ensure all chained calls are valid
  119568. var currentNode = node.expression;
  119569. while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) {
  119570. if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
  119571. return false;
  119572. }
  119573. currentNode = currentNode.expression;
  119574. }
  119575. return true;
  119576. }
  119577. ts.isFixablePromiseHandler = isFixablePromiseHandler;
  119578. function isPromiseHandler(node) {
  119579. return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch"));
  119580. }
  119581. // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts
  119582. function isFixablePromiseArgument(arg) {
  119583. switch (arg.kind) {
  119584. case 244 /* FunctionDeclaration */:
  119585. case 201 /* FunctionExpression */:
  119586. case 202 /* ArrowFunction */:
  119587. visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
  119588. // falls through
  119589. case 100 /* NullKeyword */:
  119590. case 75 /* Identifier */: // identifier includes undefined
  119591. return true;
  119592. default:
  119593. return false;
  119594. }
  119595. }
  119596. function getKeyFromNode(exp) {
  119597. return exp.pos.toString() + ":" + exp.end.toString();
  119598. }
  119599. })(ts || (ts = {}));
  119600. /* @internal */
  119601. var ts;
  119602. (function (ts) {
  119603. var SymbolDisplay;
  119604. (function (SymbolDisplay) {
  119605. // TODO(drosen): use contextual SemanticMeaning.
  119606. function getSymbolKind(typeChecker, symbol, location) {
  119607. var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
  119608. if (result !== "" /* unknown */) {
  119609. return result;
  119610. }
  119611. var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
  119612. if (flags & 32 /* Class */) {
  119613. return ts.getDeclarationOfKind(symbol, 214 /* ClassExpression */) ?
  119614. "local class" /* localClassElement */ : "class" /* classElement */;
  119615. }
  119616. if (flags & 384 /* Enum */)
  119617. return "enum" /* enumElement */;
  119618. if (flags & 524288 /* TypeAlias */)
  119619. return "type" /* typeElement */;
  119620. if (flags & 64 /* Interface */)
  119621. return "interface" /* interfaceElement */;
  119622. if (flags & 262144 /* TypeParameter */)
  119623. return "type parameter" /* typeParameterElement */;
  119624. if (flags & 8 /* EnumMember */)
  119625. return "enum member" /* enumMemberElement */;
  119626. if (flags & 2097152 /* Alias */)
  119627. return "alias" /* alias */;
  119628. if (flags & 1536 /* Module */)
  119629. return "module" /* moduleElement */;
  119630. return result;
  119631. }
  119632. SymbolDisplay.getSymbolKind = getSymbolKind;
  119633. function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
  119634. var roots = typeChecker.getRootSymbols(symbol);
  119635. // If this is a method from a mapped type, leave as a method so long as it still has a call signature.
  119636. if (roots.length === 1
  119637. && ts.first(roots).flags & 8192 /* Method */
  119638. // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`.
  119639. && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) {
  119640. return "method" /* memberFunctionElement */;
  119641. }
  119642. if (typeChecker.isUndefinedSymbol(symbol)) {
  119643. return "var" /* variableElement */;
  119644. }
  119645. if (typeChecker.isArgumentsSymbol(symbol)) {
  119646. return "local var" /* localVariableElement */;
  119647. }
  119648. if (location.kind === 104 /* ThisKeyword */ && ts.isExpression(location)) {
  119649. return "parameter" /* parameterElement */;
  119650. }
  119651. var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
  119652. if (flags & 3 /* Variable */) {
  119653. if (ts.isFirstDeclarationOfSymbolParameter(symbol)) {
  119654. return "parameter" /* parameterElement */;
  119655. }
  119656. else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) {
  119657. return "const" /* constElement */;
  119658. }
  119659. else if (ts.forEach(symbol.declarations, ts.isLet)) {
  119660. return "let" /* letElement */;
  119661. }
  119662. return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */;
  119663. }
  119664. if (flags & 16 /* Function */)
  119665. return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */;
  119666. if (flags & 32768 /* GetAccessor */)
  119667. return "getter" /* memberGetAccessorElement */;
  119668. if (flags & 65536 /* SetAccessor */)
  119669. return "setter" /* memberSetAccessorElement */;
  119670. if (flags & 8192 /* Method */)
  119671. return "method" /* memberFunctionElement */;
  119672. if (flags & 16384 /* Constructor */)
  119673. return "constructor" /* constructorImplementationElement */;
  119674. if (flags & 4 /* Property */) {
  119675. if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) {
  119676. // If union property is result of union of non method (property/accessors/variables), it is labeled as property
  119677. var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) {
  119678. var rootSymbolFlags = rootSymbol.getFlags();
  119679. if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
  119680. return "property" /* memberVariableElement */;
  119681. }
  119682. // May be a Function if this was from `typeof N` with `namespace N { function f();. }`.
  119683. ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */)));
  119684. });
  119685. if (!unionPropertyKind) {
  119686. // If this was union of all methods,
  119687. // make sure it has call signatures before we can label it as method
  119688. var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
  119689. if (typeOfUnionProperty.getCallSignatures().length) {
  119690. return "method" /* memberFunctionElement */;
  119691. }
  119692. return "property" /* memberVariableElement */;
  119693. }
  119694. return unionPropertyKind;
  119695. }
  119696. // If we requested completions after `x.` at the top-level, we may be at a source file location.
  119697. switch (location.parent && location.parent.kind) {
  119698. // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'.
  119699. case 268 /* JsxOpeningElement */:
  119700. case 266 /* JsxElement */:
  119701. case 267 /* JsxSelfClosingElement */:
  119702. return location.kind === 75 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */;
  119703. case 273 /* JsxAttribute */:
  119704. return "JSX attribute" /* jsxAttribute */;
  119705. default:
  119706. return "property" /* memberVariableElement */;
  119707. }
  119708. }
  119709. return "" /* unknown */;
  119710. }
  119711. function getSymbolModifiers(symbol) {
  119712. var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0
  119713. ? ts.getNodeModifiers(symbol.declarations[0])
  119714. : "" /* none */;
  119715. var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ?
  119716. "optional" /* optionalModifier */
  119717. : "" /* none */;
  119718. return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers;
  119719. }
  119720. SymbolDisplay.getSymbolModifiers = getSymbolModifiers;
  119721. // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location
  119722. function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) {
  119723. if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); }
  119724. var displayParts = [];
  119725. var documentation = [];
  119726. var tags = [];
  119727. var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
  119728. var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
  119729. var hasAddedSymbolInfo = false;
  119730. var isThisExpression = location.kind === 104 /* ThisKeyword */ && ts.isInExpressionContext(location);
  119731. var type;
  119732. var printer;
  119733. var documentationFromAlias;
  119734. var tagsFromAlias;
  119735. var hasMultipleSignatures = false;
  119736. if (location.kind === 104 /* ThisKeyword */ && !isThisExpression) {
  119737. return { displayParts: [ts.keywordPart(104 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined };
  119738. }
  119739. // Class at constructor site need to be shown as constructor apart from property,method, vars
  119740. if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
  119741. // If it is accessor they are allowed only if location is at name of the accessor
  119742. if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) {
  119743. symbolKind = "property" /* memberVariableElement */;
  119744. }
  119745. var signature = void 0;
  119746. type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location);
  119747. if (location.parent && location.parent.kind === 194 /* PropertyAccessExpression */) {
  119748. var right = location.parent.name;
  119749. // Either the location is on the right of a property access, or on the left and the right is missing
  119750. if (right === location || (right && right.getFullWidth() === 0)) {
  119751. location = location.parent;
  119752. }
  119753. }
  119754. // try get the call/construct signature from the type if it matches
  119755. var callExpressionLike = void 0;
  119756. if (ts.isCallOrNewExpression(location)) {
  119757. callExpressionLike = location;
  119758. }
  119759. else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) {
  119760. callExpressionLike = location.parent;
  119761. }
  119762. else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) {
  119763. callExpressionLike = location.parent;
  119764. }
  119765. if (callExpressionLike) {
  119766. signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217
  119767. var useConstructSignatures = callExpressionLike.kind === 197 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 102 /* SuperKeyword */);
  119768. var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
  119769. if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
  119770. // Get the first signature if there is one -- allSignatures may contain
  119771. // either the original signature or its target, so check for either
  119772. signature = allSignatures.length ? allSignatures[0] : undefined;
  119773. }
  119774. if (signature) {
  119775. if (useConstructSignatures && (symbolFlags & 32 /* Class */)) {
  119776. // Constructor
  119777. symbolKind = "constructor" /* constructorImplementationElement */;
  119778. addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
  119779. }
  119780. else if (symbolFlags & 2097152 /* Alias */) {
  119781. symbolKind = "alias" /* alias */;
  119782. pushSymbolKind(symbolKind);
  119783. displayParts.push(ts.spacePart());
  119784. if (useConstructSignatures) {
  119785. displayParts.push(ts.keywordPart(99 /* NewKeyword */));
  119786. displayParts.push(ts.spacePart());
  119787. }
  119788. addFullSymbolName(symbol);
  119789. }
  119790. else {
  119791. addPrefixForAnyFunctionOrVar(symbol, symbolKind);
  119792. }
  119793. switch (symbolKind) {
  119794. case "JSX attribute" /* jsxAttribute */:
  119795. case "property" /* memberVariableElement */:
  119796. case "var" /* variableElement */:
  119797. case "const" /* constElement */:
  119798. case "let" /* letElement */:
  119799. case "parameter" /* parameterElement */:
  119800. case "local var" /* localVariableElement */:
  119801. // If it is call or construct signature of lambda's write type name
  119802. displayParts.push(ts.punctuationPart(58 /* ColonToken */));
  119803. displayParts.push(ts.spacePart());
  119804. if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) {
  119805. ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */));
  119806. displayParts.push(ts.lineBreakPart());
  119807. }
  119808. if (useConstructSignatures) {
  119809. displayParts.push(ts.keywordPart(99 /* NewKeyword */));
  119810. displayParts.push(ts.spacePart());
  119811. }
  119812. addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */);
  119813. break;
  119814. default:
  119815. // Just signature
  119816. addSignatureDisplayParts(signature, allSignatures);
  119817. }
  119818. hasAddedSymbolInfo = true;
  119819. hasMultipleSignatures = allSignatures.length > 1;
  119820. }
  119821. }
  119822. else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
  119823. (location.kind === 129 /* ConstructorKeyword */ && location.parent.kind === 162 /* Constructor */)) { // At constructor keyword of constructor declaration
  119824. // get the signature from the declaration and write it
  119825. var functionDeclaration_1 = location.parent;
  119826. // Use function declaration to write the signatures only if the symbol corresponding to this declaration
  119827. var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) {
  119828. return declaration === (location.kind === 129 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1);
  119829. });
  119830. if (locationIsSymbolDeclaration) {
  119831. var allSignatures = functionDeclaration_1.kind === 162 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
  119832. if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) {
  119833. signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217
  119834. }
  119835. else {
  119836. signature = allSignatures[0];
  119837. }
  119838. if (functionDeclaration_1.kind === 162 /* Constructor */) {
  119839. // show (constructor) Type(...) signature
  119840. symbolKind = "constructor" /* constructorImplementationElement */;
  119841. addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
  119842. }
  119843. else {
  119844. // (function/method) symbol(..signature)
  119845. addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 165 /* CallSignature */ &&
  119846. !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind);
  119847. }
  119848. addSignatureDisplayParts(signature, allSignatures);
  119849. hasAddedSymbolInfo = true;
  119850. hasMultipleSignatures = allSignatures.length > 1;
  119851. }
  119852. }
  119853. }
  119854. if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
  119855. addAliasPrefixIfNecessary();
  119856. if (ts.getDeclarationOfKind(symbol, 214 /* ClassExpression */)) {
  119857. // Special case for class expressions because we would like to indicate that
  119858. // the class name is local to the class body (similar to function expression)
  119859. // (local class) class <className>
  119860. pushSymbolKind("local class" /* localClassElement */);
  119861. }
  119862. else {
  119863. // Class declaration has name which is not local.
  119864. displayParts.push(ts.keywordPart(80 /* ClassKeyword */));
  119865. }
  119866. displayParts.push(ts.spacePart());
  119867. addFullSymbolName(symbol);
  119868. writeTypeParametersOfSymbol(symbol, sourceFile);
  119869. }
  119870. if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) {
  119871. prefixNextMeaning();
  119872. displayParts.push(ts.keywordPart(114 /* InterfaceKeyword */));
  119873. displayParts.push(ts.spacePart());
  119874. addFullSymbolName(symbol);
  119875. writeTypeParametersOfSymbol(symbol, sourceFile);
  119876. }
  119877. if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) {
  119878. prefixNextMeaning();
  119879. displayParts.push(ts.keywordPart(145 /* TypeKeyword */));
  119880. displayParts.push(ts.spacePart());
  119881. addFullSymbolName(symbol);
  119882. writeTypeParametersOfSymbol(symbol, sourceFile);
  119883. displayParts.push(ts.spacePart());
  119884. displayParts.push(ts.operatorPart(62 /* EqualsToken */));
  119885. displayParts.push(ts.spacePart());
  119886. ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */));
  119887. }
  119888. if (symbolFlags & 384 /* Enum */) {
  119889. prefixNextMeaning();
  119890. if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) {
  119891. displayParts.push(ts.keywordPart(81 /* ConstKeyword */));
  119892. displayParts.push(ts.spacePart());
  119893. }
  119894. displayParts.push(ts.keywordPart(88 /* EnumKeyword */));
  119895. displayParts.push(ts.spacePart());
  119896. addFullSymbolName(symbol);
  119897. }
  119898. if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
  119899. prefixNextMeaning();
  119900. var declaration = ts.getDeclarationOfKind(symbol, 249 /* ModuleDeclaration */);
  119901. var isNamespace = declaration && declaration.name && declaration.name.kind === 75 /* Identifier */;
  119902. displayParts.push(ts.keywordPart(isNamespace ? 136 /* NamespaceKeyword */ : 135 /* ModuleKeyword */));
  119903. displayParts.push(ts.spacePart());
  119904. addFullSymbolName(symbol);
  119905. }
  119906. if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) {
  119907. prefixNextMeaning();
  119908. displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
  119909. displayParts.push(ts.textPart("type parameter"));
  119910. displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
  119911. displayParts.push(ts.spacePart());
  119912. addFullSymbolName(symbol);
  119913. if (symbol.parent) {
  119914. // Class/Interface type parameter
  119915. addInPrefix();
  119916. addFullSymbolName(symbol.parent, enclosingDeclaration);
  119917. writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
  119918. }
  119919. else {
  119920. // Method/function type parameter
  119921. var decl = ts.getDeclarationOfKind(symbol, 155 /* TypeParameter */);
  119922. if (decl === undefined)
  119923. return ts.Debug.fail();
  119924. var declaration = decl.parent;
  119925. if (declaration) {
  119926. if (ts.isFunctionLikeKind(declaration.kind)) {
  119927. addInPrefix();
  119928. var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217
  119929. if (declaration.kind === 166 /* ConstructSignature */) {
  119930. displayParts.push(ts.keywordPart(99 /* NewKeyword */));
  119931. displayParts.push(ts.spacePart());
  119932. }
  119933. else if (declaration.kind !== 165 /* CallSignature */ && declaration.name) {
  119934. addFullSymbolName(declaration.symbol);
  119935. }
  119936. ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
  119937. }
  119938. else if (declaration.kind === 247 /* TypeAliasDeclaration */) {
  119939. // Type alias type parameter
  119940. // For example
  119941. // type list<T> = T[]; // Both T will go through same code path
  119942. addInPrefix();
  119943. displayParts.push(ts.keywordPart(145 /* TypeKeyword */));
  119944. displayParts.push(ts.spacePart());
  119945. addFullSymbolName(declaration.symbol);
  119946. writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
  119947. }
  119948. }
  119949. }
  119950. }
  119951. if (symbolFlags & 8 /* EnumMember */) {
  119952. symbolKind = "enum member" /* enumMemberElement */;
  119953. addPrefixForAnyFunctionOrVar(symbol, "enum member");
  119954. var declaration = symbol.declarations[0];
  119955. if (declaration.kind === 284 /* EnumMember */) {
  119956. var constantValue = typeChecker.getConstantValue(declaration);
  119957. if (constantValue !== undefined) {
  119958. displayParts.push(ts.spacePart());
  119959. displayParts.push(ts.operatorPart(62 /* EqualsToken */));
  119960. displayParts.push(ts.spacePart());
  119961. displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral));
  119962. }
  119963. }
  119964. }
  119965. if (symbolFlags & 2097152 /* Alias */) {
  119966. prefixNextMeaning();
  119967. if (!hasAddedSymbolInfo) {
  119968. var resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
  119969. if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) {
  119970. var resolvedNode = resolvedSymbol.declarations[0];
  119971. var declarationName = ts.getNameOfDeclaration(resolvedNode);
  119972. if (declarationName) {
  119973. var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) &&
  119974. ts.hasModifier(resolvedNode, 2 /* Ambient */);
  119975. var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration;
  119976. var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol);
  119977. displayParts.push.apply(displayParts, resolvedInfo.displayParts);
  119978. displayParts.push(ts.lineBreakPart());
  119979. documentationFromAlias = resolvedInfo.documentation;
  119980. tagsFromAlias = resolvedInfo.tags;
  119981. }
  119982. }
  119983. }
  119984. switch (symbol.declarations[0].kind) {
  119985. case 252 /* NamespaceExportDeclaration */:
  119986. displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
  119987. displayParts.push(ts.spacePart());
  119988. displayParts.push(ts.keywordPart(136 /* NamespaceKeyword */));
  119989. break;
  119990. case 259 /* ExportAssignment */:
  119991. displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
  119992. displayParts.push(ts.spacePart());
  119993. displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 84 /* DefaultKeyword */));
  119994. break;
  119995. case 263 /* ExportSpecifier */:
  119996. displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
  119997. break;
  119998. default:
  119999. displayParts.push(ts.keywordPart(96 /* ImportKeyword */));
  120000. }
  120001. displayParts.push(ts.spacePart());
  120002. addFullSymbolName(symbol);
  120003. ts.forEach(symbol.declarations, function (declaration) {
  120004. if (declaration.kind === 253 /* ImportEqualsDeclaration */) {
  120005. var importEqualsDeclaration = declaration;
  120006. if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
  120007. displayParts.push(ts.spacePart());
  120008. displayParts.push(ts.operatorPart(62 /* EqualsToken */));
  120009. displayParts.push(ts.spacePart());
  120010. displayParts.push(ts.keywordPart(139 /* RequireKeyword */));
  120011. displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
  120012. displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral));
  120013. displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
  120014. }
  120015. else {
  120016. var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference);
  120017. if (internalAliasSymbol) {
  120018. displayParts.push(ts.spacePart());
  120019. displayParts.push(ts.operatorPart(62 /* EqualsToken */));
  120020. displayParts.push(ts.spacePart());
  120021. addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
  120022. }
  120023. }
  120024. return true;
  120025. }
  120026. });
  120027. }
  120028. if (!hasAddedSymbolInfo) {
  120029. if (symbolKind !== "" /* unknown */) {
  120030. if (type) {
  120031. if (isThisExpression) {
  120032. prefixNextMeaning();
  120033. displayParts.push(ts.keywordPart(104 /* ThisKeyword */));
  120034. }
  120035. else {
  120036. addPrefixForAnyFunctionOrVar(symbol, symbolKind);
  120037. }
  120038. // For properties, variables and local vars: show the type
  120039. if (symbolKind === "property" /* memberVariableElement */ ||
  120040. symbolKind === "JSX attribute" /* jsxAttribute */ ||
  120041. symbolFlags & 3 /* Variable */ ||
  120042. symbolKind === "local var" /* localVariableElement */ ||
  120043. isThisExpression) {
  120044. displayParts.push(ts.punctuationPart(58 /* ColonToken */));
  120045. displayParts.push(ts.spacePart());
  120046. // If the type is type parameter, format it specially
  120047. if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) {
  120048. var typeParameterParts = ts.mapToDisplayParts(function (writer) {
  120049. var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration);
  120050. getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
  120051. });
  120052. ts.addRange(displayParts, typeParameterParts);
  120053. }
  120054. else {
  120055. ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration));
  120056. }
  120057. }
  120058. else if (symbolFlags & 16 /* Function */ ||
  120059. symbolFlags & 8192 /* Method */ ||
  120060. symbolFlags & 16384 /* Constructor */ ||
  120061. symbolFlags & 131072 /* Signature */ ||
  120062. symbolFlags & 98304 /* Accessor */ ||
  120063. symbolKind === "method" /* memberFunctionElement */) {
  120064. var allSignatures = type.getNonNullableType().getCallSignatures();
  120065. if (allSignatures.length) {
  120066. addSignatureDisplayParts(allSignatures[0], allSignatures);
  120067. hasMultipleSignatures = allSignatures.length > 1;
  120068. }
  120069. }
  120070. }
  120071. }
  120072. else {
  120073. symbolKind = getSymbolKind(typeChecker, symbol, location);
  120074. }
  120075. }
  120076. if (documentation.length === 0 && !hasMultipleSignatures) {
  120077. documentation = symbol.getDocumentationComment(typeChecker);
  120078. }
  120079. if (documentation.length === 0 && symbolFlags & 4 /* Property */) {
  120080. // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
  120081. // there documentation comments might be attached to the right hand side symbol of their declarations.
  120082. // The pattern of such special property access is that the parent symbol is the symbol of the file.
  120083. if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 290 /* SourceFile */; })) {
  120084. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  120085. var declaration = _a[_i];
  120086. if (!declaration.parent || declaration.parent.kind !== 209 /* BinaryExpression */) {
  120087. continue;
  120088. }
  120089. var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
  120090. if (!rhsSymbol) {
  120091. continue;
  120092. }
  120093. documentation = rhsSymbol.getDocumentationComment(typeChecker);
  120094. tags = rhsSymbol.getJsDocTags();
  120095. if (documentation.length > 0) {
  120096. break;
  120097. }
  120098. }
  120099. }
  120100. }
  120101. if (tags.length === 0 && !hasMultipleSignatures) {
  120102. tags = symbol.getJsDocTags();
  120103. }
  120104. if (documentation.length === 0 && documentationFromAlias) {
  120105. documentation = documentationFromAlias;
  120106. }
  120107. if (tags.length === 0 && tagsFromAlias) {
  120108. tags = tagsFromAlias;
  120109. }
  120110. return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags };
  120111. function getPrinter() {
  120112. if (!printer) {
  120113. printer = ts.createPrinter({ removeComments: true });
  120114. }
  120115. return printer;
  120116. }
  120117. function prefixNextMeaning() {
  120118. if (displayParts.length) {
  120119. displayParts.push(ts.lineBreakPart());
  120120. }
  120121. addAliasPrefixIfNecessary();
  120122. }
  120123. function addAliasPrefixIfNecessary() {
  120124. if (alias) {
  120125. pushSymbolKind("alias" /* alias */);
  120126. displayParts.push(ts.spacePart());
  120127. }
  120128. }
  120129. function addInPrefix() {
  120130. displayParts.push(ts.spacePart());
  120131. displayParts.push(ts.keywordPart(97 /* InKeyword */));
  120132. displayParts.push(ts.spacePart());
  120133. }
  120134. function addFullSymbolName(symbolToDisplay, enclosingDeclaration) {
  120135. if (alias && symbolToDisplay === symbol) {
  120136. symbolToDisplay = alias;
  120137. }
  120138. var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */);
  120139. ts.addRange(displayParts, fullSymbolDisplayParts);
  120140. if (symbol.flags & 16777216 /* Optional */) {
  120141. displayParts.push(ts.punctuationPart(57 /* QuestionToken */));
  120142. }
  120143. }
  120144. function addPrefixForAnyFunctionOrVar(symbol, symbolKind) {
  120145. prefixNextMeaning();
  120146. if (symbolKind) {
  120147. pushSymbolKind(symbolKind);
  120148. if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) {
  120149. displayParts.push(ts.spacePart());
  120150. addFullSymbolName(symbol);
  120151. }
  120152. }
  120153. }
  120154. function pushSymbolKind(symbolKind) {
  120155. switch (symbolKind) {
  120156. case "var" /* variableElement */:
  120157. case "function" /* functionElement */:
  120158. case "let" /* letElement */:
  120159. case "const" /* constElement */:
  120160. case "constructor" /* constructorImplementationElement */:
  120161. displayParts.push(ts.textOrKeywordPart(symbolKind));
  120162. return;
  120163. default:
  120164. displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
  120165. displayParts.push(ts.textOrKeywordPart(symbolKind));
  120166. displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
  120167. return;
  120168. }
  120169. }
  120170. function addSignatureDisplayParts(signature, allSignatures, flags) {
  120171. if (flags === void 0) { flags = 0 /* None */; }
  120172. ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */));
  120173. if (allSignatures.length > 1) {
  120174. displayParts.push(ts.spacePart());
  120175. displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
  120176. displayParts.push(ts.operatorPart(39 /* PlusToken */));
  120177. displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral));
  120178. displayParts.push(ts.spacePart());
  120179. displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads"));
  120180. displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
  120181. }
  120182. documentation = signature.getDocumentationComment(typeChecker);
  120183. tags = signature.getJsDocTags();
  120184. if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) {
  120185. documentation = allSignatures[0].getDocumentationComment(typeChecker);
  120186. tags = allSignatures[0].getJsDocTags();
  120187. }
  120188. }
  120189. function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) {
  120190. var typeParameterParts = ts.mapToDisplayParts(function (writer) {
  120191. var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration);
  120192. getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
  120193. });
  120194. ts.addRange(displayParts, typeParameterParts);
  120195. }
  120196. }
  120197. SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind;
  120198. function isLocalVariableOrFunction(symbol) {
  120199. if (symbol.parent) {
  120200. return false; // This is exported symbol
  120201. }
  120202. return ts.forEach(symbol.declarations, function (declaration) {
  120203. // Function expressions are local
  120204. if (declaration.kind === 201 /* FunctionExpression */) {
  120205. return true;
  120206. }
  120207. if (declaration.kind !== 242 /* VariableDeclaration */ && declaration.kind !== 244 /* FunctionDeclaration */) {
  120208. return false;
  120209. }
  120210. // If the parent is not sourceFile or module block it is local variable
  120211. for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
  120212. // Reached source file or module block
  120213. if (parent.kind === 290 /* SourceFile */ || parent.kind === 250 /* ModuleBlock */) {
  120214. return false;
  120215. }
  120216. }
  120217. // parent is in function block
  120218. return true;
  120219. });
  120220. }
  120221. })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {}));
  120222. })(ts || (ts = {}));
  120223. var ts;
  120224. (function (ts) {
  120225. /*
  120226. * This function will compile source text from 'input' argument using specified compiler options.
  120227. * If not options are provided - it will use a set of default compiler options.
  120228. * Extra compiler options that will unconditionally be used by this function are:
  120229. * - isolatedModules = true
  120230. * - allowNonTsExtensions = true
  120231. * - noLib = true
  120232. * - noResolve = true
  120233. */
  120234. function transpileModule(input, transpileOptions) {
  120235. var diagnostics = [];
  120236. var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : {};
  120237. // mix in default options
  120238. var defaultOptions = ts.getDefaultCompilerOptions();
  120239. for (var key in defaultOptions) {
  120240. if (ts.hasProperty(defaultOptions, key) && options[key] === undefined) {
  120241. options[key] = defaultOptions[key];
  120242. }
  120243. }
  120244. for (var _i = 0, transpileOptionValueCompilerOptions_1 = ts.transpileOptionValueCompilerOptions; _i < transpileOptionValueCompilerOptions_1.length; _i++) {
  120245. var option = transpileOptionValueCompilerOptions_1[_i];
  120246. options[option.name] = option.transpileOptionValue;
  120247. }
  120248. // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
  120249. options.suppressOutputPathCheck = true;
  120250. // Filename can be non-ts file.
  120251. options.allowNonTsExtensions = true;
  120252. // if jsx is specified then treat file as .tsx
  120253. var inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts");
  120254. var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217
  120255. if (transpileOptions.moduleName) {
  120256. sourceFile.moduleName = transpileOptions.moduleName;
  120257. }
  120258. if (transpileOptions.renamedDependencies) {
  120259. sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies);
  120260. }
  120261. var newLine = ts.getNewLineCharacter(options);
  120262. // Output
  120263. var outputText;
  120264. var sourceMapText;
  120265. // Create a compilerHost object to allow the compiler to read and write files
  120266. var compilerHost = {
  120267. getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; },
  120268. writeFile: function (name, text) {
  120269. if (ts.fileExtensionIs(name, ".map")) {
  120270. ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name);
  120271. sourceMapText = text;
  120272. }
  120273. else {
  120274. ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name);
  120275. outputText = text;
  120276. }
  120277. },
  120278. getDefaultLibFileName: function () { return "lib.d.ts"; },
  120279. useCaseSensitiveFileNames: function () { return false; },
  120280. getCanonicalFileName: function (fileName) { return fileName; },
  120281. getCurrentDirectory: function () { return ""; },
  120282. getNewLine: function () { return newLine; },
  120283. fileExists: function (fileName) { return fileName === inputFileName; },
  120284. readFile: function () { return ""; },
  120285. directoryExists: function () { return true; },
  120286. getDirectories: function () { return []; }
  120287. };
  120288. var program = ts.createProgram([inputFileName], options, compilerHost);
  120289. if (transpileOptions.reportDiagnostics) {
  120290. ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
  120291. ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
  120292. }
  120293. // Emit
  120294. program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers);
  120295. if (outputText === undefined)
  120296. return ts.Debug.fail("Output generation failed");
  120297. return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText };
  120298. }
  120299. ts.transpileModule = transpileModule;
  120300. /*
  120301. * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result.
  120302. */
  120303. function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
  120304. var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName });
  120305. // addRange correctly handles cases when wither 'from' or 'to' argument is missing
  120306. ts.addRange(diagnostics, output.diagnostics);
  120307. return output.outputText;
  120308. }
  120309. ts.transpile = transpile;
  120310. var commandLineOptionsStringToEnum;
  120311. /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */
  120312. /*@internal*/
  120313. function fixupCompilerOptions(options, diagnostics) {
  120314. // Lazily create this value to fix module loading errors.
  120315. commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) {
  120316. return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
  120317. });
  120318. options = ts.cloneCompilerOptions(options);
  120319. var _loop_8 = function (opt) {
  120320. if (!ts.hasProperty(options, opt.name)) {
  120321. return "continue";
  120322. }
  120323. var value = options[opt.name];
  120324. // Value should be a key of opt.type
  120325. if (ts.isString(value)) {
  120326. // If value is not a string, this will fail
  120327. options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics);
  120328. }
  120329. else {
  120330. if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) {
  120331. // Supplied value isn't a valid enum value.
  120332. diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt));
  120333. }
  120334. }
  120335. };
  120336. for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
  120337. var opt = commandLineOptionsStringToEnum_1[_i];
  120338. _loop_8(opt);
  120339. }
  120340. return options;
  120341. }
  120342. ts.fixupCompilerOptions = fixupCompilerOptions;
  120343. })(ts || (ts = {}));
  120344. /* @internal */
  120345. var ts;
  120346. (function (ts) {
  120347. var formatting;
  120348. (function (formatting) {
  120349. var FormattingRequestKind;
  120350. (function (FormattingRequestKind) {
  120351. FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument";
  120352. FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection";
  120353. FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter";
  120354. FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon";
  120355. FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace";
  120356. FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace";
  120357. })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {}));
  120358. var FormattingContext = /** @class */ (function () {
  120359. function FormattingContext(sourceFile, formattingRequestKind, options) {
  120360. this.sourceFile = sourceFile;
  120361. this.formattingRequestKind = formattingRequestKind;
  120362. this.options = options;
  120363. }
  120364. FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
  120365. this.currentTokenSpan = ts.Debug.assertDefined(currentRange);
  120366. this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent);
  120367. this.nextTokenSpan = ts.Debug.assertDefined(nextRange);
  120368. this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent);
  120369. this.contextNode = ts.Debug.assertDefined(commonParent);
  120370. // drop cached results
  120371. this.contextNodeAllOnSameLine = undefined;
  120372. this.nextNodeAllOnSameLine = undefined;
  120373. this.tokensAreOnSameLine = undefined;
  120374. this.contextNodeBlockIsOnOneLine = undefined;
  120375. this.nextNodeBlockIsOnOneLine = undefined;
  120376. };
  120377. FormattingContext.prototype.ContextNodeAllOnSameLine = function () {
  120378. if (this.contextNodeAllOnSameLine === undefined) {
  120379. this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
  120380. }
  120381. return this.contextNodeAllOnSameLine;
  120382. };
  120383. FormattingContext.prototype.NextNodeAllOnSameLine = function () {
  120384. if (this.nextNodeAllOnSameLine === undefined) {
  120385. this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
  120386. }
  120387. return this.nextNodeAllOnSameLine;
  120388. };
  120389. FormattingContext.prototype.TokensAreOnSameLine = function () {
  120390. if (this.tokensAreOnSameLine === undefined) {
  120391. var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
  120392. var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
  120393. this.tokensAreOnSameLine = (startLine === endLine);
  120394. }
  120395. return this.tokensAreOnSameLine;
  120396. };
  120397. FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () {
  120398. if (this.contextNodeBlockIsOnOneLine === undefined) {
  120399. this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
  120400. }
  120401. return this.contextNodeBlockIsOnOneLine;
  120402. };
  120403. FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () {
  120404. if (this.nextNodeBlockIsOnOneLine === undefined) {
  120405. this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
  120406. }
  120407. return this.nextNodeBlockIsOnOneLine;
  120408. };
  120409. FormattingContext.prototype.NodeIsOnOneLine = function (node) {
  120410. var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
  120411. var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
  120412. return startLine === endLine;
  120413. };
  120414. FormattingContext.prototype.BlockIsOnOneLine = function (node) {
  120415. var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile);
  120416. var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile);
  120417. if (openBrace && closeBrace) {
  120418. var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
  120419. var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
  120420. return startLine === endLine;
  120421. }
  120422. return false;
  120423. };
  120424. return FormattingContext;
  120425. }());
  120426. formatting.FormattingContext = FormattingContext;
  120427. })(formatting = ts.formatting || (ts.formatting = {}));
  120428. })(ts || (ts = {}));
  120429. /* @internal */
  120430. var ts;
  120431. (function (ts) {
  120432. var formatting;
  120433. (function (formatting) {
  120434. var standardScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
  120435. var jsxScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
  120436. var ScanAction;
  120437. (function (ScanAction) {
  120438. ScanAction[ScanAction["Scan"] = 0] = "Scan";
  120439. ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken";
  120440. ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
  120441. ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
  120442. ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
  120443. ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
  120444. ScanAction[ScanAction["RescanJsxAttributeValue"] = 6] = "RescanJsxAttributeValue";
  120445. })(ScanAction || (ScanAction = {}));
  120446. function getFormattingScanner(text, languageVariant, startPos, endPos, cb) {
  120447. var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
  120448. scanner.setText(text);
  120449. scanner.setTextPos(startPos);
  120450. var wasNewLine = true;
  120451. var leadingTrivia;
  120452. var trailingTrivia;
  120453. var savedPos;
  120454. var lastScanAction;
  120455. var lastTokenInfo;
  120456. var res = cb({
  120457. advance: advance,
  120458. readTokenInfo: readTokenInfo,
  120459. readEOFTokenRange: readEOFTokenRange,
  120460. isOnToken: isOnToken,
  120461. isOnEOF: isOnEOF,
  120462. getCurrentLeadingTrivia: function () { return leadingTrivia; },
  120463. lastTrailingTriviaWasNewLine: function () { return wasNewLine; },
  120464. skipToEndOf: skipToEndOf,
  120465. });
  120466. lastTokenInfo = undefined;
  120467. scanner.setText(undefined);
  120468. return res;
  120469. function advance() {
  120470. lastTokenInfo = undefined;
  120471. var isStarted = scanner.getStartPos() !== startPos;
  120472. if (isStarted) {
  120473. wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */;
  120474. }
  120475. else {
  120476. scanner.scan();
  120477. }
  120478. leadingTrivia = undefined;
  120479. trailingTrivia = undefined;
  120480. var pos = scanner.getStartPos();
  120481. // Read leading trivia and token
  120482. while (pos < endPos) {
  120483. var t = scanner.getToken();
  120484. if (!ts.isTrivia(t)) {
  120485. break;
  120486. }
  120487. // consume leading trivia
  120488. scanner.scan();
  120489. var item = {
  120490. pos: pos,
  120491. end: scanner.getStartPos(),
  120492. kind: t
  120493. };
  120494. pos = scanner.getStartPos();
  120495. leadingTrivia = ts.append(leadingTrivia, item);
  120496. }
  120497. savedPos = scanner.getStartPos();
  120498. }
  120499. function shouldRescanGreaterThanToken(node) {
  120500. switch (node.kind) {
  120501. case 33 /* GreaterThanEqualsToken */:
  120502. case 70 /* GreaterThanGreaterThanEqualsToken */:
  120503. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  120504. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  120505. case 48 /* GreaterThanGreaterThanToken */:
  120506. return true;
  120507. }
  120508. return false;
  120509. }
  120510. function shouldRescanJsxIdentifier(node) {
  120511. if (node.parent) {
  120512. switch (node.parent.kind) {
  120513. case 273 /* JsxAttribute */:
  120514. case 268 /* JsxOpeningElement */:
  120515. case 269 /* JsxClosingElement */:
  120516. case 267 /* JsxSelfClosingElement */:
  120517. // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier.
  120518. return ts.isKeyword(node.kind) || node.kind === 75 /* Identifier */;
  120519. }
  120520. }
  120521. return false;
  120522. }
  120523. function shouldRescanJsxText(node) {
  120524. var isJSXText = ts.isJsxText(node);
  120525. if (isJSXText) {
  120526. var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); });
  120527. if (!containingElement)
  120528. return false; // should never happen
  120529. return !ts.isParenthesizedExpression(containingElement.parent);
  120530. }
  120531. return false;
  120532. }
  120533. function shouldRescanSlashToken(container) {
  120534. return container.kind === 13 /* RegularExpressionLiteral */;
  120535. }
  120536. function shouldRescanTemplateToken(container) {
  120537. return container.kind === 16 /* TemplateMiddle */ ||
  120538. container.kind === 17 /* TemplateTail */;
  120539. }
  120540. function shouldRescanJsxAttributeValue(node) {
  120541. return node.parent && ts.isJsxAttribute(node.parent) && node.parent.initializer === node;
  120542. }
  120543. function startsWithSlashToken(t) {
  120544. return t === 43 /* SlashToken */ || t === 67 /* SlashEqualsToken */;
  120545. }
  120546. function readTokenInfo(n) {
  120547. ts.Debug.assert(isOnToken());
  120548. // normally scanner returns the smallest available token
  120549. // check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
  120550. var expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ :
  120551. shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ :
  120552. shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ :
  120553. shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ :
  120554. shouldRescanJsxText(n) ? 5 /* RescanJsxText */ :
  120555. shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ :
  120556. 0 /* Scan */;
  120557. if (lastTokenInfo && expectedScanAction === lastScanAction) {
  120558. // readTokenInfo was called before with the same expected scan action.
  120559. // No need to re-scan text, return existing 'lastTokenInfo'
  120560. // it is ok to call fixTokenKind here since it does not affect
  120561. // what portion of text is consumed. In contrast rescanning can change it,
  120562. // i.e. for '>=' when originally scanner eats just one character
  120563. // and rescanning forces it to consume more.
  120564. return fixTokenKind(lastTokenInfo, n);
  120565. }
  120566. if (scanner.getStartPos() !== savedPos) {
  120567. ts.Debug.assert(lastTokenInfo !== undefined);
  120568. // readTokenInfo was called before but scan action differs - rescan text
  120569. scanner.setTextPos(savedPos);
  120570. scanner.scan();
  120571. }
  120572. var currentToken = getNextToken(n, expectedScanAction);
  120573. var token = formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), currentToken);
  120574. // consume trailing trivia
  120575. if (trailingTrivia) {
  120576. trailingTrivia = undefined;
  120577. }
  120578. while (scanner.getStartPos() < endPos) {
  120579. currentToken = scanner.scan();
  120580. if (!ts.isTrivia(currentToken)) {
  120581. break;
  120582. }
  120583. var trivia = formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), currentToken);
  120584. if (!trailingTrivia) {
  120585. trailingTrivia = [];
  120586. }
  120587. trailingTrivia.push(trivia);
  120588. if (currentToken === 4 /* NewLineTrivia */) {
  120589. // move past new line
  120590. scanner.scan();
  120591. break;
  120592. }
  120593. }
  120594. lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token };
  120595. return fixTokenKind(lastTokenInfo, n);
  120596. }
  120597. function getNextToken(n, expectedScanAction) {
  120598. var token = scanner.getToken();
  120599. lastScanAction = 0 /* Scan */;
  120600. switch (expectedScanAction) {
  120601. case 1 /* RescanGreaterThanToken */:
  120602. if (token === 31 /* GreaterThanToken */) {
  120603. lastScanAction = 1 /* RescanGreaterThanToken */;
  120604. var newToken = scanner.reScanGreaterToken();
  120605. ts.Debug.assert(n.kind === newToken);
  120606. return newToken;
  120607. }
  120608. break;
  120609. case 2 /* RescanSlashToken */:
  120610. if (startsWithSlashToken(token)) {
  120611. lastScanAction = 2 /* RescanSlashToken */;
  120612. var newToken = scanner.reScanSlashToken();
  120613. ts.Debug.assert(n.kind === newToken);
  120614. return newToken;
  120615. }
  120616. break;
  120617. case 3 /* RescanTemplateToken */:
  120618. if (token === 19 /* CloseBraceToken */) {
  120619. lastScanAction = 3 /* RescanTemplateToken */;
  120620. return scanner.reScanTemplateToken();
  120621. }
  120622. break;
  120623. case 4 /* RescanJsxIdentifier */:
  120624. lastScanAction = 4 /* RescanJsxIdentifier */;
  120625. return scanner.scanJsxIdentifier();
  120626. case 5 /* RescanJsxText */:
  120627. lastScanAction = 5 /* RescanJsxText */;
  120628. return scanner.reScanJsxToken();
  120629. case 6 /* RescanJsxAttributeValue */:
  120630. lastScanAction = 6 /* RescanJsxAttributeValue */;
  120631. return scanner.reScanJsxAttributeValue();
  120632. case 0 /* Scan */:
  120633. break;
  120634. default:
  120635. ts.Debug.assertNever(expectedScanAction);
  120636. }
  120637. return token;
  120638. }
  120639. function readEOFTokenRange() {
  120640. ts.Debug.assert(isOnEOF());
  120641. return formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), 1 /* EndOfFileToken */);
  120642. }
  120643. function isOnToken() {
  120644. var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
  120645. var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos();
  120646. return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current);
  120647. }
  120648. function isOnEOF() {
  120649. var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
  120650. return current === 1 /* EndOfFileToken */;
  120651. }
  120652. // when containing node in the tree is token
  120653. // but its kind differs from the kind that was returned by the scanner,
  120654. // then kind needs to be fixed. This might happen in cases
  120655. // when parser interprets token differently, i.e keyword treated as identifier
  120656. function fixTokenKind(tokenInfo, container) {
  120657. if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {
  120658. tokenInfo.token.kind = container.kind;
  120659. }
  120660. return tokenInfo;
  120661. }
  120662. function skipToEndOf(node) {
  120663. scanner.setTextPos(node.end);
  120664. savedPos = scanner.getStartPos();
  120665. lastScanAction = undefined;
  120666. lastTokenInfo = undefined;
  120667. wasNewLine = false;
  120668. leadingTrivia = undefined;
  120669. trailingTrivia = undefined;
  120670. }
  120671. }
  120672. formatting.getFormattingScanner = getFormattingScanner;
  120673. })(formatting = ts.formatting || (ts.formatting = {}));
  120674. })(ts || (ts = {}));
  120675. /* @internal */
  120676. var ts;
  120677. (function (ts) {
  120678. var formatting;
  120679. (function (formatting) {
  120680. formatting.anyContext = ts.emptyArray;
  120681. var RuleAction;
  120682. (function (RuleAction) {
  120683. RuleAction[RuleAction["StopProcessingSpaceActions"] = 1] = "StopProcessingSpaceActions";
  120684. RuleAction[RuleAction["StopProcessingTokenActions"] = 2] = "StopProcessingTokenActions";
  120685. RuleAction[RuleAction["InsertSpace"] = 4] = "InsertSpace";
  120686. RuleAction[RuleAction["InsertNewLine"] = 8] = "InsertNewLine";
  120687. RuleAction[RuleAction["DeleteSpace"] = 16] = "DeleteSpace";
  120688. RuleAction[RuleAction["DeleteToken"] = 32] = "DeleteToken";
  120689. RuleAction[RuleAction["InsertTrailingSemicolon"] = 64] = "InsertTrailingSemicolon";
  120690. RuleAction[RuleAction["StopAction"] = 3] = "StopAction";
  120691. RuleAction[RuleAction["ModifySpaceAction"] = 28] = "ModifySpaceAction";
  120692. RuleAction[RuleAction["ModifyTokenAction"] = 96] = "ModifyTokenAction";
  120693. })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {}));
  120694. var RuleFlags;
  120695. (function (RuleFlags) {
  120696. RuleFlags[RuleFlags["None"] = 0] = "None";
  120697. RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines";
  120698. })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {}));
  120699. })(formatting = ts.formatting || (ts.formatting = {}));
  120700. })(ts || (ts = {}));
  120701. /* @internal */
  120702. var ts;
  120703. (function (ts) {
  120704. var formatting;
  120705. (function (formatting) {
  120706. function getAllRules() {
  120707. var allTokens = [];
  120708. for (var token = 0 /* FirstToken */; token <= 152 /* LastToken */; token++) {
  120709. if (token !== 1 /* EndOfFileToken */) {
  120710. allTokens.push(token);
  120711. }
  120712. }
  120713. function anyTokenExcept() {
  120714. var tokens = [];
  120715. for (var _i = 0; _i < arguments.length; _i++) {
  120716. tokens[_i] = arguments[_i];
  120717. }
  120718. return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false };
  120719. }
  120720. var anyToken = { tokens: allTokens, isSpecific: false };
  120721. var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArrays(allTokens, [3 /* MultiLineCommentTrivia */]));
  120722. var anyTokenIncludingEOF = tokenRangeFrom(__spreadArrays(allTokens, [1 /* EndOfFileToken */]));
  120723. var keywords = tokenRangeFromRange(77 /* FirstKeyword */, 152 /* LastKeyword */);
  120724. var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 74 /* LastBinaryOperator */);
  120725. var binaryKeywordOperators = [97 /* InKeyword */, 98 /* InstanceOfKeyword */, 152 /* OfKeyword */, 123 /* AsKeyword */, 133 /* IsKeyword */];
  120726. var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */];
  120727. var unaryPrefixExpressions = [
  120728. 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 75 /* Identifier */, 20 /* OpenParenToken */,
  120729. 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */
  120730. ];
  120731. var unaryPreincrementExpressions = [75 /* Identifier */, 20 /* OpenParenToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */];
  120732. var unaryPostincrementExpressions = [75 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 99 /* NewKeyword */];
  120733. var unaryPredecrementExpressions = [75 /* Identifier */, 20 /* OpenParenToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */];
  120734. var unaryPostdecrementExpressions = [75 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 99 /* NewKeyword */];
  120735. var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
  120736. var typeNames = __spreadArrays([75 /* Identifier */], ts.typeKeywords);
  120737. // Place a space before open brace in a function declaration
  120738. // TypeScript: Function can have return types, which can be made of tons of different token kinds
  120739. var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
  120740. // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc)
  120741. var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([75 /* Identifier */, 3 /* MultiLineCommentTrivia */, 80 /* ClassKeyword */, 89 /* ExportKeyword */, 96 /* ImportKeyword */]);
  120742. // Place a space before open brace in a control flow construct
  120743. var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 86 /* DoKeyword */, 107 /* TryKeyword */, 92 /* FinallyKeyword */, 87 /* ElseKeyword */]);
  120744. // These rules are higher in priority than user-configurable
  120745. var highPriorityCommonRules = [
  120746. // Leave comments alone
  120747. rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* StopProcessingSpaceActions */),
  120748. rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* StopProcessingSpaceActions */),
  120749. rule("NotSpaceBeforeColon", anyToken, 58 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
  120750. rule("SpaceAfterColon", 58 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 4 /* InsertSpace */),
  120751. rule("NoSpaceBeforeQuestionMark", anyToken, 57 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
  120752. // insert space after '?' only when it is used in conditional operator
  120753. rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */),
  120754. // in other cases there should be no space between '?' and next token
  120755. rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120756. rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120757. rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120758. rule("NoSpaceBetweenImportParenInImportType", 96 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */),
  120759. // Special handling of unary operators.
  120760. // Prefix operators generally shouldn't have a space between
  120761. // them and their target unary expression.
  120762. rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
  120763. rule("NoSpaceAfterUnaryPreincrementOperator", 45 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120764. rule("NoSpaceAfterUnaryPredecrementOperator", 46 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120765. rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 45 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
  120766. rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 46 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
  120767. // More unary operator special-casing.
  120768. // DevDiv 181814: Be careful when removing leading whitespace
  120769. // around unary operators. Examples:
  120770. // 1 - -2 --X--> 1--2
  120771. // a + ++b --X--> a+++b
  120772. rule("SpaceAfterPostincrementWhenFollowedByAdd", 45 /* PlusPlusToken */, 39 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120773. rule("SpaceAfterAddWhenFollowedByUnaryPlus", 39 /* PlusToken */, 39 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120774. rule("SpaceAfterAddWhenFollowedByPreincrement", 39 /* PlusToken */, 45 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120775. rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 46 /* MinusMinusToken */, 40 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120776. rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 40 /* MinusToken */, 40 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120777. rule("SpaceAfterSubtractWhenFollowedByPredecrement", 40 /* MinusToken */, 46 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120778. rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120779. // For functions and control block place } on a new line [multi-line rule]
  120780. rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */),
  120781. // Space/new line after }.
  120782. rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */),
  120783. // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
  120784. // Also should not apply to })
  120785. rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 87 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120786. rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 111 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120787. rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
  120788. // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];'
  120789. rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */),
  120790. rule("NoSpaceBetweenFunctionKeywordAndStar", 94 /* FunctionKeyword */, 41 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */),
  120791. rule("SpaceAfterStarInGeneratorDeclaration", 41 /* AsteriskToken */, 75 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */),
  120792. rule("SpaceAfterFunctionInFuncDecl", 94 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */),
  120793. // Insert new line after { and before } in multi-line contexts.
  120794. rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */),
  120795. // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token.
  120796. // Though, we do extra check on the context to make sure we are dealing with get/set node. Example:
  120797. // get x() {}
  120798. // set x(val) {}
  120799. rule("SpaceAfterGetSetInMember", [131 /* GetKeyword */, 142 /* SetKeyword */], 75 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */),
  120800. rule("NoSpaceBetweenYieldKeywordAndStar", 121 /* YieldKeyword */, 41 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */),
  120801. rule("SpaceBetweenYieldOrYieldStarAndOperand", [121 /* YieldKeyword */, 41 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */),
  120802. rule("NoSpaceBetweenReturnAndSemicolon", 101 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120803. rule("SpaceAfterCertainKeywords", [109 /* VarKeyword */, 105 /* ThrowKeyword */, 99 /* NewKeyword */, 85 /* DeleteKeyword */, 101 /* ReturnKeyword */, 108 /* TypeOfKeyword */, 127 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120804. rule("SpaceAfterLetConstInVariableDeclaration", [115 /* LetKeyword */, 81 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */),
  120805. rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */),
  120806. // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
  120807. rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120808. rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120809. rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */),
  120810. // Async-await
  120811. rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120812. rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, 94 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120813. // Template string
  120814. rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120815. // JSX opening elements
  120816. rule("SpaceBeforeJsxAttribute", anyToken, 75 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120817. rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 43 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120818. rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 43 /* SlashToken */, 31 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120819. rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 62 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120820. rule("NoSpaceAfterEqualInJsxAttribute", 62 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120821. // TypeScript-specific rules
  120822. // Use of module as a function call. e.g.: import m2 = module("m2");
  120823. rule("NoSpaceAfterModuleImport", [135 /* ModuleKeyword */, 139 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120824. // Add a space around certain TypeScript keywords
  120825. rule("SpaceAfterCertainTypeScriptKeywords", [
  120826. 122 /* AbstractKeyword */,
  120827. 80 /* ClassKeyword */,
  120828. 130 /* DeclareKeyword */,
  120829. 84 /* DefaultKeyword */,
  120830. 88 /* EnumKeyword */,
  120831. 89 /* ExportKeyword */,
  120832. 90 /* ExtendsKeyword */,
  120833. 131 /* GetKeyword */,
  120834. 113 /* ImplementsKeyword */,
  120835. 96 /* ImportKeyword */,
  120836. 114 /* InterfaceKeyword */,
  120837. 135 /* ModuleKeyword */,
  120838. 136 /* NamespaceKeyword */,
  120839. 117 /* PrivateKeyword */,
  120840. 119 /* PublicKeyword */,
  120841. 118 /* ProtectedKeyword */,
  120842. 138 /* ReadonlyKeyword */,
  120843. 142 /* SetKeyword */,
  120844. 120 /* StaticKeyword */,
  120845. 145 /* TypeKeyword */,
  120846. 149 /* FromKeyword */,
  120847. 134 /* KeyOfKeyword */,
  120848. 132 /* InferKeyword */,
  120849. ], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120850. rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [90 /* ExtendsKeyword */, 113 /* ImplementsKeyword */, 149 /* FromKeyword */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120851. // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
  120852. rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */),
  120853. // Lambda expressions
  120854. rule("SpaceBeforeArrow", anyToken, 38 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120855. rule("SpaceAfterArrow", 38 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120856. // Optional parameters and let args
  120857. rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 75 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120858. rule("NoSpaceAfterOptionalParameters", 57 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
  120859. // Remove spaces in empty interface literals. e.g.: x: {}
  120860. rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */),
  120861. // generics and type assertions
  120862. rule("NoSpaceBeforeOpenAngularBracket", typeNames, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
  120863. rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
  120864. rule("NoSpaceAfterOpenAngularBracket", 29 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
  120865. rule("NoSpaceBeforeCloseAngularBracket", anyToken, 31 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
  120866. rule("NoSpaceAfterCloseAngularBracket", 31 /* GreaterThanToken */, [20 /* OpenParenToken */, 22 /* OpenBracketToken */, 31 /* GreaterThanToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 16 /* DeleteSpace */),
  120867. // decorators
  120868. rule("SpaceBeforeAt", [21 /* CloseParenToken */, 75 /* Identifier */], 59 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120869. rule("NoSpaceAfterAt", 59 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120870. // Insert space after @ in decorator
  120871. rule("SpaceAfterDecorator", anyToken, [
  120872. 122 /* AbstractKeyword */,
  120873. 75 /* Identifier */,
  120874. 89 /* ExportKeyword */,
  120875. 84 /* DefaultKeyword */,
  120876. 80 /* ClassKeyword */,
  120877. 120 /* StaticKeyword */,
  120878. 119 /* PublicKeyword */,
  120879. 117 /* PrivateKeyword */,
  120880. 118 /* ProtectedKeyword */,
  120881. 131 /* GetKeyword */,
  120882. 142 /* SetKeyword */,
  120883. 22 /* OpenBracketToken */,
  120884. 41 /* AsteriskToken */,
  120885. ], [isEndOfDecoratorContextOnSameLine], 4 /* InsertSpace */),
  120886. rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 53 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */),
  120887. rule("NoSpaceAfterNewKeywordOnConstructorSignature", 99 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */),
  120888. rule("SpaceLessThanAndNonJSXTypeAnnotation", 29 /* LessThanToken */, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120889. ];
  120890. // These rules are applied after high priority
  120891. var userConfigurableRules = [
  120892. // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
  120893. rule("SpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120894. rule("NoSpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120895. rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 4 /* InsertSpace */),
  120896. rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */),
  120897. // Insert space after function keyword for anonymous functions
  120898. rule("SpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */),
  120899. rule("NoSpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */),
  120900. // Insert space after keywords in control flow statements
  120901. rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */),
  120902. rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */),
  120903. // Insert space after opening and before closing nonempty parenthesis
  120904. rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120905. rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120906. rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120907. rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120908. rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120909. rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120910. // Insert space after opening and before closing nonempty brackets
  120911. rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120912. rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120913. rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120914. rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120915. rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120916. // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
  120917. rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
  120918. rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
  120919. rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
  120920. rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120921. rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120922. // Insert space after opening and before closing template string braces
  120923. rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120924. rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120925. rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120926. rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120927. // No space after { and before } in JSX expression
  120928. rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
  120929. rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
  120930. rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
  120931. rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
  120932. // Insert space after semicolon in for statement
  120933. rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */),
  120934. rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */),
  120935. // Insert space before and after binary operators
  120936. rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120937. rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
  120938. rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
  120939. rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
  120940. rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */),
  120941. rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */),
  120942. // Open Brace braces after control block
  120943. rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
  120944. // Open Brace braces after function
  120945. // TypeScript: Function can have return types, which can be made of tons of different token kinds
  120946. rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
  120947. // Open Brace braces after TypeScript module/class/interface
  120948. rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
  120949. rule("SpaceAfterTypeAssertion", 31 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */),
  120950. rule("NoSpaceAfterTypeAssertion", 31 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */),
  120951. rule("SpaceBeforeTypeAnnotation", anyToken, 58 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */),
  120952. rule("NoSpaceBeforeTypeAnnotation", anyToken, 58 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */),
  120953. rule("NoOptionalSemicolon", 26 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", ts.SemicolonPreference.Remove), isSemicolonDeletionContext], 32 /* DeleteToken */),
  120954. rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", ts.SemicolonPreference.Insert), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */),
  120955. ];
  120956. // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list.
  120957. var lowPriorityCommonRules = [
  120958. // Space after keyword but not before ; or : or ?
  120959. rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120960. rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
  120961. rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
  120962. rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
  120963. rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120964. // No space before and after indexer `x[]`
  120965. rule("NoSpaceBeforeOpenBracket", anyTokenExcept(126 /* AsyncKeyword */, 78 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
  120966. rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */),
  120967. rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120968. // Remove extra space between for and await
  120969. rule("SpaceBetweenForAndAwaitKeyword", 93 /* ForKeyword */, 127 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120970. // Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
  120971. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
  120972. rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 86 /* DoKeyword */, 87 /* ElseKeyword */, 78 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 4 /* InsertSpace */),
  120973. // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
  120974. rule("SpaceAfterTryFinally", [107 /* TryKeyword */, 92 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
  120975. ];
  120976. return __spreadArrays(highPriorityCommonRules, userConfigurableRules, lowPriorityCommonRules);
  120977. }
  120978. formatting.getAllRules = getAllRules;
  120979. /**
  120980. * A rule takes a two tokens (left/right) and a particular context
  120981. * for which you're meant to look at them. You then declare what should the
  120982. * whitespace annotation be between these tokens via the action param.
  120983. *
  120984. * @param debugName Name to print
  120985. * @param left The left side of the comparison
  120986. * @param right The right side of the comparison
  120987. * @param context A set of filters to narrow down the space in which this formatter rule applies
  120988. * @param action a declaration of the expected whitespace
  120989. * @param flags whether the rule deletes a line or not, defaults to no-op
  120990. */
  120991. function rule(debugName, left, right, context, action, flags) {
  120992. if (flags === void 0) { flags = 0 /* None */; }
  120993. return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } };
  120994. }
  120995. function tokenRangeFrom(tokens) {
  120996. return { tokens: tokens, isSpecific: true };
  120997. }
  120998. function toTokenRange(arg) {
  120999. return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg;
  121000. }
  121001. function tokenRangeFromRange(from, to, except) {
  121002. if (except === void 0) { except = []; }
  121003. var tokens = [];
  121004. for (var token = from; token <= to; token++) {
  121005. if (!ts.contains(except, token)) {
  121006. tokens.push(token);
  121007. }
  121008. }
  121009. return tokenRangeFrom(tokens);
  121010. }
  121011. ///
  121012. /// Contexts
  121013. ///
  121014. function optionEquals(optionName, optionValue) {
  121015. return function (context) { return context.options && context.options[optionName] === optionValue; };
  121016. }
  121017. function isOptionEnabled(optionName) {
  121018. return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; };
  121019. }
  121020. function isOptionDisabled(optionName) {
  121021. return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; };
  121022. }
  121023. function isOptionDisabledOrUndefined(optionName) {
  121024. return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; };
  121025. }
  121026. function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) {
  121027. return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); };
  121028. }
  121029. function isOptionEnabledOrUndefined(optionName) {
  121030. return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; };
  121031. }
  121032. function isForContext(context) {
  121033. return context.contextNode.kind === 230 /* ForStatement */;
  121034. }
  121035. function isNotForContext(context) {
  121036. return !isForContext(context);
  121037. }
  121038. function isBinaryOpContext(context) {
  121039. switch (context.contextNode.kind) {
  121040. case 209 /* BinaryExpression */:
  121041. return context.contextNode.operatorToken.kind !== 27 /* CommaToken */;
  121042. case 210 /* ConditionalExpression */:
  121043. case 180 /* ConditionalType */:
  121044. case 217 /* AsExpression */:
  121045. case 263 /* ExportSpecifier */:
  121046. case 258 /* ImportSpecifier */:
  121047. case 168 /* TypePredicate */:
  121048. case 178 /* UnionType */:
  121049. case 179 /* IntersectionType */:
  121050. return true;
  121051. // equals in binding elements: function foo([[x, y] = [1, 2]])
  121052. case 191 /* BindingElement */:
  121053. // equals in type X = ...
  121054. // falls through
  121055. case 247 /* TypeAliasDeclaration */:
  121056. // equal in import a = module('a');
  121057. // falls through
  121058. case 253 /* ImportEqualsDeclaration */:
  121059. // equal in let a = 0
  121060. // falls through
  121061. case 242 /* VariableDeclaration */:
  121062. // equal in p = 0
  121063. // falls through
  121064. case 156 /* Parameter */:
  121065. case 284 /* EnumMember */:
  121066. case 159 /* PropertyDeclaration */:
  121067. case 158 /* PropertySignature */:
  121068. return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */;
  121069. // "in" keyword in for (let x in []) { }
  121070. case 231 /* ForInStatement */:
  121071. // "in" keyword in [P in keyof T]: T[P]
  121072. // falls through
  121073. case 155 /* TypeParameter */:
  121074. return context.currentTokenSpan.kind === 97 /* InKeyword */ || context.nextTokenSpan.kind === 97 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */;
  121075. // Technically, "of" is not a binary operator, but format it the same way as "in"
  121076. case 232 /* ForOfStatement */:
  121077. return context.currentTokenSpan.kind === 152 /* OfKeyword */ || context.nextTokenSpan.kind === 152 /* OfKeyword */;
  121078. }
  121079. return false;
  121080. }
  121081. function isNotBinaryOpContext(context) {
  121082. return !isBinaryOpContext(context);
  121083. }
  121084. function isNotTypeAnnotationContext(context) {
  121085. return !isTypeAnnotationContext(context);
  121086. }
  121087. function isTypeAnnotationContext(context) {
  121088. var contextKind = context.contextNode.kind;
  121089. return contextKind === 159 /* PropertyDeclaration */ ||
  121090. contextKind === 158 /* PropertySignature */ ||
  121091. contextKind === 156 /* Parameter */ ||
  121092. contextKind === 242 /* VariableDeclaration */ ||
  121093. ts.isFunctionLikeKind(contextKind);
  121094. }
  121095. function isConditionalOperatorContext(context) {
  121096. return context.contextNode.kind === 210 /* ConditionalExpression */ ||
  121097. context.contextNode.kind === 180 /* ConditionalType */;
  121098. }
  121099. function isSameLineTokenOrBeforeBlockContext(context) {
  121100. return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
  121101. }
  121102. function isBraceWrappedContext(context) {
  121103. return context.contextNode.kind === 189 /* ObjectBindingPattern */ ||
  121104. context.contextNode.kind === 186 /* MappedType */ ||
  121105. isSingleLineBlockContext(context);
  121106. }
  121107. // This check is done before an open brace in a control construct, a function, or a typescript block declaration
  121108. function isBeforeMultilineBlockContext(context) {
  121109. return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
  121110. }
  121111. function isMultilineBlockContext(context) {
  121112. return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
  121113. }
  121114. function isSingleLineBlockContext(context) {
  121115. return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
  121116. }
  121117. function isBlockContext(context) {
  121118. return nodeIsBlockContext(context.contextNode);
  121119. }
  121120. function isBeforeBlockContext(context) {
  121121. return nodeIsBlockContext(context.nextTokenParent);
  121122. }
  121123. // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children
  121124. function nodeIsBlockContext(node) {
  121125. if (nodeIsTypeScriptDeclWithBlockContext(node)) {
  121126. // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc).
  121127. return true;
  121128. }
  121129. switch (node.kind) {
  121130. case 223 /* Block */:
  121131. case 251 /* CaseBlock */:
  121132. case 193 /* ObjectLiteralExpression */:
  121133. case 250 /* ModuleBlock */:
  121134. return true;
  121135. }
  121136. return false;
  121137. }
  121138. function isFunctionDeclContext(context) {
  121139. switch (context.contextNode.kind) {
  121140. case 244 /* FunctionDeclaration */:
  121141. case 161 /* MethodDeclaration */:
  121142. case 160 /* MethodSignature */:
  121143. // case SyntaxKind.MemberFunctionDeclaration:
  121144. // falls through
  121145. case 163 /* GetAccessor */:
  121146. case 164 /* SetAccessor */:
  121147. // case SyntaxKind.MethodSignature:
  121148. // falls through
  121149. case 165 /* CallSignature */:
  121150. case 201 /* FunctionExpression */:
  121151. case 162 /* Constructor */:
  121152. case 202 /* ArrowFunction */:
  121153. // case SyntaxKind.ConstructorDeclaration:
  121154. // case SyntaxKind.SimpleArrowFunctionExpression:
  121155. // case SyntaxKind.ParenthesizedArrowFunctionExpression:
  121156. // falls through
  121157. case 246 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
  121158. return true;
  121159. }
  121160. return false;
  121161. }
  121162. function isNotFunctionDeclContext(context) {
  121163. return !isFunctionDeclContext(context);
  121164. }
  121165. function isFunctionDeclarationOrFunctionExpressionContext(context) {
  121166. return context.contextNode.kind === 244 /* FunctionDeclaration */ || context.contextNode.kind === 201 /* FunctionExpression */;
  121167. }
  121168. function isTypeScriptDeclWithBlockContext(context) {
  121169. return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
  121170. }
  121171. function nodeIsTypeScriptDeclWithBlockContext(node) {
  121172. switch (node.kind) {
  121173. case 245 /* ClassDeclaration */:
  121174. case 214 /* ClassExpression */:
  121175. case 246 /* InterfaceDeclaration */:
  121176. case 248 /* EnumDeclaration */:
  121177. case 173 /* TypeLiteral */:
  121178. case 249 /* ModuleDeclaration */:
  121179. case 260 /* ExportDeclaration */:
  121180. case 261 /* NamedExports */:
  121181. case 254 /* ImportDeclaration */:
  121182. case 257 /* NamedImports */:
  121183. return true;
  121184. }
  121185. return false;
  121186. }
  121187. function isAfterCodeBlockContext(context) {
  121188. switch (context.currentTokenParent.kind) {
  121189. case 245 /* ClassDeclaration */:
  121190. case 249 /* ModuleDeclaration */:
  121191. case 248 /* EnumDeclaration */:
  121192. case 280 /* CatchClause */:
  121193. case 250 /* ModuleBlock */:
  121194. case 237 /* SwitchStatement */:
  121195. return true;
  121196. case 223 /* Block */: {
  121197. var blockParent = context.currentTokenParent.parent;
  121198. // In a codefix scenario, we can't rely on parents being set. So just always return true.
  121199. if (!blockParent || blockParent.kind !== 202 /* ArrowFunction */ && blockParent.kind !== 201 /* FunctionExpression */) {
  121200. return true;
  121201. }
  121202. }
  121203. }
  121204. return false;
  121205. }
  121206. function isControlDeclContext(context) {
  121207. switch (context.contextNode.kind) {
  121208. case 227 /* IfStatement */:
  121209. case 237 /* SwitchStatement */:
  121210. case 230 /* ForStatement */:
  121211. case 231 /* ForInStatement */:
  121212. case 232 /* ForOfStatement */:
  121213. case 229 /* WhileStatement */:
  121214. case 240 /* TryStatement */:
  121215. case 228 /* DoStatement */:
  121216. case 236 /* WithStatement */:
  121217. // TODO
  121218. // case SyntaxKind.ElseClause:
  121219. // falls through
  121220. case 280 /* CatchClause */:
  121221. return true;
  121222. default:
  121223. return false;
  121224. }
  121225. }
  121226. function isObjectContext(context) {
  121227. return context.contextNode.kind === 193 /* ObjectLiteralExpression */;
  121228. }
  121229. function isFunctionCallContext(context) {
  121230. return context.contextNode.kind === 196 /* CallExpression */;
  121231. }
  121232. function isNewContext(context) {
  121233. return context.contextNode.kind === 197 /* NewExpression */;
  121234. }
  121235. function isFunctionCallOrNewContext(context) {
  121236. return isFunctionCallContext(context) || isNewContext(context);
  121237. }
  121238. function isPreviousTokenNotComma(context) {
  121239. return context.currentTokenSpan.kind !== 27 /* CommaToken */;
  121240. }
  121241. function isNextTokenNotCloseBracket(context) {
  121242. return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */;
  121243. }
  121244. function isArrowFunctionContext(context) {
  121245. return context.contextNode.kind === 202 /* ArrowFunction */;
  121246. }
  121247. function isImportTypeContext(context) {
  121248. return context.contextNode.kind === 188 /* ImportType */;
  121249. }
  121250. function isNonJsxSameLineTokenContext(context) {
  121251. return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */;
  121252. }
  121253. function isNonJsxElementOrFragmentContext(context) {
  121254. return context.contextNode.kind !== 266 /* JsxElement */ && context.contextNode.kind !== 270 /* JsxFragment */;
  121255. }
  121256. function isJsxExpressionContext(context) {
  121257. return context.contextNode.kind === 276 /* JsxExpression */ || context.contextNode.kind === 275 /* JsxSpreadAttribute */;
  121258. }
  121259. function isNextTokenParentJsxAttribute(context) {
  121260. return context.nextTokenParent.kind === 273 /* JsxAttribute */;
  121261. }
  121262. function isJsxAttributeContext(context) {
  121263. return context.contextNode.kind === 273 /* JsxAttribute */;
  121264. }
  121265. function isJsxSelfClosingElementContext(context) {
  121266. return context.contextNode.kind === 267 /* JsxSelfClosingElement */;
  121267. }
  121268. function isNotBeforeBlockInFunctionDeclarationContext(context) {
  121269. return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
  121270. }
  121271. function isEndOfDecoratorContextOnSameLine(context) {
  121272. return context.TokensAreOnSameLine() &&
  121273. !!context.contextNode.decorators &&
  121274. nodeIsInDecoratorContext(context.currentTokenParent) &&
  121275. !nodeIsInDecoratorContext(context.nextTokenParent);
  121276. }
  121277. function nodeIsInDecoratorContext(node) {
  121278. while (ts.isExpressionNode(node)) {
  121279. node = node.parent;
  121280. }
  121281. return node.kind === 157 /* Decorator */;
  121282. }
  121283. function isStartOfVariableDeclarationList(context) {
  121284. return context.currentTokenParent.kind === 243 /* VariableDeclarationList */ &&
  121285. context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
  121286. }
  121287. function isNotFormatOnEnter(context) {
  121288. return context.formattingRequestKind !== 2 /* FormatOnEnter */;
  121289. }
  121290. function isModuleDeclContext(context) {
  121291. return context.contextNode.kind === 249 /* ModuleDeclaration */;
  121292. }
  121293. function isObjectTypeContext(context) {
  121294. return context.contextNode.kind === 173 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
  121295. }
  121296. function isConstructorSignatureContext(context) {
  121297. return context.contextNode.kind === 166 /* ConstructSignature */;
  121298. }
  121299. function isTypeArgumentOrParameterOrAssertion(token, parent) {
  121300. if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) {
  121301. return false;
  121302. }
  121303. switch (parent.kind) {
  121304. case 169 /* TypeReference */:
  121305. case 199 /* TypeAssertionExpression */:
  121306. case 247 /* TypeAliasDeclaration */:
  121307. case 245 /* ClassDeclaration */:
  121308. case 214 /* ClassExpression */:
  121309. case 246 /* InterfaceDeclaration */:
  121310. case 244 /* FunctionDeclaration */:
  121311. case 201 /* FunctionExpression */:
  121312. case 202 /* ArrowFunction */:
  121313. case 161 /* MethodDeclaration */:
  121314. case 160 /* MethodSignature */:
  121315. case 165 /* CallSignature */:
  121316. case 166 /* ConstructSignature */:
  121317. case 196 /* CallExpression */:
  121318. case 197 /* NewExpression */:
  121319. case 216 /* ExpressionWithTypeArguments */:
  121320. return true;
  121321. default:
  121322. return false;
  121323. }
  121324. }
  121325. function isTypeArgumentOrParameterOrAssertionContext(context) {
  121326. return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) ||
  121327. isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
  121328. }
  121329. function isTypeAssertionContext(context) {
  121330. return context.contextNode.kind === 199 /* TypeAssertionExpression */;
  121331. }
  121332. function isVoidOpContext(context) {
  121333. return context.currentTokenSpan.kind === 110 /* VoidKeyword */ && context.currentTokenParent.kind === 205 /* VoidExpression */;
  121334. }
  121335. function isYieldOrYieldStarWithOperand(context) {
  121336. return context.contextNode.kind === 212 /* YieldExpression */ && context.contextNode.expression !== undefined;
  121337. }
  121338. function isNonNullAssertionContext(context) {
  121339. return context.contextNode.kind === 218 /* NonNullExpression */;
  121340. }
  121341. function isNotStatementConditionContext(context) {
  121342. return !isStatementConditionContext(context);
  121343. }
  121344. function isStatementConditionContext(context) {
  121345. switch (context.contextNode.kind) {
  121346. case 227 /* IfStatement */:
  121347. case 230 /* ForStatement */:
  121348. case 231 /* ForInStatement */:
  121349. case 232 /* ForOfStatement */:
  121350. case 228 /* DoStatement */:
  121351. case 229 /* WhileStatement */:
  121352. return true;
  121353. default:
  121354. return false;
  121355. }
  121356. }
  121357. function isSemicolonDeletionContext(context) {
  121358. var nextTokenKind = context.nextTokenSpan.kind;
  121359. var nextTokenStart = context.nextTokenSpan.pos;
  121360. if (ts.isTrivia(nextTokenKind)) {
  121361. var nextRealToken = context.nextTokenParent === context.currentTokenParent
  121362. ? ts.findNextToken(context.currentTokenParent, ts.findAncestor(context.currentTokenParent, function (a) { return !a.parent; }), context.sourceFile)
  121363. : context.nextTokenParent.getFirstToken(context.sourceFile);
  121364. if (!nextRealToken) {
  121365. return true;
  121366. }
  121367. nextTokenKind = nextRealToken.kind;
  121368. nextTokenStart = nextRealToken.getStart(context.sourceFile);
  121369. }
  121370. var startLine = context.sourceFile.getLineAndCharacterOfPosition(context.currentTokenSpan.pos).line;
  121371. var endLine = context.sourceFile.getLineAndCharacterOfPosition(nextTokenStart).line;
  121372. if (startLine === endLine) {
  121373. return nextTokenKind === 19 /* CloseBraceToken */
  121374. || nextTokenKind === 1 /* EndOfFileToken */;
  121375. }
  121376. if (nextTokenKind === 222 /* SemicolonClassElement */ ||
  121377. nextTokenKind === 26 /* SemicolonToken */) {
  121378. return false;
  121379. }
  121380. if (context.contextNode.kind === 246 /* InterfaceDeclaration */ ||
  121381. context.contextNode.kind === 247 /* TypeAliasDeclaration */) {
  121382. // Can’t remove semicolon after `foo`; it would parse as a method declaration:
  121383. //
  121384. // interface I {
  121385. // foo;
  121386. // (): void
  121387. // }
  121388. return !ts.isPropertySignature(context.currentTokenParent)
  121389. || !!context.currentTokenParent.type
  121390. || nextTokenKind !== 20 /* OpenParenToken */;
  121391. }
  121392. if (ts.isPropertyDeclaration(context.currentTokenParent)) {
  121393. return !context.currentTokenParent.initializer;
  121394. }
  121395. return context.currentTokenParent.kind !== 230 /* ForStatement */
  121396. && context.currentTokenParent.kind !== 224 /* EmptyStatement */
  121397. && context.currentTokenParent.kind !== 222 /* SemicolonClassElement */
  121398. && nextTokenKind !== 22 /* OpenBracketToken */
  121399. && nextTokenKind !== 20 /* OpenParenToken */
  121400. && nextTokenKind !== 39 /* PlusToken */
  121401. && nextTokenKind !== 40 /* MinusToken */
  121402. && nextTokenKind !== 43 /* SlashToken */
  121403. && nextTokenKind !== 13 /* RegularExpressionLiteral */
  121404. && nextTokenKind !== 27 /* CommaToken */
  121405. && nextTokenKind !== 211 /* TemplateExpression */
  121406. && nextTokenKind !== 15 /* TemplateHead */
  121407. && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */
  121408. && nextTokenKind !== 24 /* DotToken */;
  121409. }
  121410. function isSemicolonInsertionContext(context) {
  121411. return ts.positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile);
  121412. }
  121413. })(formatting = ts.formatting || (ts.formatting = {}));
  121414. })(ts || (ts = {}));
  121415. /* @internal */
  121416. var ts;
  121417. (function (ts) {
  121418. var formatting;
  121419. (function (formatting) {
  121420. function getFormatContext(options) {
  121421. return { options: options, getRules: getRulesMap() };
  121422. }
  121423. formatting.getFormatContext = getFormatContext;
  121424. var rulesMapCache;
  121425. function getRulesMap() {
  121426. if (rulesMapCache === undefined) {
  121427. rulesMapCache = createRulesMap(formatting.getAllRules());
  121428. }
  121429. return rulesMapCache;
  121430. }
  121431. /**
  121432. * For a given rule action, gets a mask of other rule actions that
  121433. * cannot be applied at the same position.
  121434. */
  121435. function getRuleActionExclusion(ruleAction) {
  121436. var mask = 0;
  121437. if (ruleAction & 1 /* StopProcessingSpaceActions */) {
  121438. mask |= 28 /* ModifySpaceAction */;
  121439. }
  121440. if (ruleAction & 2 /* StopProcessingTokenActions */) {
  121441. mask |= 96 /* ModifyTokenAction */;
  121442. }
  121443. if (ruleAction & 28 /* ModifySpaceAction */) {
  121444. mask |= 28 /* ModifySpaceAction */;
  121445. }
  121446. if (ruleAction & 96 /* ModifyTokenAction */) {
  121447. mask |= 96 /* ModifyTokenAction */;
  121448. }
  121449. return mask;
  121450. }
  121451. function createRulesMap(rules) {
  121452. var map = buildMap(rules);
  121453. return function (context) {
  121454. var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)];
  121455. if (bucket) {
  121456. var rules_1 = [];
  121457. var ruleActionMask = 0;
  121458. for (var _i = 0, bucket_1 = bucket; _i < bucket_1.length; _i++) {
  121459. var rule = bucket_1[_i];
  121460. var acceptRuleActions = ~getRuleActionExclusion(ruleActionMask);
  121461. if (rule.action & acceptRuleActions && ts.every(rule.context, function (c) { return c(context); })) {
  121462. rules_1.push(rule);
  121463. ruleActionMask |= rule.action;
  121464. }
  121465. }
  121466. if (rules_1.length) {
  121467. return rules_1;
  121468. }
  121469. }
  121470. };
  121471. }
  121472. function buildMap(rules) {
  121473. // Map from bucket index to array of rules
  121474. var map = new Array(mapRowLength * mapRowLength);
  121475. // This array is used only during construction of the rulesbucket in the map
  121476. var rulesBucketConstructionStateList = new Array(map.length);
  121477. for (var _i = 0, rules_2 = rules; _i < rules_2.length; _i++) {
  121478. var rule = rules_2[_i];
  121479. var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
  121480. for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
  121481. var left = _b[_a];
  121482. for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
  121483. var right = _d[_c];
  121484. var index = getRuleBucketIndex(left, right);
  121485. var rulesBucket = map[index];
  121486. if (rulesBucket === undefined) {
  121487. rulesBucket = map[index] = [];
  121488. }
  121489. addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
  121490. }
  121491. }
  121492. }
  121493. return map;
  121494. }
  121495. function getRuleBucketIndex(row, column) {
  121496. ts.Debug.assert(row <= 152 /* LastKeyword */ && column <= 152 /* LastKeyword */, "Must compute formatting context from tokens");
  121497. return (row * mapRowLength) + column;
  121498. }
  121499. var maskBitSize = 5;
  121500. var mask = 31; // MaskBitSize bits
  121501. var mapRowLength = 152 /* LastToken */ + 1;
  121502. var RulesPosition;
  121503. (function (RulesPosition) {
  121504. RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific";
  121505. RulesPosition[RulesPosition["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny";
  121506. RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific";
  121507. RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny";
  121508. RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific";
  121509. RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny";
  121510. })(RulesPosition || (RulesPosition = {}));
  121511. // The Rules list contains all the inserted rules into a rulebucket in the following order:
  121512. // 1- Ignore rules with specific token combination
  121513. // 2- Ignore rules with any token combination
  121514. // 3- Context rules with specific token combination
  121515. // 4- Context rules with any token combination
  121516. // 5- Non-context rules with specific token combination
  121517. // 6- Non-context rules with any token combination
  121518. //
  121519. // The member rulesInsertionIndexBitmap is used to describe the number of rules
  121520. // in each sub-bucket (above) hence can be used to know the index of where to insert
  121521. // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
  121522. //
  121523. // Example:
  121524. // In order to insert a rule to the end of sub-bucket (3), we get the index by adding
  121525. // the values in the bitmap segments 3rd, 2nd, and 1st.
  121526. function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) {
  121527. var position = rule.action & 3 /* StopAction */ ?
  121528. specificTokens ? RulesPosition.StopRulesSpecific : RulesPosition.StopRulesAny :
  121529. rule.context !== formatting.anyContext ?
  121530. specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny :
  121531. specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny;
  121532. var state = constructionState[rulesBucketIndex] || 0;
  121533. rules.splice(getInsertionIndex(state, position), 0, rule);
  121534. constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position);
  121535. }
  121536. function getInsertionIndex(indexBitmap, maskPosition) {
  121537. var index = 0;
  121538. for (var pos = 0; pos <= maskPosition; pos += maskBitSize) {
  121539. index += indexBitmap & mask;
  121540. indexBitmap >>= maskBitSize;
  121541. }
  121542. return index;
  121543. }
  121544. function increaseInsertionIndex(indexBitmap, maskPosition) {
  121545. var value = ((indexBitmap >> maskPosition) & mask) + 1;
  121546. ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
  121547. return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition);
  121548. }
  121549. })(formatting = ts.formatting || (ts.formatting = {}));
  121550. })(ts || (ts = {}));
  121551. /* @internal */
  121552. var ts;
  121553. (function (ts) {
  121554. var formatting;
  121555. (function (formatting) {
  121556. function createTextRangeWithKind(pos, end, kind) {
  121557. var textRangeWithKind = { pos: pos, end: end, kind: kind };
  121558. if (ts.Debug.isDebugging) {
  121559. Object.defineProperty(textRangeWithKind, "__debugKind", {
  121560. get: function () { return ts.Debug.formatSyntaxKind(kind); },
  121561. });
  121562. }
  121563. return textRangeWithKind;
  121564. }
  121565. formatting.createTextRangeWithKind = createTextRangeWithKind;
  121566. var Constants;
  121567. (function (Constants) {
  121568. Constants[Constants["Unknown"] = -1] = "Unknown";
  121569. })(Constants || (Constants = {}));
  121570. function formatOnEnter(position, sourceFile, formatContext) {
  121571. var line = sourceFile.getLineAndCharacterOfPosition(position).line;
  121572. if (line === 0) {
  121573. return [];
  121574. }
  121575. // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
  121576. // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
  121577. // trailing whitespaces. So the end of the formatting span should be the later one between:
  121578. // 1. the end of the previous line
  121579. // 2. the last non-whitespace character in the current line
  121580. var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile);
  121581. while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
  121582. endOfFormatSpan--;
  121583. }
  121584. // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to
  121585. // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
  121586. // previous character before the end of format span is line break character as well.
  121587. if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
  121588. endOfFormatSpan--;
  121589. }
  121590. var span = {
  121591. // get start position for the previous line
  121592. pos: ts.getStartPositionOfLine(line - 1, sourceFile),
  121593. // end value is exclusive so add 1 to the result
  121594. end: endOfFormatSpan + 1
  121595. };
  121596. return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */);
  121597. }
  121598. formatting.formatOnEnter = formatOnEnter;
  121599. function formatOnSemicolon(position, sourceFile, formatContext) {
  121600. var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile);
  121601. return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */);
  121602. }
  121603. formatting.formatOnSemicolon = formatOnSemicolon;
  121604. function formatOnOpeningCurly(position, sourceFile, formatContext) {
  121605. var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile);
  121606. if (!openingCurly) {
  121607. return [];
  121608. }
  121609. var curlyBraceRange = openingCurly.parent;
  121610. var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
  121611. /**
  121612. * We limit the span to end at the opening curly to handle the case where
  121613. * the brace matched to that just typed will be incorrect after further edits.
  121614. * For example, we could type the opening curly for the following method
  121615. * body without brace-matching activated:
  121616. * ```
  121617. * class C {
  121618. * foo()
  121619. * }
  121620. * ```
  121621. * and we wouldn't want to move the closing brace.
  121622. */
  121623. var textRange = {
  121624. pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile),
  121625. end: position
  121626. };
  121627. return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */);
  121628. }
  121629. formatting.formatOnOpeningCurly = formatOnOpeningCurly;
  121630. function formatOnClosingCurly(position, sourceFile, formatContext) {
  121631. var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile);
  121632. return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */);
  121633. }
  121634. formatting.formatOnClosingCurly = formatOnClosingCurly;
  121635. function formatDocument(sourceFile, formatContext) {
  121636. var span = {
  121637. pos: 0,
  121638. end: sourceFile.text.length
  121639. };
  121640. return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */);
  121641. }
  121642. formatting.formatDocument = formatDocument;
  121643. function formatSelection(start, end, sourceFile, formatContext) {
  121644. // format from the beginning of the line
  121645. var span = {
  121646. pos: ts.getLineStartPositionForPosition(start, sourceFile),
  121647. end: end,
  121648. };
  121649. return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */);
  121650. }
  121651. formatting.formatSelection = formatSelection;
  121652. /**
  121653. * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment).
  121654. * @param expectedTokenKind The kind of the last token constituting the desired parent node.
  121655. */
  121656. function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) {
  121657. var precedingToken = ts.findPrecedingToken(end, sourceFile);
  121658. return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ?
  121659. precedingToken :
  121660. undefined;
  121661. }
  121662. /**
  121663. * Finds the highest node enclosing `node` at the same list level as `node`
  121664. * and whose end does not exceed `node.end`.
  121665. *
  121666. * Consider typing the following
  121667. * ```
  121668. * let x = 1;
  121669. * while (true) {
  121670. * }
  121671. * ```
  121672. * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding
  121673. * variable declaration.
  121674. */
  121675. function findOutermostNodeWithinListLevel(node) {
  121676. var current = node;
  121677. while (current &&
  121678. current.parent &&
  121679. current.parent.end === node.end &&
  121680. !isListElement(current.parent, current)) {
  121681. current = current.parent;
  121682. }
  121683. return current;
  121684. }
  121685. // Returns true if node is a element in some list in parent
  121686. // i.e. parent is class declaration with the list of members and node is one of members.
  121687. function isListElement(parent, node) {
  121688. switch (parent.kind) {
  121689. case 245 /* ClassDeclaration */:
  121690. case 246 /* InterfaceDeclaration */:
  121691. return ts.rangeContainsRange(parent.members, node);
  121692. case 249 /* ModuleDeclaration */:
  121693. var body = parent.body;
  121694. return !!body && body.kind === 250 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
  121695. case 290 /* SourceFile */:
  121696. case 223 /* Block */:
  121697. case 250 /* ModuleBlock */:
  121698. return ts.rangeContainsRange(parent.statements, node);
  121699. case 280 /* CatchClause */:
  121700. return ts.rangeContainsRange(parent.block.statements, node);
  121701. }
  121702. return false;
  121703. }
  121704. /** find node that fully contains given text range */
  121705. function findEnclosingNode(range, sourceFile) {
  121706. return find(sourceFile);
  121707. function find(n) {
  121708. var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });
  121709. if (candidate) {
  121710. var result = find(candidate);
  121711. if (result) {
  121712. return result;
  121713. }
  121714. }
  121715. return n;
  121716. }
  121717. }
  121718. /** formatting is not applied to ranges that contain parse errors.
  121719. * This function will return a predicate that for a given text range will tell
  121720. * if there are any parse errors that overlap with the range.
  121721. */
  121722. function prepareRangeContainsErrorFunction(errors, originalRange) {
  121723. if (!errors.length) {
  121724. return rangeHasNoErrors;
  121725. }
  121726. // pick only errors that fall in range
  121727. var sorted = errors
  121728. .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217
  121729. .sort(function (e1, e2) { return e1.start - e2.start; });
  121730. if (!sorted.length) {
  121731. return rangeHasNoErrors;
  121732. }
  121733. var index = 0;
  121734. return function (r) {
  121735. // in current implementation sequence of arguments [r1, r2...] is monotonically increasing.
  121736. // 'index' tracks the index of the most recent error that was checked.
  121737. while (true) {
  121738. if (index >= sorted.length) {
  121739. // all errors in the range were already checked -> no error in specified range
  121740. return false;
  121741. }
  121742. var error = sorted[index];
  121743. if (r.end <= error.start) {
  121744. // specified range ends before the error referred by 'index' - no error in range
  121745. return false;
  121746. }
  121747. if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {
  121748. // specified range overlaps with error range
  121749. return true;
  121750. }
  121751. index++;
  121752. }
  121753. };
  121754. function rangeHasNoErrors() {
  121755. return false;
  121756. }
  121757. }
  121758. /**
  121759. * Start of the original range might fall inside the comment - scanner will not yield appropriate results
  121760. * This function will look for token that is located before the start of target range
  121761. * and return its end as start position for the scanner.
  121762. */
  121763. function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
  121764. var start = enclosingNode.getStart(sourceFile);
  121765. if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
  121766. return start;
  121767. }
  121768. var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile);
  121769. if (!precedingToken) {
  121770. // no preceding token found - start from the beginning of enclosing node
  121771. return enclosingNode.pos;
  121772. }
  121773. // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal)
  121774. // start from the beginning of enclosingNode to handle the entire 'originalRange'
  121775. if (precedingToken.end >= originalRange.pos) {
  121776. return enclosingNode.pos;
  121777. }
  121778. return precedingToken.end;
  121779. }
  121780. /*
  121781. * For cases like
  121782. * if (a ||
  121783. * b ||$
  121784. * c) {...}
  121785. * If we hit Enter at $ we want line ' b ||' to be indented.
  121786. * Formatting will be applied to the last two lines.
  121787. * Node that fully encloses these lines is binary expression 'a ||...'.
  121788. * Initial indentation for this node will be 0.
  121789. * Binary expressions don't introduce new indentation scopes, however it is possible
  121790. * that some parent node on the same line does - like if statement in this case.
  121791. * Note that we are considering parents only from the same line with initial node -
  121792. * if parent is on the different line - its delta was already contributed
  121793. * to the initial indentation.
  121794. */
  121795. function getOwnOrInheritedDelta(n, options, sourceFile) {
  121796. var previousLine = -1 /* Unknown */;
  121797. var child;
  121798. while (n) {
  121799. var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
  121800. if (previousLine !== -1 /* Unknown */ && line !== previousLine) {
  121801. break;
  121802. }
  121803. if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
  121804. return options.indentSize;
  121805. }
  121806. previousLine = line;
  121807. child = n;
  121808. n = n.parent;
  121809. }
  121810. return 0;
  121811. }
  121812. function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) {
  121813. var range = { pos: 0, end: sourceFileLike.text.length };
  121814. return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors
  121815. sourceFileLike); });
  121816. }
  121817. formatting.formatNodeGivenIndentation = formatNodeGivenIndentation;
  121818. function formatNodeLines(node, sourceFile, formatContext, requestKind) {
  121819. if (!node) {
  121820. return [];
  121821. }
  121822. var span = {
  121823. pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
  121824. end: node.end
  121825. };
  121826. return formatSpan(span, sourceFile, formatContext, requestKind);
  121827. }
  121828. function formatSpan(originalRange, sourceFile, formatContext, requestKind) {
  121829. // find the smallest node that fully wraps the range and compute the initial indentation for the node
  121830. var enclosingNode = findEnclosingNode(originalRange, sourceFile);
  121831. return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); });
  121832. }
  121833. function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) {
  121834. var options = _a.options, getRules = _a.getRules;
  121835. // formatting context is used by rules provider
  121836. var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options);
  121837. var previousRange;
  121838. var previousParent;
  121839. var previousRangeStartLine;
  121840. var lastIndentedLine;
  121841. var indentationOnLastIndentedLine = -1 /* Unknown */;
  121842. var edits = [];
  121843. formattingScanner.advance();
  121844. if (formattingScanner.isOnToken()) {
  121845. var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
  121846. var undecoratedStartLine = startLine;
  121847. if (enclosingNode.decorators) {
  121848. undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
  121849. }
  121850. processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
  121851. }
  121852. if (!formattingScanner.isOnToken()) {
  121853. var leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
  121854. if (leadingTrivia) {
  121855. indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); });
  121856. trimTrailingWhitespacesForRemainingRange();
  121857. }
  121858. }
  121859. return edits;
  121860. // local functions
  121861. /** Tries to compute the indentation for a list element.
  121862. * If list element is not in range then
  121863. * function will pick its actual indentation
  121864. * so it can be pushed downstream as inherited indentation.
  121865. * If list element is in the range - its indentation will be equal
  121866. * to inherited indentation from its predecessors.
  121867. */
  121868. function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
  121869. if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) ||
  121870. ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
  121871. if (inheritedIndentation !== -1 /* Unknown */) {
  121872. return inheritedIndentation;
  121873. }
  121874. }
  121875. else {
  121876. var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
  121877. var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile);
  121878. var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
  121879. if (startLine !== parentStartLine || startPos === column) {
  121880. // Use the base indent size if it is greater than
  121881. // the indentation of the inherited predecessor.
  121882. var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options);
  121883. return baseIndentSize > column ? baseIndentSize : column;
  121884. }
  121885. }
  121886. return -1 /* Unknown */;
  121887. }
  121888. function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
  121889. var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
  121890. if (effectiveParentStartLine === startLine) {
  121891. // if node is located on the same line with the parent
  121892. // - inherit indentation from the parent
  121893. // - push children if either parent of node itself has non-zero delta
  121894. return {
  121895. indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
  121896. delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta)
  121897. };
  121898. }
  121899. else if (inheritedIndentation === -1 /* Unknown */) {
  121900. if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) {
  121901. // the is used for chaining methods formatting
  121902. // - we need to get the indentation on last line and the delta of parent
  121903. return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
  121904. }
  121905. else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
  121906. return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
  121907. }
  121908. else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) {
  121909. return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
  121910. }
  121911. else {
  121912. return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta };
  121913. }
  121914. }
  121915. else {
  121916. return { indentation: inheritedIndentation, delta: delta };
  121917. }
  121918. }
  121919. function getFirstNonDecoratorTokenOfNode(node) {
  121920. if (node.modifiers && node.modifiers.length) {
  121921. return node.modifiers[0].kind;
  121922. }
  121923. switch (node.kind) {
  121924. case 245 /* ClassDeclaration */: return 80 /* ClassKeyword */;
  121925. case 246 /* InterfaceDeclaration */: return 114 /* InterfaceKeyword */;
  121926. case 244 /* FunctionDeclaration */: return 94 /* FunctionKeyword */;
  121927. case 248 /* EnumDeclaration */: return 248 /* EnumDeclaration */;
  121928. case 163 /* GetAccessor */: return 131 /* GetKeyword */;
  121929. case 164 /* SetAccessor */: return 142 /* SetKeyword */;
  121930. case 161 /* MethodDeclaration */:
  121931. if (node.asteriskToken) {
  121932. return 41 /* AsteriskToken */;
  121933. }
  121934. // falls through
  121935. case 159 /* PropertyDeclaration */:
  121936. case 156 /* Parameter */:
  121937. var name = ts.getNameOfDeclaration(node);
  121938. if (name) {
  121939. return name.kind;
  121940. }
  121941. }
  121942. }
  121943. function getDynamicIndentation(node, nodeStartLine, indentation, delta) {
  121944. return {
  121945. getIndentationForComment: function (kind, tokenIndentation, container) {
  121946. switch (kind) {
  121947. // preceding comment to the token that closes the indentation scope inherits the indentation from the scope
  121948. // .. {
  121949. // // comment
  121950. // }
  121951. case 19 /* CloseBraceToken */:
  121952. case 23 /* CloseBracketToken */:
  121953. case 21 /* CloseParenToken */:
  121954. return indentation + getDelta(container);
  121955. }
  121956. return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation;
  121957. },
  121958. // if list end token is LessThanToken '>' then its delta should be explicitly suppressed
  121959. // so that LessThanToken as a binary operator can still be indented.
  121960. // foo.then
  121961. // <
  121962. // number,
  121963. // string,
  121964. // >();
  121965. // vs
  121966. // var a = xValue
  121967. // > yValue;
  121968. getIndentationForToken: function (line, kind, container, suppressDelta) {
  121969. return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation;
  121970. },
  121971. getIndentation: function () { return indentation; },
  121972. getDelta: getDelta,
  121973. recomputeIndentation: function (lineAdded) {
  121974. if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) {
  121975. indentation += lineAdded ? options.indentSize : -options.indentSize;
  121976. delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
  121977. }
  121978. }
  121979. };
  121980. function shouldAddDelta(line, kind, container) {
  121981. switch (kind) {
  121982. // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
  121983. case 18 /* OpenBraceToken */:
  121984. case 19 /* CloseBraceToken */:
  121985. case 21 /* CloseParenToken */:
  121986. case 87 /* ElseKeyword */:
  121987. case 111 /* WhileKeyword */:
  121988. case 59 /* AtToken */:
  121989. return false;
  121990. case 43 /* SlashToken */:
  121991. case 31 /* GreaterThanToken */:
  121992. switch (container.kind) {
  121993. case 268 /* JsxOpeningElement */:
  121994. case 269 /* JsxClosingElement */:
  121995. case 267 /* JsxSelfClosingElement */:
  121996. return false;
  121997. }
  121998. break;
  121999. case 22 /* OpenBracketToken */:
  122000. case 23 /* CloseBracketToken */:
  122001. if (container.kind !== 186 /* MappedType */) {
  122002. return false;
  122003. }
  122004. break;
  122005. }
  122006. // if token line equals to the line of containing node (this is a first token in the node) - use node indentation
  122007. return nodeStartLine !== line
  122008. // if this token is the first token following the list of decorators, we do not need to indent
  122009. && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node));
  122010. }
  122011. function getDelta(child) {
  122012. // Delta value should be zero when the node explicitly prevents indentation of the child node
  122013. return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0;
  122014. }
  122015. }
  122016. function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) {
  122017. if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
  122018. return;
  122019. }
  122020. var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
  122021. // a useful observations when tracking context node
  122022. // /
  122023. // [a]
  122024. // / | \
  122025. // [b] [c] [d]
  122026. // node 'a' is a context node for nodes 'b', 'c', 'd'
  122027. // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
  122028. // this rule can be applied recursively to child nodes of 'a'.
  122029. //
  122030. // context node is set to parent node value after processing every child node
  122031. // context node is set to parent of the token after processing every token
  122032. var childContextNode = contextNode;
  122033. // if there are any tokens that logically belong to node and interleave child nodes
  122034. // such tokens will be consumed in processChildNode for the child that follows them
  122035. ts.forEachChild(node, function (child) {
  122036. processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
  122037. }, function (nodes) {
  122038. processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
  122039. });
  122040. // proceed any tokens in the node that are located after child nodes
  122041. while (formattingScanner.isOnToken()) {
  122042. var tokenInfo = formattingScanner.readTokenInfo(node);
  122043. if (tokenInfo.token.end > node.end) {
  122044. break;
  122045. }
  122046. if (node.kind === 11 /* JsxText */) {
  122047. // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here
  122048. formattingScanner.advance();
  122049. continue;
  122050. }
  122051. consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
  122052. }
  122053. if (!node.parent && formattingScanner.isOnEOF()) {
  122054. var token = formattingScanner.readEOFTokenRange();
  122055. if (token.end <= node.end && previousRange) {
  122056. processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, node, previousRange, previousRangeStartLine, previousParent, contextNode, nodeDynamicIndentation);
  122057. }
  122058. }
  122059. function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
  122060. var childStartPos = child.getStart(sourceFile);
  122061. var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
  122062. var undecoratedChildStartLine = childStartLine;
  122063. if (child.decorators) {
  122064. undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
  122065. }
  122066. // if child is a list item - try to get its indentation, only if parent is within the original range.
  122067. var childIndentationAmount = -1 /* Unknown */;
  122068. if (isListItem && ts.rangeContainsRange(originalRange, parent)) {
  122069. childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
  122070. if (childIndentationAmount !== -1 /* Unknown */) {
  122071. inheritedIndentation = childIndentationAmount;
  122072. }
  122073. }
  122074. // child node is outside the target range - do not dive inside
  122075. if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
  122076. if (child.end < originalRange.pos) {
  122077. formattingScanner.skipToEndOf(child);
  122078. }
  122079. return inheritedIndentation;
  122080. }
  122081. if (child.getFullWidth() === 0) {
  122082. return inheritedIndentation;
  122083. }
  122084. while (formattingScanner.isOnToken()) {
  122085. // proceed any parent tokens that are located prior to child.getStart()
  122086. var tokenInfo = formattingScanner.readTokenInfo(node);
  122087. if (tokenInfo.token.end > childStartPos) {
  122088. // stop when formatting scanner advances past the beginning of the child
  122089. break;
  122090. }
  122091. consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
  122092. }
  122093. if (!formattingScanner.isOnToken()) {
  122094. return inheritedIndentation;
  122095. }
  122096. // JSX text shouldn't affect indenting
  122097. if (ts.isToken(child) && child.kind !== 11 /* JsxText */) {
  122098. // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
  122099. var tokenInfo = formattingScanner.readTokenInfo(child);
  122100. ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
  122101. consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
  122102. return inheritedIndentation;
  122103. }
  122104. var effectiveParentStartLine = child.kind === 157 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
  122105. var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
  122106. processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
  122107. if (child.kind === 11 /* JsxText */) {
  122108. var range = { pos: child.getStart(), end: child.getEnd() };
  122109. if (range.pos !== range.end) { // don't indent zero-width jsx text
  122110. var siblings = parent.getChildren(sourceFile);
  122111. var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; });
  122112. var previousNode = siblings[currentIndex - 1];
  122113. if (previousNode) {
  122114. // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on
  122115. if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) {
  122116. // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on
  122117. var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line;
  122118. indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true);
  122119. }
  122120. }
  122121. }
  122122. }
  122123. childContextNode = node;
  122124. if (isFirstListItem && parent.kind === 192 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
  122125. inheritedIndentation = childIndentation.indentation;
  122126. }
  122127. return inheritedIndentation;
  122128. }
  122129. function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) {
  122130. ts.Debug.assert(ts.isNodeArray(nodes));
  122131. var listStartToken = getOpenTokenForList(parent, nodes);
  122132. var listDynamicIndentation = parentDynamicIndentation;
  122133. var startLine = parentStartLine;
  122134. if (listStartToken !== 0 /* Unknown */) {
  122135. // introduce a new indentation scope for lists (including list start and end tokens)
  122136. while (formattingScanner.isOnToken()) {
  122137. var tokenInfo = formattingScanner.readTokenInfo(parent);
  122138. if (tokenInfo.token.end > nodes.pos) {
  122139. // stop when formatting scanner moves past the beginning of node list
  122140. break;
  122141. }
  122142. else if (tokenInfo.token.kind === listStartToken) {
  122143. // consume list start token
  122144. startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
  122145. consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
  122146. var indentationOnListStartToken = void 0;
  122147. if (indentationOnLastIndentedLine !== -1 /* Unknown */) {
  122148. // scanner just processed list start token so consider last indentation as list indentation
  122149. // function foo(): { // last indentation was 0, list item will be indented based on this value
  122150. // foo: number;
  122151. // }: {};
  122152. indentationOnListStartToken = indentationOnLastIndentedLine;
  122153. }
  122154. else {
  122155. var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile);
  122156. indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options);
  122157. }
  122158. listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217
  122159. }
  122160. else {
  122161. // consume any tokens that precede the list as child elements of 'node' using its indentation scope
  122162. consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
  122163. }
  122164. }
  122165. }
  122166. var inheritedIndentation = -1 /* Unknown */;
  122167. for (var i = 0; i < nodes.length; i++) {
  122168. var child = nodes[i];
  122169. inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0);
  122170. }
  122171. var listEndToken = getCloseTokenForOpenToken(listStartToken);
  122172. if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) {
  122173. var tokenInfo = formattingScanner.readTokenInfo(parent);
  122174. if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) {
  122175. formattingScanner.advance();
  122176. tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined;
  122177. }
  122178. // consume the list end token only if it is still belong to the parent
  122179. // there might be the case when current token matches end token but does not considered as one
  122180. // function (x: function) <--
  122181. // without this check close paren will be interpreted as list end token for function expression which is wrong
  122182. if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) {
  122183. // consume list end token
  122184. consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true);
  122185. }
  122186. }
  122187. }
  122188. function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) {
  122189. ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token));
  122190. var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
  122191. var indentToken = false;
  122192. if (currentTokenInfo.leadingTrivia) {
  122193. processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation);
  122194. }
  122195. var lineAction = 0 /* None */;
  122196. var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token);
  122197. var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
  122198. if (isTokenInRange) {
  122199. var rangeHasError = rangeContainsError(currentTokenInfo.token);
  122200. // save previousRange since processRange will overwrite this value with current one
  122201. var savePreviousRange = previousRange;
  122202. lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation);
  122203. // do not indent comments\token if token range overlaps with some error
  122204. if (!rangeHasError) {
  122205. if (lineAction === 0 /* None */) {
  122206. // indent token only if end line of previous range does not match start line of the token
  122207. var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
  122208. indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
  122209. }
  122210. else {
  122211. indentToken = lineAction === 1 /* LineAdded */;
  122212. }
  122213. }
  122214. }
  122215. if (currentTokenInfo.trailingTrivia) {
  122216. processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation);
  122217. }
  122218. if (indentToken) {
  122219. var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
  122220. dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) :
  122221. -1 /* Unknown */;
  122222. var indentNextTokenOrTrivia = true;
  122223. if (currentTokenInfo.leadingTrivia) {
  122224. var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
  122225. indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); });
  122226. }
  122227. // indent token only if is it is in target range and does not overlap with any error ranges
  122228. if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) {
  122229. insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */);
  122230. lastIndentedLine = tokenStart.line;
  122231. indentationOnLastIndentedLine = tokenIndentation;
  122232. }
  122233. }
  122234. formattingScanner.advance();
  122235. childContextNode = parent;
  122236. }
  122237. }
  122238. function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) {
  122239. for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) {
  122240. var triviaItem = trivia_1[_i];
  122241. var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem);
  122242. switch (triviaItem.kind) {
  122243. case 3 /* MultiLineCommentTrivia */:
  122244. if (triviaInRange) {
  122245. indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
  122246. }
  122247. indentNextTokenOrTrivia = false;
  122248. break;
  122249. case 2 /* SingleLineCommentTrivia */:
  122250. if (indentNextTokenOrTrivia && triviaInRange) {
  122251. indentSingleLine(triviaItem);
  122252. }
  122253. indentNextTokenOrTrivia = false;
  122254. break;
  122255. case 4 /* NewLineTrivia */:
  122256. indentNextTokenOrTrivia = true;
  122257. break;
  122258. }
  122259. }
  122260. return indentNextTokenOrTrivia;
  122261. }
  122262. function processTrivia(trivia, parent, contextNode, dynamicIndentation) {
  122263. for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) {
  122264. var triviaItem = trivia_2[_i];
  122265. if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) {
  122266. var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
  122267. processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation);
  122268. }
  122269. }
  122270. }
  122271. function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) {
  122272. var rangeHasError = rangeContainsError(range);
  122273. var lineAction = 0 /* None */;
  122274. if (!rangeHasError) {
  122275. if (!previousRange) {
  122276. // trim whitespaces starting from the beginning of the span up to the current line
  122277. var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
  122278. trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
  122279. }
  122280. else {
  122281. lineAction =
  122282. processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
  122283. }
  122284. }
  122285. previousRange = range;
  122286. previousParent = parent;
  122287. previousRangeStartLine = rangeStart.line;
  122288. return lineAction;
  122289. }
  122290. function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) {
  122291. formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode);
  122292. var rules = getRules(formattingContext);
  122293. var trimTrailingWhitespaces = false;
  122294. var lineAction = 0 /* None */;
  122295. if (rules) {
  122296. // Apply rules in reverse order so that higher priority rules (which are first in the array)
  122297. // win in a conflict with lower priority rules.
  122298. ts.forEachRight(rules, function (rule) {
  122299. lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine);
  122300. switch (lineAction) {
  122301. case 2 /* LineRemoved */:
  122302. // Handle the case where the next line is moved to be the end of this line.
  122303. // In this case we don't indent the next line in the next pass.
  122304. if (currentParent.getStart(sourceFile) === currentItem.pos) {
  122305. dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false);
  122306. }
  122307. break;
  122308. case 1 /* LineAdded */:
  122309. // Handle the case where token2 is moved to the new line.
  122310. // In this case we indent token2 in the next pass but we set
  122311. // sameLineIndent flag to notify the indenter that the indentation is within the line.
  122312. if (currentParent.getStart(sourceFile) === currentItem.pos) {
  122313. dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true);
  122314. }
  122315. break;
  122316. default:
  122317. ts.Debug.assert(lineAction === 0 /* None */);
  122318. }
  122319. // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
  122320. trimTrailingWhitespaces = !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */;
  122321. });
  122322. }
  122323. else {
  122324. trimTrailingWhitespaces = currentItem.kind !== 1 /* EndOfFileToken */;
  122325. }
  122326. if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) {
  122327. // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
  122328. trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem);
  122329. }
  122330. return lineAction;
  122331. }
  122332. function insertIndentation(pos, indentation, lineAdded) {
  122333. var indentationString = getIndentationString(indentation, options);
  122334. if (lineAdded) {
  122335. // new line is added before the token by the formatting rules
  122336. // insert indentation string at the very beginning of the token
  122337. recordReplace(pos, 0, indentationString);
  122338. }
  122339. else {
  122340. var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
  122341. var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile);
  122342. if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
  122343. recordReplace(startLinePosition, tokenStart.character, indentationString);
  122344. }
  122345. }
  122346. }
  122347. function characterToColumn(startLinePosition, characterInLine) {
  122348. var column = 0;
  122349. for (var i = 0; i < characterInLine; i++) {
  122350. if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) {
  122351. column += options.tabSize - column % options.tabSize;
  122352. }
  122353. else {
  122354. column++;
  122355. }
  122356. }
  122357. return column;
  122358. }
  122359. function indentationIsDifferent(indentationString, startLinePosition) {
  122360. return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length);
  122361. }
  122362. function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) {
  122363. if (indentFinalLine === void 0) { indentFinalLine = true; }
  122364. // split comment in lines
  122365. var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
  122366. var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
  122367. if (startLine === endLine) {
  122368. if (!firstLineIsIndented) {
  122369. // treat as single line comment
  122370. insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false);
  122371. }
  122372. return;
  122373. }
  122374. var parts = [];
  122375. var startPos = commentRange.pos;
  122376. for (var line = startLine; line < endLine; line++) {
  122377. var endOfLine = ts.getEndLinePosition(line, sourceFile);
  122378. parts.push({ pos: startPos, end: endOfLine });
  122379. startPos = ts.getStartPositionOfLine(line + 1, sourceFile);
  122380. }
  122381. if (indentFinalLine) {
  122382. parts.push({ pos: startPos, end: commentRange.end });
  122383. }
  122384. if (parts.length === 0)
  122385. return;
  122386. var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile);
  122387. var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
  122388. if (indentation === nonWhitespaceColumnInFirstPart.column && !jsxTextStyleIndent) {
  122389. return;
  122390. }
  122391. var startIndex = 0;
  122392. if (firstLineIsIndented) {
  122393. startIndex = 1;
  122394. startLine++;
  122395. }
  122396. // shift all parts on the delta size
  122397. var delta = indentation - nonWhitespaceColumnInFirstPart.column;
  122398. for (var i = startIndex; i < parts.length; i++, startLine++) {
  122399. var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile);
  122400. var nonWhitespaceCharacterAndColumn = i === 0
  122401. ? nonWhitespaceColumnInFirstPart
  122402. : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
  122403. if (jsxTextStyleIndent) {
  122404. // skip adding indentation to blank lines
  122405. if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile))))
  122406. continue;
  122407. // reset delta on every line
  122408. delta = indentation - nonWhitespaceCharacterAndColumn.column;
  122409. }
  122410. var newIndentation = nonWhitespaceCharacterAndColumn.column + delta;
  122411. if (newIndentation > 0) {
  122412. var indentationString = getIndentationString(newIndentation, options);
  122413. recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString);
  122414. }
  122415. else {
  122416. recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character);
  122417. }
  122418. }
  122419. }
  122420. function trimTrailingWhitespacesForLines(line1, line2, range) {
  122421. for (var line = line1; line < line2; line++) {
  122422. var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile);
  122423. var lineEndPosition = ts.getEndLinePosition(line, sourceFile);
  122424. // do not trim whitespaces in comments or template expression
  122425. if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
  122426. continue;
  122427. }
  122428. var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
  122429. if (whitespaceStart !== -1) {
  122430. ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1)));
  122431. recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
  122432. }
  122433. }
  122434. }
  122435. /**
  122436. * @param start The position of the first character in range
  122437. * @param end The position of the last character in range
  122438. */
  122439. function getTrailingWhitespaceStartPosition(start, end) {
  122440. var pos = end;
  122441. while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) {
  122442. pos--;
  122443. }
  122444. if (pos !== end) {
  122445. return pos + 1;
  122446. }
  122447. return -1;
  122448. }
  122449. /**
  122450. * Trimming will be done for lines after the previous range
  122451. */
  122452. function trimTrailingWhitespacesForRemainingRange() {
  122453. var startPosition = previousRange ? previousRange.end : originalRange.pos;
  122454. var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
  122455. var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
  122456. trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange);
  122457. }
  122458. function recordDelete(start, len) {
  122459. if (len) {
  122460. edits.push(ts.createTextChangeFromStartLength(start, len, ""));
  122461. }
  122462. }
  122463. function recordReplace(start, len, newText) {
  122464. if (len || newText) {
  122465. edits.push(ts.createTextChangeFromStartLength(start, len, newText));
  122466. }
  122467. }
  122468. function recordInsert(start, text) {
  122469. if (text) {
  122470. edits.push(ts.createTextChangeFromStartLength(start, 0, text));
  122471. }
  122472. }
  122473. function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) {
  122474. var onLaterLine = currentStartLine !== previousStartLine;
  122475. switch (rule.action) {
  122476. case 1 /* StopProcessingSpaceActions */:
  122477. // no action required
  122478. return 0 /* None */;
  122479. case 16 /* DeleteSpace */:
  122480. if (previousRange.end !== currentRange.pos) {
  122481. // delete characters starting from t1.end up to t2.pos exclusive
  122482. recordDelete(previousRange.end, currentRange.pos - previousRange.end);
  122483. return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
  122484. }
  122485. break;
  122486. case 32 /* DeleteToken */:
  122487. recordDelete(previousRange.pos, previousRange.end - previousRange.pos);
  122488. break;
  122489. case 8 /* InsertNewLine */:
  122490. // exit early if we on different lines and rule cannot change number of newlines
  122491. // if line1 and line2 are on subsequent lines then no edits are required - ok to exit
  122492. // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines
  122493. if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
  122494. return 0 /* None */;
  122495. }
  122496. // edit should not be applied if we have one line feed between elements
  122497. var lineDelta = currentStartLine - previousStartLine;
  122498. if (lineDelta !== 1) {
  122499. recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter);
  122500. return onLaterLine ? 0 /* None */ : 1 /* LineAdded */;
  122501. }
  122502. break;
  122503. case 4 /* InsertSpace */:
  122504. // exit early if we on different lines and rule cannot change number of newlines
  122505. if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
  122506. return 0 /* None */;
  122507. }
  122508. var posDelta = currentRange.pos - previousRange.end;
  122509. if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) {
  122510. recordReplace(previousRange.end, currentRange.pos - previousRange.end, " ");
  122511. return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
  122512. }
  122513. break;
  122514. case 64 /* InsertTrailingSemicolon */:
  122515. recordInsert(previousRange.end, ";");
  122516. }
  122517. return 0 /* None */;
  122518. }
  122519. }
  122520. var LineAction;
  122521. (function (LineAction) {
  122522. LineAction[LineAction["None"] = 0] = "None";
  122523. LineAction[LineAction["LineAdded"] = 1] = "LineAdded";
  122524. LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved";
  122525. })(LineAction || (LineAction = {}));
  122526. /**
  122527. * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`.
  122528. */
  122529. function getRangeOfEnclosingComment(sourceFile, position, precedingToken, tokenAtPosition) {
  122530. if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); }
  122531. var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc);
  122532. if (jsdoc)
  122533. tokenAtPosition = jsdoc.parent;
  122534. var tokenStart = tokenAtPosition.getStart(sourceFile);
  122535. if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
  122536. return undefined;
  122537. }
  122538. // eslint-disable-next-line no-null/no-null
  122539. precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken;
  122540. // Between two consecutive tokens, all comments are either trailing on the former
  122541. // or leading on the latter (and none are in both lists).
  122542. var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end);
  122543. var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
  122544. var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
  122545. return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) ||
  122546. // The end marker of a single-line comment does not include the newline character.
  122547. // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
  122548. //
  122549. // // asdf ^\n
  122550. //
  122551. // But for closed multi-line comments, we don't want to be inside the comment in the following case:
  122552. //
  122553. // /* asdf */^
  122554. //
  122555. // However, unterminated multi-line comments *do* contain their end.
  122556. //
  122557. // Internally, we represent the end of the comment at the newline and closing '/', respectively.
  122558. //
  122559. position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); });
  122560. }
  122561. formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment;
  122562. function getOpenTokenForList(node, list) {
  122563. switch (node.kind) {
  122564. case 162 /* Constructor */:
  122565. case 244 /* FunctionDeclaration */:
  122566. case 201 /* FunctionExpression */:
  122567. case 161 /* MethodDeclaration */:
  122568. case 160 /* MethodSignature */:
  122569. case 202 /* ArrowFunction */:
  122570. if (node.typeParameters === list) {
  122571. return 29 /* LessThanToken */;
  122572. }
  122573. else if (node.parameters === list) {
  122574. return 20 /* OpenParenToken */;
  122575. }
  122576. break;
  122577. case 196 /* CallExpression */:
  122578. case 197 /* NewExpression */:
  122579. if (node.typeArguments === list) {
  122580. return 29 /* LessThanToken */;
  122581. }
  122582. else if (node.arguments === list) {
  122583. return 20 /* OpenParenToken */;
  122584. }
  122585. break;
  122586. case 169 /* TypeReference */:
  122587. if (node.typeArguments === list) {
  122588. return 29 /* LessThanToken */;
  122589. }
  122590. break;
  122591. case 173 /* TypeLiteral */:
  122592. return 18 /* OpenBraceToken */;
  122593. }
  122594. return 0 /* Unknown */;
  122595. }
  122596. function getCloseTokenForOpenToken(kind) {
  122597. switch (kind) {
  122598. case 20 /* OpenParenToken */:
  122599. return 21 /* CloseParenToken */;
  122600. case 29 /* LessThanToken */:
  122601. return 31 /* GreaterThanToken */;
  122602. case 18 /* OpenBraceToken */:
  122603. return 19 /* CloseBraceToken */;
  122604. }
  122605. return 0 /* Unknown */;
  122606. }
  122607. var internedSizes;
  122608. var internedTabsIndentation;
  122609. var internedSpacesIndentation;
  122610. function getIndentationString(indentation, options) {
  122611. // reset interned strings if FormatCodeOptions were changed
  122612. var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
  122613. if (resetInternedStrings) {
  122614. internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
  122615. internedTabsIndentation = internedSpacesIndentation = undefined;
  122616. }
  122617. if (!options.convertTabsToSpaces) {
  122618. var tabs = Math.floor(indentation / options.tabSize);
  122619. var spaces = indentation - tabs * options.tabSize;
  122620. var tabString = void 0;
  122621. if (!internedTabsIndentation) {
  122622. internedTabsIndentation = [];
  122623. }
  122624. if (internedTabsIndentation[tabs] === undefined) {
  122625. internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs);
  122626. }
  122627. else {
  122628. tabString = internedTabsIndentation[tabs];
  122629. }
  122630. return spaces ? tabString + ts.repeatString(" ", spaces) : tabString;
  122631. }
  122632. else {
  122633. var spacesString = void 0;
  122634. var quotient = Math.floor(indentation / options.indentSize);
  122635. var remainder = indentation % options.indentSize;
  122636. if (!internedSpacesIndentation) {
  122637. internedSpacesIndentation = [];
  122638. }
  122639. if (internedSpacesIndentation[quotient] === undefined) {
  122640. spacesString = ts.repeatString(" ", options.indentSize * quotient);
  122641. internedSpacesIndentation[quotient] = spacesString;
  122642. }
  122643. else {
  122644. spacesString = internedSpacesIndentation[quotient];
  122645. }
  122646. return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString;
  122647. }
  122648. }
  122649. formatting.getIndentationString = getIndentationString;
  122650. })(formatting = ts.formatting || (ts.formatting = {}));
  122651. })(ts || (ts = {}));
  122652. /* @internal */
  122653. var ts;
  122654. (function (ts) {
  122655. var formatting;
  122656. (function (formatting) {
  122657. var SmartIndenter;
  122658. (function (SmartIndenter) {
  122659. var Value;
  122660. (function (Value) {
  122661. Value[Value["Unknown"] = -1] = "Unknown";
  122662. })(Value || (Value = {}));
  122663. /**
  122664. * @param assumeNewLineBeforeCloseBrace
  122665. * `false` when called on text from a real source file.
  122666. * `true` when we need to assume `position` is on a newline.
  122667. *
  122668. * This is useful for codefixes. Consider
  122669. * ```
  122670. * function f() {
  122671. * |}
  122672. * ```
  122673. * with `position` at `|`.
  122674. *
  122675. * When inserting some text after an open brace, we would like to get indentation as if a newline was already there.
  122676. * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior.
  122677. */
  122678. function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) {
  122679. if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; }
  122680. if (position > sourceFile.text.length) {
  122681. return getBaseIndentation(options); // past EOF
  122682. }
  122683. // no indentation when the indent style is set to none,
  122684. // so we can return fast
  122685. if (options.indentStyle === ts.IndentStyle.None) {
  122686. return 0;
  122687. }
  122688. var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true);
  122689. // eslint-disable-next-line no-null/no-null
  122690. var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null);
  122691. if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
  122692. return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
  122693. }
  122694. if (!precedingToken) {
  122695. return getBaseIndentation(options);
  122696. }
  122697. // no indentation in string \regex\template literals
  122698. var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
  122699. if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) {
  122700. return 0;
  122701. }
  122702. var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
  122703. // indentation is first non-whitespace character in a previous line
  122704. // for block indentation, we should look for a line which contains something that's not
  122705. // whitespace.
  122706. if (options.indentStyle === ts.IndentStyle.Block) {
  122707. return getBlockIndent(sourceFile, position, options);
  122708. }
  122709. if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 209 /* BinaryExpression */) {
  122710. // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
  122711. var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
  122712. if (actualIndentation !== -1 /* Unknown */) {
  122713. return actualIndentation;
  122714. }
  122715. }
  122716. var containerList = getListByPosition(position, precedingToken.parent, sourceFile);
  122717. // use list position if the preceding token is before any list items
  122718. if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) {
  122719. return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217
  122720. }
  122721. return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options);
  122722. }
  122723. SmartIndenter.getIndentation = getIndentation;
  122724. function getCommentIndent(sourceFile, position, options, enclosingCommentRange) {
  122725. var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1;
  122726. var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line;
  122727. ts.Debug.assert(commentStartLine >= 0);
  122728. if (previousLine <= commentStartLine) {
  122729. return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options);
  122730. }
  122731. var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile);
  122732. var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character;
  122733. if (column === 0) {
  122734. return column;
  122735. }
  122736. var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character);
  122737. return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column;
  122738. }
  122739. function getBlockIndent(sourceFile, position, options) {
  122740. // move backwards until we find a line with a non-whitespace character,
  122741. // then find the first non-whitespace character for that line.
  122742. var current = position;
  122743. while (current > 0) {
  122744. var char = sourceFile.text.charCodeAt(current);
  122745. if (!ts.isWhiteSpaceLike(char)) {
  122746. break;
  122747. }
  122748. current--;
  122749. }
  122750. var lineStart = ts.getLineStartPositionForPosition(current, sourceFile);
  122751. return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
  122752. }
  122753. function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) {
  122754. // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken'
  122755. // if such node is found - compute initial indentation for 'position' inside this node
  122756. var previous;
  122757. var current = precedingToken;
  122758. while (current) {
  122759. if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) {
  122760. var currentStart = getStartLineAndCharacterForNode(current, sourceFile);
  122761. var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
  122762. var indentationDelta = nextTokenKind !== 0 /* Unknown */
  122763. // handle cases when codefix is about to be inserted before the close brace
  122764. ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0
  122765. : lineAtPosition !== currentStart.line ? options.indentSize : 0;
  122766. return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217
  122767. }
  122768. // check if current node is a list item - if yes, take indentation from it
  122769. // do not consider parent-child line sharing yet:
  122770. // function foo(a
  122771. // | preceding node 'a' does share line with its parent but indentation is expected
  122772. var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true);
  122773. if (actualIndentation !== -1 /* Unknown */) {
  122774. return actualIndentation;
  122775. }
  122776. previous = current;
  122777. current = current.parent;
  122778. }
  122779. // no parent was found - return the base indentation of the SourceFile
  122780. return getBaseIndentation(options);
  122781. }
  122782. function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
  122783. var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
  122784. return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options);
  122785. }
  122786. SmartIndenter.getIndentationForNode = getIndentationForNode;
  122787. function getBaseIndentation(options) {
  122788. return options.baseIndentSize || 0;
  122789. }
  122790. SmartIndenter.getBaseIndentation = getBaseIndentation;
  122791. function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
  122792. var parent = current.parent;
  122793. // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if
  122794. // * parent and child nodes start on the same line, or
  122795. // * parent is an IfStatement and child starts on the same line as an 'else clause'.
  122796. while (parent) {
  122797. var useActualIndentation = true;
  122798. if (ignoreActualIndentationRange) {
  122799. var start = current.getStart(sourceFile);
  122800. useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end;
  122801. }
  122802. var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile);
  122803. var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line ||
  122804. childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile);
  122805. if (useActualIndentation) {
  122806. // check if current node is a list item - if yes, take indentation from it
  122807. var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine);
  122808. if (actualIndentation !== -1 /* Unknown */) {
  122809. return actualIndentation + indentationDelta;
  122810. }
  122811. // try to fetch actual indentation for current node from source text
  122812. actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options);
  122813. if (actualIndentation !== -1 /* Unknown */) {
  122814. return actualIndentation + indentationDelta;
  122815. }
  122816. }
  122817. // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
  122818. if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) {
  122819. indentationDelta += options.indentSize;
  122820. }
  122821. // In our AST, a call argument's `parent` is the call-expression, not the argument list.
  122822. // We would like to increase indentation based on the relationship between an argument and its argument-list,
  122823. // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list.
  122824. // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression
  122825. // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation.
  122826. //
  122827. // Instead, when at an argument, we unspoof the starting position of the enclosing call expression
  122828. // *after* applying indentation for the argument.
  122829. var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile);
  122830. current = parent;
  122831. parent = current.parent;
  122832. currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart;
  122833. }
  122834. return indentationDelta + getBaseIndentation(options);
  122835. }
  122836. function getContainingListOrParentStart(parent, child, sourceFile) {
  122837. var containingList = getContainingList(child, sourceFile);
  122838. var startPos = containingList ? containingList.pos : parent.getStart(sourceFile);
  122839. return sourceFile.getLineAndCharacterOfPosition(startPos);
  122840. }
  122841. /*
  122842. * Function returns Value.Unknown if indentation cannot be determined
  122843. */
  122844. function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) {
  122845. // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
  122846. var commaItemInfo = ts.findListItemInfo(commaToken);
  122847. if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
  122848. return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
  122849. }
  122850. else {
  122851. // handle broken code gracefully
  122852. return -1 /* Unknown */;
  122853. }
  122854. }
  122855. /*
  122856. * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression)
  122857. */
  122858. function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) {
  122859. // actual indentation is used for statements\declarations if one of cases below is true:
  122860. // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
  122861. // - parent and child are not on the same line
  122862. var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
  122863. (parent.kind === 290 /* SourceFile */ || !parentAndChildShareLine);
  122864. if (!useActualIndentation) {
  122865. return -1 /* Unknown */;
  122866. }
  122867. return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
  122868. }
  122869. var NextTokenKind;
  122870. (function (NextTokenKind) {
  122871. NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown";
  122872. NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace";
  122873. NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
  122874. })(NextTokenKind || (NextTokenKind = {}));
  122875. function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
  122876. var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
  122877. if (!nextToken) {
  122878. return 0 /* Unknown */;
  122879. }
  122880. if (nextToken.kind === 18 /* OpenBraceToken */) {
  122881. // open braces are always indented at the parent level
  122882. return 1 /* OpenBrace */;
  122883. }
  122884. else if (nextToken.kind === 19 /* CloseBraceToken */) {
  122885. // close braces are indented at the parent level if they are located on the same line with cursor
  122886. // this means that if new line will be added at $ position, this case will be indented
  122887. // class A {
  122888. // $
  122889. // }
  122890. /// and this one - not
  122891. // class A {
  122892. // $}
  122893. var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
  122894. return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
  122895. }
  122896. return 0 /* Unknown */;
  122897. }
  122898. function getStartLineAndCharacterForNode(n, sourceFile) {
  122899. return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
  122900. }
  122901. function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) {
  122902. if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) {
  122903. return false;
  122904. }
  122905. var expressionOfCallExpressionEnd = parent.expression.getEnd();
  122906. var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line;
  122907. return expressionOfCallExpressionEndLine === childStartLine;
  122908. }
  122909. SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
  122910. function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
  122911. if (parent.kind === 227 /* IfStatement */ && parent.elseStatement === child) {
  122912. var elseKeyword = ts.findChildOfKind(parent, 87 /* ElseKeyword */, sourceFile);
  122913. ts.Debug.assert(elseKeyword !== undefined);
  122914. var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
  122915. return elseKeywordStartLine === childStartLine;
  122916. }
  122917. return false;
  122918. }
  122919. SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
  122920. function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) {
  122921. if (ts.isCallOrNewExpression(parent)) {
  122922. if (!parent.arguments)
  122923. return false;
  122924. var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; });
  122925. // If it's not one of the arguments, don't look past this
  122926. if (!currentNode)
  122927. return false;
  122928. var currentIndex = parent.arguments.indexOf(currentNode);
  122929. if (currentIndex === 0)
  122930. return false; // Can't look at previous node if first
  122931. var previousNode = parent.arguments[currentIndex - 1];
  122932. var lineOfPreviousNode = ts.getLineAndCharacterOfPosition(sourceFile, previousNode.getEnd()).line;
  122933. if (childStartLine === lineOfPreviousNode) {
  122934. return true;
  122935. }
  122936. }
  122937. return false;
  122938. }
  122939. SmartIndenter.argumentStartsOnSameLineAsPreviousArgument = argumentStartsOnSameLineAsPreviousArgument;
  122940. function getContainingList(node, sourceFile) {
  122941. return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile);
  122942. }
  122943. SmartIndenter.getContainingList = getContainingList;
  122944. function getListByPosition(pos, node, sourceFile) {
  122945. return node && getListByRange(pos, pos, node, sourceFile);
  122946. }
  122947. function getListByRange(start, end, node, sourceFile) {
  122948. switch (node.kind) {
  122949. case 169 /* TypeReference */:
  122950. return getList(node.typeArguments);
  122951. case 193 /* ObjectLiteralExpression */:
  122952. return getList(node.properties);
  122953. case 192 /* ArrayLiteralExpression */:
  122954. return getList(node.elements);
  122955. case 173 /* TypeLiteral */:
  122956. return getList(node.members);
  122957. case 244 /* FunctionDeclaration */:
  122958. case 201 /* FunctionExpression */:
  122959. case 202 /* ArrowFunction */:
  122960. case 161 /* MethodDeclaration */:
  122961. case 160 /* MethodSignature */:
  122962. case 165 /* CallSignature */:
  122963. case 162 /* Constructor */:
  122964. case 171 /* ConstructorType */:
  122965. case 166 /* ConstructSignature */:
  122966. return getList(node.typeParameters) || getList(node.parameters);
  122967. case 245 /* ClassDeclaration */:
  122968. case 214 /* ClassExpression */:
  122969. case 246 /* InterfaceDeclaration */:
  122970. case 247 /* TypeAliasDeclaration */:
  122971. case 320 /* JSDocTemplateTag */:
  122972. return getList(node.typeParameters);
  122973. case 197 /* NewExpression */:
  122974. case 196 /* CallExpression */:
  122975. return getList(node.typeArguments) || getList(node.arguments);
  122976. case 243 /* VariableDeclarationList */:
  122977. return getList(node.declarations);
  122978. case 257 /* NamedImports */:
  122979. case 261 /* NamedExports */:
  122980. return getList(node.elements);
  122981. case 189 /* ObjectBindingPattern */:
  122982. case 190 /* ArrayBindingPattern */:
  122983. return getList(node.elements);
  122984. }
  122985. function getList(list) {
  122986. return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined;
  122987. }
  122988. }
  122989. function getVisualListRange(node, list, sourceFile) {
  122990. var children = node.getChildren(sourceFile);
  122991. for (var i = 1; i < children.length - 1; i++) {
  122992. if (children[i].pos === list.pos && children[i].end === list.end) {
  122993. return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) };
  122994. }
  122995. }
  122996. return list;
  122997. }
  122998. function getActualIndentationForListStartLine(list, sourceFile, options) {
  122999. if (!list) {
  123000. return -1 /* Unknown */;
  123001. }
  123002. return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options);
  123003. }
  123004. function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) {
  123005. if (node.parent && node.parent.kind === 243 /* VariableDeclarationList */) {
  123006. // VariableDeclarationList has no wrapping tokens
  123007. return -1 /* Unknown */;
  123008. }
  123009. var containingList = getContainingList(node, sourceFile);
  123010. if (containingList) {
  123011. var index = containingList.indexOf(node);
  123012. if (index !== -1) {
  123013. var result = deriveActualIndentationFromList(containingList, index, sourceFile, options);
  123014. if (result !== -1 /* Unknown */) {
  123015. return result;
  123016. }
  123017. }
  123018. return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217
  123019. }
  123020. return -1 /* Unknown */;
  123021. }
  123022. function deriveActualIndentationFromList(list, index, sourceFile, options) {
  123023. ts.Debug.assert(index >= 0 && index < list.length);
  123024. var node = list[index];
  123025. // walk toward the start of the list starting from current node and check if the line is the same for all items.
  123026. // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i]
  123027. var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
  123028. for (var i = index - 1; i >= 0; i--) {
  123029. if (list[i].kind === 27 /* CommaToken */) {
  123030. continue;
  123031. }
  123032. // skip list items that ends on the same line with the current list element
  123033. var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
  123034. if (prevEndLine !== lineAndCharacter.line) {
  123035. return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
  123036. }
  123037. lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile);
  123038. }
  123039. return -1 /* Unknown */;
  123040. }
  123041. function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) {
  123042. var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
  123043. return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
  123044. }
  123045. /**
  123046. * Character is the actual index of the character since the beginning of the line.
  123047. * Column - position of the character after expanding tabs to spaces.
  123048. * "0\t2$"
  123049. * value of 'character' for '$' is 3
  123050. * value of 'column' for '$' is 6 (assuming that tab size is 4)
  123051. */
  123052. function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
  123053. var character = 0;
  123054. var column = 0;
  123055. for (var pos = startPos; pos < endPos; pos++) {
  123056. var ch = sourceFile.text.charCodeAt(pos);
  123057. if (!ts.isWhiteSpaceSingleLine(ch)) {
  123058. break;
  123059. }
  123060. if (ch === 9 /* tab */) {
  123061. column += options.tabSize + (column % options.tabSize);
  123062. }
  123063. else {
  123064. column++;
  123065. }
  123066. character++;
  123067. }
  123068. return { column: column, character: character };
  123069. }
  123070. SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn;
  123071. function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
  123072. return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
  123073. }
  123074. SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
  123075. function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) {
  123076. var childKind = child ? child.kind : 0 /* Unknown */;
  123077. switch (parent.kind) {
  123078. case 226 /* ExpressionStatement */:
  123079. case 245 /* ClassDeclaration */:
  123080. case 214 /* ClassExpression */:
  123081. case 246 /* InterfaceDeclaration */:
  123082. case 248 /* EnumDeclaration */:
  123083. case 247 /* TypeAliasDeclaration */:
  123084. case 192 /* ArrayLiteralExpression */:
  123085. case 223 /* Block */:
  123086. case 250 /* ModuleBlock */:
  123087. case 193 /* ObjectLiteralExpression */:
  123088. case 173 /* TypeLiteral */:
  123089. case 186 /* MappedType */:
  123090. case 175 /* TupleType */:
  123091. case 251 /* CaseBlock */:
  123092. case 278 /* DefaultClause */:
  123093. case 277 /* CaseClause */:
  123094. case 200 /* ParenthesizedExpression */:
  123095. case 194 /* PropertyAccessExpression */:
  123096. case 196 /* CallExpression */:
  123097. case 197 /* NewExpression */:
  123098. case 225 /* VariableStatement */:
  123099. case 259 /* ExportAssignment */:
  123100. case 235 /* ReturnStatement */:
  123101. case 210 /* ConditionalExpression */:
  123102. case 190 /* ArrayBindingPattern */:
  123103. case 189 /* ObjectBindingPattern */:
  123104. case 268 /* JsxOpeningElement */:
  123105. case 271 /* JsxOpeningFragment */:
  123106. case 267 /* JsxSelfClosingElement */:
  123107. case 276 /* JsxExpression */:
  123108. case 160 /* MethodSignature */:
  123109. case 165 /* CallSignature */:
  123110. case 166 /* ConstructSignature */:
  123111. case 156 /* Parameter */:
  123112. case 170 /* FunctionType */:
  123113. case 171 /* ConstructorType */:
  123114. case 182 /* ParenthesizedType */:
  123115. case 198 /* TaggedTemplateExpression */:
  123116. case 206 /* AwaitExpression */:
  123117. case 261 /* NamedExports */:
  123118. case 257 /* NamedImports */:
  123119. case 263 /* ExportSpecifier */:
  123120. case 258 /* ImportSpecifier */:
  123121. case 159 /* PropertyDeclaration */:
  123122. return true;
  123123. case 242 /* VariableDeclaration */:
  123124. case 281 /* PropertyAssignment */:
  123125. case 209 /* BinaryExpression */:
  123126. if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 193 /* ObjectLiteralExpression */) { // TODO: GH#18217
  123127. return rangeIsOnOneLine(sourceFile, child);
  123128. }
  123129. if (parent.kind !== 209 /* BinaryExpression */) {
  123130. return true;
  123131. }
  123132. break;
  123133. case 228 /* DoStatement */:
  123134. case 229 /* WhileStatement */:
  123135. case 231 /* ForInStatement */:
  123136. case 232 /* ForOfStatement */:
  123137. case 230 /* ForStatement */:
  123138. case 227 /* IfStatement */:
  123139. case 244 /* FunctionDeclaration */:
  123140. case 201 /* FunctionExpression */:
  123141. case 161 /* MethodDeclaration */:
  123142. case 202 /* ArrowFunction */:
  123143. case 162 /* Constructor */:
  123144. case 163 /* GetAccessor */:
  123145. case 164 /* SetAccessor */:
  123146. return childKind !== 223 /* Block */;
  123147. case 260 /* ExportDeclaration */:
  123148. return childKind !== 261 /* NamedExports */;
  123149. case 254 /* ImportDeclaration */:
  123150. return childKind !== 255 /* ImportClause */ ||
  123151. (!!child.namedBindings && child.namedBindings.kind !== 257 /* NamedImports */);
  123152. case 266 /* JsxElement */:
  123153. return childKind !== 269 /* JsxClosingElement */;
  123154. case 270 /* JsxFragment */:
  123155. return childKind !== 272 /* JsxClosingFragment */;
  123156. case 179 /* IntersectionType */:
  123157. case 178 /* UnionType */:
  123158. if (childKind === 173 /* TypeLiteral */) {
  123159. return false;
  123160. }
  123161. // falls through
  123162. }
  123163. // No explicit rule for given nodes so the result will follow the default value argument
  123164. return indentByDefault;
  123165. }
  123166. SmartIndenter.nodeWillIndentChild = nodeWillIndentChild;
  123167. function isControlFlowEndingStatement(kind, parent) {
  123168. switch (kind) {
  123169. case 235 /* ReturnStatement */:
  123170. case 239 /* ThrowStatement */:
  123171. case 233 /* ContinueStatement */:
  123172. case 234 /* BreakStatement */:
  123173. return parent.kind !== 223 /* Block */;
  123174. default:
  123175. return false;
  123176. }
  123177. }
  123178. /**
  123179. * True when the parent node should indent the given child by an explicit rule.
  123180. * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child.
  123181. */
  123182. function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) {
  123183. if (isNextChild === void 0) { isNextChild = false; }
  123184. return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)
  123185. && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent));
  123186. }
  123187. SmartIndenter.shouldIndentChildNode = shouldIndentChildNode;
  123188. function rangeIsOnOneLine(sourceFile, range) {
  123189. var rangeStart = ts.skipTrivia(sourceFile.text, range.pos);
  123190. var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line;
  123191. var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
  123192. return startLine === endLine;
  123193. }
  123194. })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {}));
  123195. })(formatting = ts.formatting || (ts.formatting = {}));
  123196. })(ts || (ts = {}));
  123197. /* @internal */
  123198. var ts;
  123199. (function (ts) {
  123200. var textChanges;
  123201. (function (textChanges_3) {
  123202. /**
  123203. * Currently for simplicity we store recovered positions on the node itself.
  123204. * It can be changed to side-table later if we decide that current design is too invasive.
  123205. */
  123206. function getPos(n) {
  123207. var result = n.__pos;
  123208. ts.Debug.assert(typeof result === "number");
  123209. return result;
  123210. }
  123211. function setPos(n, pos) {
  123212. ts.Debug.assert(typeof pos === "number");
  123213. n.__pos = pos;
  123214. }
  123215. function getEnd(n) {
  123216. var result = n.__end;
  123217. ts.Debug.assert(typeof result === "number");
  123218. return result;
  123219. }
  123220. function setEnd(n, end) {
  123221. ts.Debug.assert(typeof end === "number");
  123222. n.__end = end;
  123223. }
  123224. var LeadingTriviaOption;
  123225. (function (LeadingTriviaOption) {
  123226. /** Exclude all leading trivia (use getStart()) */
  123227. LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
  123228. /** Include leading trivia and,
  123229. * if there are no line breaks between the node and the previous token,
  123230. * include all trivia between the node and the previous token
  123231. */
  123232. LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
  123233. })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
  123234. var TrailingTriviaOption;
  123235. (function (TrailingTriviaOption) {
  123236. /** Exclude all trailing trivia (use getEnd()) */
  123237. TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
  123238. /** Include trailing trivia */
  123239. TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
  123240. })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
  123241. function skipWhitespacesAndLineBreaks(text, start) {
  123242. return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
  123243. }
  123244. function hasCommentsBeforeLineBreak(text, start) {
  123245. var i = start;
  123246. while (i < text.length) {
  123247. var ch = text.charCodeAt(i);
  123248. if (ts.isWhiteSpaceSingleLine(ch)) {
  123249. i++;
  123250. continue;
  123251. }
  123252. return ch === 47 /* slash */;
  123253. }
  123254. return false;
  123255. }
  123256. var useNonAdjustedPositions = {
  123257. leadingTriviaOption: LeadingTriviaOption.Exclude,
  123258. trailingTriviaOption: TrailingTriviaOption.Exclude,
  123259. };
  123260. var ChangeKind;
  123261. (function (ChangeKind) {
  123262. ChangeKind[ChangeKind["Remove"] = 0] = "Remove";
  123263. ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode";
  123264. ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes";
  123265. ChangeKind[ChangeKind["Text"] = 3] = "Text";
  123266. })(ChangeKind || (ChangeKind = {}));
  123267. function getAdjustedRange(sourceFile, startNode, endNode, options) {
  123268. return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
  123269. }
  123270. function getAdjustedStartPosition(sourceFile, node, options) {
  123271. var leadingTriviaOption = options.leadingTriviaOption;
  123272. if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
  123273. return node.getStart(sourceFile);
  123274. }
  123275. var fullStart = node.getFullStart();
  123276. var start = node.getStart(sourceFile);
  123277. if (fullStart === start) {
  123278. return start;
  123279. }
  123280. var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile);
  123281. var startLine = ts.getLineStartPositionForPosition(start, sourceFile);
  123282. if (startLine === fullStartLine) {
  123283. // full start and start of the node are on the same line
  123284. // a, b;
  123285. // ^ ^
  123286. // | start
  123287. // fullstart
  123288. // when b is replaced - we usually want to keep the leading trvia
  123289. // when b is deleted - we delete it
  123290. return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
  123291. }
  123292. // get start position of the line following the line that contains fullstart position
  123293. // (but only if the fullstart isn't the very beginning of the file)
  123294. var nextLineStart = fullStart > 0 ? 1 : 0;
  123295. var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
  123296. // skip whitespaces/newlines
  123297. adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
  123298. return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
  123299. }
  123300. function getAdjustedEndPosition(sourceFile, node, options) {
  123301. var end = node.end;
  123302. var trailingTriviaOption = options.trailingTriviaOption;
  123303. if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
  123304. return end;
  123305. }
  123306. var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
  123307. return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
  123308. ? newEnd
  123309. : end;
  123310. }
  123311. /**
  123312. * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
  123313. */
  123314. function isSeparator(node, candidate) {
  123315. return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 193 /* ObjectLiteralExpression */));
  123316. }
  123317. function spaces(count) {
  123318. var s = "";
  123319. for (var i = 0; i < count; i++) {
  123320. s += " ";
  123321. }
  123322. return s;
  123323. }
  123324. function isThisTypeAnnotatable(containingFunction) {
  123325. return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction);
  123326. }
  123327. textChanges_3.isThisTypeAnnotatable = isThisTypeAnnotatable;
  123328. var ChangeTracker = /** @class */ (function () {
  123329. /** Public for tests only. Other callers should use `ChangeTracker.with`. */
  123330. function ChangeTracker(newLineCharacter, formatContext) {
  123331. this.newLineCharacter = newLineCharacter;
  123332. this.formatContext = formatContext;
  123333. this.changes = [];
  123334. this.newFiles = [];
  123335. this.classesWithNodesInsertedAtStart = ts.createMap(); // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
  123336. this.deletedNodes = [];
  123337. }
  123338. ChangeTracker.fromContext = function (context) {
  123339. return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
  123340. };
  123341. ChangeTracker.with = function (context, cb) {
  123342. var tracker = ChangeTracker.fromContext(context);
  123343. cb(tracker);
  123344. return tracker.getChanges();
  123345. };
  123346. ChangeTracker.prototype.pushRaw = function (sourceFile, change) {
  123347. ts.Debug.assertEqual(sourceFile.fileName, change.fileName);
  123348. for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) {
  123349. var c = _a[_i];
  123350. this.changes.push({
  123351. kind: ChangeKind.Text,
  123352. sourceFile: sourceFile,
  123353. text: c.newText,
  123354. range: ts.createTextRangeFromSpan(c.span),
  123355. });
  123356. }
  123357. };
  123358. ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
  123359. this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
  123360. };
  123361. ChangeTracker.prototype.delete = function (sourceFile, node) {
  123362. this.deletedNodes.push({ sourceFile: sourceFile, node: node });
  123363. };
  123364. ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) {
  123365. this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
  123366. };
  123367. ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
  123368. if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
  123369. var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
  123370. var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
  123371. this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  123372. };
  123373. ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
  123374. if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
  123375. var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
  123376. var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
  123377. this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  123378. };
  123379. ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
  123380. if (options === void 0) { options = {}; }
  123381. this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
  123382. };
  123383. ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
  123384. if (options === void 0) { options = useNonAdjustedPositions; }
  123385. this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
  123386. };
  123387. ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
  123388. if (options === void 0) { options = useNonAdjustedPositions; }
  123389. this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
  123390. };
  123391. ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
  123392. if (options === void 0) { options = {}; }
  123393. this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
  123394. };
  123395. ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
  123396. if (options === void 0) { options = useNonAdjustedPositions; }
  123397. this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
  123398. };
  123399. ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
  123400. this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
  123401. };
  123402. ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
  123403. if (options === void 0) { options = useNonAdjustedPositions; }
  123404. this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
  123405. };
  123406. ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
  123407. var next = ts.findNextToken(node, node.parent, sourceFile);
  123408. return next && next.kind === 27 /* CommaToken */ ? next : undefined;
  123409. };
  123410. ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
  123411. var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
  123412. this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
  123413. };
  123414. ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
  123415. if (options === void 0) { options = {}; }
  123416. this.replaceRange(sourceFile, ts.createRange(pos), newNode, options);
  123417. };
  123418. ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) {
  123419. if (options === void 0) { options = {}; }
  123420. this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options);
  123421. };
  123422. ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) {
  123423. var pos = getInsertionPositionAtSourceFileTop(sourceFile);
  123424. this.insertNodeAt(sourceFile, pos, newNode, {
  123425. prefix: pos === 0 ? undefined : this.newLineCharacter,
  123426. suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""),
  123427. });
  123428. };
  123429. ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
  123430. if (blankLineBetween === void 0) { blankLineBetween = false; }
  123431. this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
  123432. };
  123433. ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
  123434. var pos = before.getStart(sourceFile);
  123435. this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " });
  123436. };
  123437. ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) {
  123438. if (!before.modifiers) {
  123439. this.insertModifierBefore(sourceFile, modifier, before);
  123440. return;
  123441. }
  123442. var pos = before.modifiers.end;
  123443. this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " });
  123444. };
  123445. ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) {
  123446. var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile);
  123447. var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
  123448. // First try to see if we can put the comment on the previous line.
  123449. // We need to make sure that we are not in the middle of a string literal or a comment.
  123450. // If so, we do not want to separate the node from its comment if we can.
  123451. // Otherwise, add an extra new line immediately before the error span.
  123452. var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
  123453. var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
  123454. var indent = sourceFile.text.slice(lineStartPosition, startPosition);
  123455. var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
  123456. this.insertText(sourceFile, token.getStart(sourceFile), text);
  123457. };
  123458. ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) {
  123459. var fnStart = node.getStart(sourceFile);
  123460. if (node.jsDoc) {
  123461. for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
  123462. var jsdoc = _a[_i];
  123463. this.deleteRange(sourceFile, {
  123464. pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile),
  123465. end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {})
  123466. });
  123467. }
  123468. }
  123469. var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1);
  123470. var indent = sourceFile.text.slice(startPosition, fnStart);
  123471. this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent });
  123472. };
  123473. ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
  123474. this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text });
  123475. };
  123476. ChangeTracker.prototype.insertText = function (sourceFile, pos, text) {
  123477. this.replaceRangeWithText(sourceFile, ts.createRange(pos), text);
  123478. };
  123479. /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
  123480. ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) {
  123481. var endNode;
  123482. if (ts.isFunctionLike(node)) {
  123483. endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile);
  123484. if (!endNode) {
  123485. if (!ts.isArrowFunction(node))
  123486. return false; // Function missing parentheses, give up
  123487. // If no `)`, is an arrow function `x => x`, so use the end of the first parameter
  123488. endNode = ts.first(node.parameters);
  123489. }
  123490. }
  123491. else {
  123492. endNode = node.kind !== 242 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name;
  123493. }
  123494. this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
  123495. return true;
  123496. };
  123497. ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) {
  123498. var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1;
  123499. var suffix = node.parameters.length ? ", " : "";
  123500. this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix: suffix });
  123501. };
  123502. ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) {
  123503. // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter
  123504. var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile);
  123505. this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" });
  123506. };
  123507. ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) {
  123508. if (ts.isStatement(before) || ts.isClassElement(before)) {
  123509. return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
  123510. }
  123511. else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
  123512. return { suffix: ", " };
  123513. }
  123514. else if (ts.isParameter(before)) {
  123515. return {};
  123516. }
  123517. else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) {
  123518. return { suffix: ", " };
  123519. }
  123520. return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
  123521. };
  123522. ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
  123523. var firstStatement = ts.firstOrUndefined(ctr.body.statements);
  123524. if (!firstStatement || !ctr.body.multiLine) {
  123525. this.replaceConstructorBody(sourceFile, ctr, __spreadArrays([newStatement], ctr.body.statements));
  123526. }
  123527. else {
  123528. this.insertNodeBefore(sourceFile, firstStatement, newStatement);
  123529. }
  123530. };
  123531. ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) {
  123532. var lastStatement = ts.lastOrUndefined(ctr.body.statements);
  123533. if (!lastStatement || !ctr.body.multiLine) {
  123534. this.replaceConstructorBody(sourceFile, ctr, __spreadArrays(ctr.body.statements, [newStatement]));
  123535. }
  123536. else {
  123537. this.insertNodeAfter(sourceFile, lastStatement, newStatement);
  123538. }
  123539. };
  123540. ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) {
  123541. this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
  123542. };
  123543. ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
  123544. var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
  123545. this.insertNodeAt(sourceFile, pos, newNode, {
  123546. prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
  123547. suffix: this.newLineCharacter
  123548. });
  123549. };
  123550. ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
  123551. this.insertNodeAtStartWorker(sourceFile, cls, newElement);
  123552. };
  123553. ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) {
  123554. this.insertNodeAtStartWorker(sourceFile, obj, newElement);
  123555. };
  123556. ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) {
  123557. var _a;
  123558. var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls);
  123559. this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation));
  123560. };
  123561. /**
  123562. * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on
  123563. * new lines and must share the same indentation.
  123564. */
  123565. ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) {
  123566. var indentation;
  123567. var lastRange = cls;
  123568. for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) {
  123569. var member = _a[_i];
  123570. if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) {
  123571. // each indented member must be on a new line
  123572. return undefined;
  123573. }
  123574. var memberStart = member.getStart(sourceFile);
  123575. var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options);
  123576. if (indentation === undefined) {
  123577. indentation = memberIndentation;
  123578. }
  123579. else if (memberIndentation !== indentation) {
  123580. // indentation of multiple members is not consistent
  123581. return undefined;
  123582. }
  123583. lastRange = member;
  123584. }
  123585. return indentation;
  123586. };
  123587. ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) {
  123588. var _a;
  123589. var clsStart = cls.getStart(sourceFile);
  123590. return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
  123591. + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4);
  123592. };
  123593. ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) {
  123594. // Rules:
  123595. // - Always insert leading newline.
  123596. // - For object literals:
  123597. // - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file
  123598. // (because trailing commas are generally illegal in a JSON file).
  123599. // - Add a leading comma if the source file is not a JSON file, there are existing insertions,
  123600. // and the node is empty (because we didn't add a trailing comma per the previous rule).
  123601. // - Only insert a trailing newline if body is single-line and there are no other insertions for the node.
  123602. // NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`.
  123603. var members = getMembersOrProperties(cls);
  123604. var isEmpty = members.length === 0;
  123605. var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile });
  123606. var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty);
  123607. var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion;
  123608. return {
  123609. indentation: indentation,
  123610. prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter,
  123611. suffix: insertTrailingComma ? "," : ""
  123612. };
  123613. };
  123614. ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
  123615. var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
  123616. this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
  123617. };
  123618. ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
  123619. var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
  123620. this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
  123621. };
  123622. ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) {
  123623. this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
  123624. };
  123625. ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
  123626. var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
  123627. this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
  123628. };
  123629. ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
  123630. if (needSemicolonBetween(after, newNode)) {
  123631. // check if previous statement ends with semicolon
  123632. // if not - insert semicolon to preserve the code from changing the meaning due to ASI
  123633. if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
  123634. this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */));
  123635. }
  123636. }
  123637. var endPosition = getAdjustedEndPosition(sourceFile, after, {});
  123638. return endPosition;
  123639. };
  123640. ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
  123641. var options = this.getInsertNodeAfterOptionsWorker(after);
  123642. return __assign(__assign({}, options), { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
  123643. };
  123644. ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
  123645. switch (node.kind) {
  123646. case 245 /* ClassDeclaration */:
  123647. case 249 /* ModuleDeclaration */:
  123648. return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
  123649. case 242 /* VariableDeclaration */:
  123650. case 10 /* StringLiteral */:
  123651. case 75 /* Identifier */:
  123652. return { prefix: ", " };
  123653. case 281 /* PropertyAssignment */:
  123654. return { suffix: "," + this.newLineCharacter };
  123655. case 89 /* ExportKeyword */:
  123656. return { prefix: " " };
  123657. case 156 /* Parameter */:
  123658. return {};
  123659. default:
  123660. ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it
  123661. return { suffix: this.newLineCharacter };
  123662. }
  123663. };
  123664. ChangeTracker.prototype.insertName = function (sourceFile, node, name) {
  123665. ts.Debug.assert(!node.name);
  123666. if (node.kind === 202 /* ArrowFunction */) {
  123667. var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile);
  123668. var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile);
  123669. if (lparen) {
  123670. // `() => {}` --> `function f() {}`
  123671. this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(94 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " });
  123672. deleteNode(this, sourceFile, arrow);
  123673. }
  123674. else {
  123675. // `x => {}` -> `function f(x) {}`
  123676. this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "(");
  123677. // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)`
  123678. this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */));
  123679. }
  123680. if (node.body.kind !== 223 /* Block */) {
  123681. // `() => 0` => `function f() { return 0; }`
  123682. this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(101 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
  123683. this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " });
  123684. }
  123685. }
  123686. else {
  123687. var pos = ts.findChildOfKind(node, node.kind === 201 /* FunctionExpression */ ? 94 /* FunctionKeyword */ : 80 /* ClassKeyword */, sourceFile).end;
  123688. this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
  123689. }
  123690. };
  123691. ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
  123692. this.insertText(sourceFile, node.getStart(sourceFile), "export ");
  123693. };
  123694. /**
  123695. * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
  123696. * i.e. arguments in arguments lists, parameters in parameter lists etc.
  123697. * Note that separators are part of the node in statements and class elements.
  123698. */
  123699. ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
  123700. if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
  123701. if (!containingList) {
  123702. ts.Debug.fail("node is not a list element");
  123703. return;
  123704. }
  123705. var index = ts.indexOfNode(containingList, after);
  123706. if (index < 0) {
  123707. return;
  123708. }
  123709. var end = after.getEnd();
  123710. if (index !== containingList.length - 1) {
  123711. // any element except the last one
  123712. // use next sibling as an anchor
  123713. var nextToken = ts.getTokenAtPosition(sourceFile, after.end);
  123714. if (nextToken && isSeparator(after, nextToken)) {
  123715. // for list
  123716. // a, b, c
  123717. // create change for adding 'e' after 'a' as
  123718. // - find start of next element after a (it is b)
  123719. // - use this start as start and end position in final change
  123720. // - build text of change by formatting the text of node + separator + whitespace trivia of b
  123721. // in multiline case it will work as
  123722. // a,
  123723. // b,
  123724. // c,
  123725. // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#')
  123726. // a,*
  123727. // ***insertedtext<separator>#
  123728. // ###b,
  123729. // c,
  123730. // find line and character of the next element
  123731. var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart()));
  123732. // find line and character of the token that precedes next element (usually it is separator)
  123733. var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end);
  123734. var prefix = void 0;
  123735. var startPos = void 0;
  123736. if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) {
  123737. // next element is located on the same line with separator:
  123738. // a,$$$$b
  123739. // ^ ^
  123740. // | |-next element
  123741. // |-separator
  123742. // where $$$ is some leading trivia
  123743. // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces
  123744. // a, x,$$$$b
  123745. // ^ ^ ^
  123746. // | | |-next element
  123747. // | |-new inserted node padded with spaces
  123748. // |-separator
  123749. startPos = nextToken.end;
  123750. prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character);
  123751. }
  123752. else {
  123753. // next element is located on different line that separator
  123754. // let insert position be the beginning of the line that contains next element
  123755. startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile);
  123756. }
  123757. // write separator and leading trivia of the next element as suffix
  123758. var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile));
  123759. this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix });
  123760. }
  123761. }
  123762. else {
  123763. var afterStart = after.getStart(sourceFile);
  123764. var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile);
  123765. var separator = void 0;
  123766. var multilineList = false;
  123767. // insert element after the last element in the list that has more than one item
  123768. // pick the element preceding the after element to:
  123769. // - pick the separator
  123770. // - determine if list is a multiline
  123771. if (containingList.length === 1) {
  123772. // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise
  123773. // i.e. var x = 1 // this is x
  123774. // | new element will be inserted at this position
  123775. separator = 27 /* CommaToken */;
  123776. }
  123777. else {
  123778. // element has more than one element, pick separator from the list
  123779. var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile);
  123780. separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */;
  123781. // determine if list is multiline by checking lines of after element and element that precedes it.
  123782. var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
  123783. multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
  123784. }
  123785. if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) {
  123786. // in this case we'll always treat containing list as multiline
  123787. multilineList = true;
  123788. }
  123789. if (multilineList) {
  123790. // insert separator immediately following the 'after' node to preserve comments in trailing trivia
  123791. this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator));
  123792. // use the same indentation as 'after' item
  123793. var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
  123794. // insert element before the line break on the line that contains 'after' element
  123795. var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false);
  123796. if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
  123797. insertPos--;
  123798. }
  123799. this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter });
  123800. }
  123801. else {
  123802. this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
  123803. }
  123804. }
  123805. };
  123806. ChangeTracker.prototype.parenthesizeExpression = function (sourceFile, expression) {
  123807. this.replaceRange(sourceFile, ts.rangeOfNode(expression), ts.createParen(expression));
  123808. };
  123809. ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
  123810. var _this = this;
  123811. this.classesWithNodesInsertedAtStart.forEach(function (_a) {
  123812. var node = _a.node, sourceFile = _a.sourceFile;
  123813. var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1];
  123814. if (openBraceEnd !== undefined && closeBraceEnd !== undefined) {
  123815. var isEmpty = getMembersOrProperties(node).length === 0;
  123816. var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile);
  123817. if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) {
  123818. // For `class C { }` remove the whitespace inside the braces.
  123819. _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1));
  123820. }
  123821. if (isSingleLine) {
  123822. _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter);
  123823. }
  123824. }
  123825. });
  123826. };
  123827. ChangeTracker.prototype.finishDeleteDeclarations = function () {
  123828. var _this = this;
  123829. var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
  123830. var _loop_9 = function (sourceFile, node) {
  123831. if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
  123832. if (ts.isArray(node)) {
  123833. this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
  123834. }
  123835. else {
  123836. deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node);
  123837. }
  123838. }
  123839. };
  123840. var this_1 = this;
  123841. for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
  123842. var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
  123843. _loop_9(sourceFile, node);
  123844. }
  123845. deletedNodesInLists.forEach(function (node) {
  123846. var sourceFile = node.getSourceFile();
  123847. var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
  123848. if (node !== ts.last(list))
  123849. return;
  123850. var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2);
  123851. if (lastNonDeletedIndex !== -1) {
  123852. _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
  123853. }
  123854. });
  123855. };
  123856. /**
  123857. * Note: after calling this, the TextChanges object must be discarded!
  123858. * @param validate only for tests
  123859. * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
  123860. * so we can only call this once and can't get the non-formatted text separately.
  123861. */
  123862. ChangeTracker.prototype.getChanges = function (validate) {
  123863. this.finishDeleteDeclarations();
  123864. this.finishClassesWithNodesInsertedAtStart();
  123865. var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
  123866. for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
  123867. var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
  123868. changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext));
  123869. }
  123870. return changes;
  123871. };
  123872. ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
  123873. this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
  123874. };
  123875. return ChangeTracker;
  123876. }());
  123877. textChanges_3.ChangeTracker = ChangeTracker;
  123878. // find first non-whitespace position in the leading trivia of the node
  123879. function startPositionToDeleteNodeInList(sourceFile, node) {
  123880. return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
  123881. }
  123882. function getClassOrObjectBraceEnds(cls, sourceFile) {
  123883. var open = ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile);
  123884. var close = ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile);
  123885. return [open === null || open === void 0 ? void 0 : open.end, close === null || close === void 0 ? void 0 : close.end];
  123886. }
  123887. function getMembersOrProperties(cls) {
  123888. return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members;
  123889. }
  123890. function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) {
  123891. return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext);
  123892. }
  123893. textChanges_3.getNewFileText = getNewFileText;
  123894. var changesToText;
  123895. (function (changesToText) {
  123896. function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
  123897. return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
  123898. var sourceFile = changesInFile[0].sourceFile;
  123899. // order changes by start position
  123900. // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
  123901. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
  123902. var _loop_10 = function (i) {
  123903. ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
  123904. return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
  123905. });
  123906. };
  123907. // verify that change intervals do not overlap, except possibly at end points.
  123908. for (var i = 0; i < normalized.length - 1; i++) {
  123909. _loop_10(i);
  123910. }
  123911. var textChanges = normalized.map(function (c) {
  123912. return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
  123913. });
  123914. return { fileName: sourceFile.fileName, textChanges: textChanges };
  123915. });
  123916. }
  123917. changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
  123918. function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) {
  123919. var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext);
  123920. return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
  123921. }
  123922. changesToText.newFileChanges = newFileChanges;
  123923. function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
  123924. // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
  123925. var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
  123926. var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 99 /* ESNext */, /*setParentNodes*/ true, scriptKind);
  123927. var changes = ts.formatting.formatDocument(sourceFile, formatContext);
  123928. return applyChanges(nonFormattedText, changes) + newLineCharacter;
  123929. }
  123930. changesToText.newFileChangesWorker = newFileChangesWorker;
  123931. function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
  123932. if (change.kind === ChangeKind.Remove) {
  123933. return "";
  123934. }
  123935. if (change.kind === ChangeKind.Text) {
  123936. return change.text;
  123937. }
  123938. var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
  123939. var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
  123940. var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
  123941. ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217
  123942. : format(change.node);
  123943. // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
  123944. var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
  123945. return (options.prefix || "") + noIndent + (options.suffix || "");
  123946. }
  123947. function getFormatCodeSettingsForWriting(_a, sourceFile) {
  123948. var options = _a.options;
  123949. var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore;
  123950. var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !ts.probablyUsesSemicolons(sourceFile);
  123951. return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore });
  123952. }
  123953. /** Note: this may mutate `nodeIn`. */
  123954. function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) {
  123955. var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta;
  123956. var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text;
  123957. if (validate)
  123958. validate(node, text);
  123959. var formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
  123960. var initialIndentation = indentation !== undefined
  123961. ? indentation
  123962. : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos);
  123963. if (delta === undefined) {
  123964. delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? (formatOptions.indentSize || 0) : 0;
  123965. }
  123966. var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
  123967. var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, __assign(__assign({}, formatContext), { options: formatOptions }));
  123968. return applyChanges(text, changes);
  123969. }
  123970. /** Note: output node may be mutated input node. */
  123971. function getNonformattedText(node, sourceFile, newLineCharacter) {
  123972. var writer = createWriter(newLineCharacter);
  123973. var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
  123974. ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
  123975. return { text: writer.getText(), node: assignPositionsToNode(node) };
  123976. }
  123977. changesToText.getNonformattedText = getNonformattedText;
  123978. })(changesToText || (changesToText = {}));
  123979. function applyChanges(text, changes) {
  123980. for (var i = changes.length - 1; i >= 0; i--) {
  123981. var _a = changes[i], span = _a.span, newText = _a.newText;
  123982. text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span));
  123983. }
  123984. return text;
  123985. }
  123986. textChanges_3.applyChanges = applyChanges;
  123987. function isTrivia(s) {
  123988. return ts.skipTrivia(s, 0) === s.length;
  123989. }
  123990. function assignPositionsToNode(node) {
  123991. var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217
  123992. // create proxy node for non synthesized nodes
  123993. var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited);
  123994. newNode.pos = getPos(node);
  123995. newNode.end = getEnd(node);
  123996. return newNode;
  123997. }
  123998. function assignPositionsToNodeArray(nodes, visitor, test, start, count) {
  123999. var visited = ts.visitNodes(nodes, visitor, test, start, count);
  124000. if (!visited) {
  124001. return visited;
  124002. }
  124003. // clone nodearray if necessary
  124004. var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited;
  124005. nodeArray.pos = getPos(nodes);
  124006. nodeArray.end = getEnd(nodes);
  124007. return nodeArray;
  124008. }
  124009. function createWriter(newLine) {
  124010. var lastNonTriviaPosition = 0;
  124011. var writer = ts.createTextWriter(newLine);
  124012. var onEmitNode = function (hint, node, printCallback) {
  124013. if (node) {
  124014. setPos(node, lastNonTriviaPosition);
  124015. }
  124016. printCallback(hint, node);
  124017. if (node) {
  124018. setEnd(node, lastNonTriviaPosition);
  124019. }
  124020. };
  124021. var onBeforeEmitNodeArray = function (nodes) {
  124022. if (nodes) {
  124023. setPos(nodes, lastNonTriviaPosition);
  124024. }
  124025. };
  124026. var onAfterEmitNodeArray = function (nodes) {
  124027. if (nodes) {
  124028. setEnd(nodes, lastNonTriviaPosition);
  124029. }
  124030. };
  124031. var onBeforeEmitToken = function (node) {
  124032. if (node) {
  124033. setPos(node, lastNonTriviaPosition);
  124034. }
  124035. };
  124036. var onAfterEmitToken = function (node) {
  124037. if (node) {
  124038. setEnd(node, lastNonTriviaPosition);
  124039. }
  124040. };
  124041. function setLastNonTriviaPosition(s, force) {
  124042. if (force || !isTrivia(s)) {
  124043. lastNonTriviaPosition = writer.getTextPos();
  124044. var i = 0;
  124045. while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) {
  124046. i++;
  124047. }
  124048. // trim trailing whitespaces
  124049. lastNonTriviaPosition -= i;
  124050. }
  124051. }
  124052. function write(s) {
  124053. writer.write(s);
  124054. setLastNonTriviaPosition(s, /*force*/ false);
  124055. }
  124056. function writeComment(s) {
  124057. writer.writeComment(s);
  124058. }
  124059. function writeKeyword(s) {
  124060. writer.writeKeyword(s);
  124061. setLastNonTriviaPosition(s, /*force*/ false);
  124062. }
  124063. function writeOperator(s) {
  124064. writer.writeOperator(s);
  124065. setLastNonTriviaPosition(s, /*force*/ false);
  124066. }
  124067. function writePunctuation(s) {
  124068. writer.writePunctuation(s);
  124069. setLastNonTriviaPosition(s, /*force*/ false);
  124070. }
  124071. function writeTrailingSemicolon(s) {
  124072. writer.writeTrailingSemicolon(s);
  124073. setLastNonTriviaPosition(s, /*force*/ false);
  124074. }
  124075. function writeParameter(s) {
  124076. writer.writeParameter(s);
  124077. setLastNonTriviaPosition(s, /*force*/ false);
  124078. }
  124079. function writeProperty(s) {
  124080. writer.writeProperty(s);
  124081. setLastNonTriviaPosition(s, /*force*/ false);
  124082. }
  124083. function writeSpace(s) {
  124084. writer.writeSpace(s);
  124085. setLastNonTriviaPosition(s, /*force*/ false);
  124086. }
  124087. function writeStringLiteral(s) {
  124088. writer.writeStringLiteral(s);
  124089. setLastNonTriviaPosition(s, /*force*/ false);
  124090. }
  124091. function writeSymbol(s, sym) {
  124092. writer.writeSymbol(s, sym);
  124093. setLastNonTriviaPosition(s, /*force*/ false);
  124094. }
  124095. function writeLine() {
  124096. writer.writeLine();
  124097. }
  124098. function increaseIndent() {
  124099. writer.increaseIndent();
  124100. }
  124101. function decreaseIndent() {
  124102. writer.decreaseIndent();
  124103. }
  124104. function getText() {
  124105. return writer.getText();
  124106. }
  124107. function rawWrite(s) {
  124108. writer.rawWrite(s);
  124109. setLastNonTriviaPosition(s, /*force*/ false);
  124110. }
  124111. function writeLiteral(s) {
  124112. writer.writeLiteral(s);
  124113. setLastNonTriviaPosition(s, /*force*/ true);
  124114. }
  124115. function getTextPos() {
  124116. return writer.getTextPos();
  124117. }
  124118. function getLine() {
  124119. return writer.getLine();
  124120. }
  124121. function getColumn() {
  124122. return writer.getColumn();
  124123. }
  124124. function getIndent() {
  124125. return writer.getIndent();
  124126. }
  124127. function isAtStartOfLine() {
  124128. return writer.isAtStartOfLine();
  124129. }
  124130. function clear() {
  124131. writer.clear();
  124132. lastNonTriviaPosition = 0;
  124133. }
  124134. return {
  124135. onEmitNode: onEmitNode,
  124136. onBeforeEmitNodeArray: onBeforeEmitNodeArray,
  124137. onAfterEmitNodeArray: onAfterEmitNodeArray,
  124138. onBeforeEmitToken: onBeforeEmitToken,
  124139. onAfterEmitToken: onAfterEmitToken,
  124140. write: write,
  124141. writeComment: writeComment,
  124142. writeKeyword: writeKeyword,
  124143. writeOperator: writeOperator,
  124144. writePunctuation: writePunctuation,
  124145. writeTrailingSemicolon: writeTrailingSemicolon,
  124146. writeParameter: writeParameter,
  124147. writeProperty: writeProperty,
  124148. writeSpace: writeSpace,
  124149. writeStringLiteral: writeStringLiteral,
  124150. writeSymbol: writeSymbol,
  124151. writeLine: writeLine,
  124152. increaseIndent: increaseIndent,
  124153. decreaseIndent: decreaseIndent,
  124154. getText: getText,
  124155. rawWrite: rawWrite,
  124156. writeLiteral: writeLiteral,
  124157. getTextPos: getTextPos,
  124158. getLine: getLine,
  124159. getColumn: getColumn,
  124160. getIndent: getIndent,
  124161. isAtStartOfLine: isAtStartOfLine,
  124162. hasTrailingComment: function () { return writer.hasTrailingComment(); },
  124163. hasTrailingWhitespace: function () { return writer.hasTrailingWhitespace(); },
  124164. clear: clear
  124165. };
  124166. }
  124167. function getInsertionPositionAtSourceFileTop(sourceFile) {
  124168. var lastPrologue;
  124169. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  124170. var node = _a[_i];
  124171. if (ts.isPrologueDirective(node)) {
  124172. lastPrologue = node;
  124173. }
  124174. else {
  124175. break;
  124176. }
  124177. }
  124178. var position = 0;
  124179. var text = sourceFile.text;
  124180. if (lastPrologue) {
  124181. position = lastPrologue.end;
  124182. advancePastLineBreak();
  124183. return position;
  124184. }
  124185. var shebang = ts.getShebang(text);
  124186. if (shebang !== undefined) {
  124187. position = shebang.length;
  124188. advancePastLineBreak();
  124189. }
  124190. var ranges = ts.getLeadingCommentRanges(text, position);
  124191. if (!ranges)
  124192. return position;
  124193. // Find the first attached comment to the first node and add before it
  124194. var lastComment;
  124195. var firstNodeLine;
  124196. for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) {
  124197. var range = ranges_1[_b];
  124198. if (range.kind === 3 /* MultiLineCommentTrivia */) {
  124199. if (ts.isPinnedComment(text, range.pos)) {
  124200. lastComment = { range: range, pinnedOrTripleSlash: true };
  124201. continue;
  124202. }
  124203. }
  124204. else if (ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) {
  124205. lastComment = { range: range, pinnedOrTripleSlash: true };
  124206. continue;
  124207. }
  124208. if (lastComment) {
  124209. // Always insert after pinned or triple slash comments
  124210. if (lastComment.pinnedOrTripleSlash)
  124211. break;
  124212. // There was a blank line between the last comment and this comment.
  124213. // This comment is not part of the copyright comments
  124214. var commentLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
  124215. var lastCommentEndLine = sourceFile.getLineAndCharacterOfPosition(lastComment.range.end).line;
  124216. if (commentLine >= lastCommentEndLine + 2)
  124217. break;
  124218. }
  124219. if (sourceFile.statements.length) {
  124220. if (firstNodeLine === undefined)
  124221. firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line;
  124222. var commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
  124223. if (firstNodeLine < commentEndLine + 2)
  124224. break;
  124225. }
  124226. lastComment = { range: range, pinnedOrTripleSlash: false };
  124227. }
  124228. if (lastComment) {
  124229. position = lastComment.range.end;
  124230. advancePastLineBreak();
  124231. }
  124232. return position;
  124233. function advancePastLineBreak() {
  124234. if (position < text.length) {
  124235. var charCode = text.charCodeAt(position);
  124236. if (ts.isLineBreak(charCode)) {
  124237. position++;
  124238. if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) {
  124239. position++;
  124240. }
  124241. }
  124242. }
  124243. }
  124244. }
  124245. function isValidLocationToAddComment(sourceFile, position) {
  124246. return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position);
  124247. }
  124248. textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment;
  124249. function needSemicolonBetween(a, b) {
  124250. return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 154 /* ComputedPropertyName */
  124251. || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[`
  124252. }
  124253. var deleteDeclaration;
  124254. (function (deleteDeclaration_1) {
  124255. function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) {
  124256. switch (node.kind) {
  124257. case 156 /* Parameter */: {
  124258. var oldFunction = node.parent;
  124259. if (ts.isArrowFunction(oldFunction) &&
  124260. oldFunction.parameters.length === 1 &&
  124261. !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) {
  124262. // Lambdas with exactly one parameter are special because, after removal, there
  124263. // must be an empty parameter list (i.e. `()`) and this won't necessarily be the
  124264. // case if the parameter is simply removed (e.g. in `x => 1`).
  124265. changes.replaceNodeWithText(sourceFile, node, "()");
  124266. }
  124267. else {
  124268. deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
  124269. }
  124270. break;
  124271. }
  124272. case 254 /* ImportDeclaration */:
  124273. var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isImportDeclaration);
  124274. deleteNode(changes, sourceFile, node,
  124275. // For first import, leave header comment in place
  124276. isFirstImport ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
  124277. break;
  124278. case 191 /* BindingElement */:
  124279. var pattern = node.parent;
  124280. var preserveComma = pattern.kind === 190 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements);
  124281. if (preserveComma) {
  124282. deleteNode(changes, sourceFile, node);
  124283. }
  124284. else {
  124285. deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
  124286. }
  124287. break;
  124288. case 242 /* VariableDeclaration */:
  124289. deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
  124290. break;
  124291. case 155 /* TypeParameter */:
  124292. deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
  124293. break;
  124294. case 258 /* ImportSpecifier */:
  124295. var namedImports = node.parent;
  124296. if (namedImports.elements.length === 1) {
  124297. deleteImportBinding(changes, sourceFile, namedImports);
  124298. }
  124299. else {
  124300. deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
  124301. }
  124302. break;
  124303. case 256 /* NamespaceImport */:
  124304. deleteImportBinding(changes, sourceFile, node);
  124305. break;
  124306. default:
  124307. if (ts.isImportClause(node.parent) && node.parent.name === node) {
  124308. deleteDefaultImport(changes, sourceFile, node.parent);
  124309. }
  124310. else if (ts.isCallLikeExpression(node.parent)) {
  124311. deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
  124312. }
  124313. else {
  124314. deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
  124315. }
  124316. }
  124317. }
  124318. deleteDeclaration_1.deleteDeclaration = deleteDeclaration;
  124319. function deleteDefaultImport(changes, sourceFile, importClause) {
  124320. if (!importClause.namedBindings) {
  124321. // Delete the whole import
  124322. deleteNode(changes, sourceFile, importClause.parent);
  124323. }
  124324. else {
  124325. // import |d,| * as ns from './file'
  124326. var start = importClause.name.getStart(sourceFile);
  124327. var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end);
  124328. if (nextToken && nextToken.kind === 27 /* CommaToken */) {
  124329. // shift first non-whitespace position after comma to the start position of the node
  124330. var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true);
  124331. changes.deleteRange(sourceFile, { pos: start, end: end });
  124332. }
  124333. else {
  124334. deleteNode(changes, sourceFile, importClause.name);
  124335. }
  124336. }
  124337. }
  124338. function deleteImportBinding(changes, sourceFile, node) {
  124339. if (node.parent.name) {
  124340. // Delete named imports while preserving the default import
  124341. // import d|, * as ns| from './file'
  124342. // import d|, { a }| from './file'
  124343. var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1));
  124344. changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
  124345. }
  124346. else {
  124347. // Delete the entire import declaration
  124348. // |import * as ns from './file'|
  124349. // |import { a } from './file'|
  124350. var importDecl = ts.getAncestor(node, 254 /* ImportDeclaration */);
  124351. deleteNode(changes, sourceFile, importDecl);
  124352. }
  124353. }
  124354. function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
  124355. var parent = node.parent;
  124356. if (parent.kind === 280 /* CatchClause */) {
  124357. // TODO: There's currently no unused diagnostic for this, could be a suggestion
  124358. changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile));
  124359. return;
  124360. }
  124361. if (parent.declarations.length !== 1) {
  124362. deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
  124363. return;
  124364. }
  124365. var gp = parent.parent;
  124366. switch (gp.kind) {
  124367. case 232 /* ForOfStatement */:
  124368. case 231 /* ForInStatement */:
  124369. changes.replaceNode(sourceFile, node, ts.createObjectLiteral());
  124370. break;
  124371. case 230 /* ForStatement */:
  124372. deleteNode(changes, sourceFile, parent);
  124373. break;
  124374. case 225 /* VariableStatement */:
  124375. deleteNode(changes, sourceFile, gp);
  124376. break;
  124377. default:
  124378. ts.Debug.assertNever(gp);
  124379. }
  124380. }
  124381. })(deleteDeclaration || (deleteDeclaration = {}));
  124382. /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
  124383. // Exported for tests only! (TODO: improve tests to not need this)
  124384. function deleteNode(changes, sourceFile, node, options) {
  124385. if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
  124386. var startPosition = getAdjustedStartPosition(sourceFile, node, options);
  124387. var endPosition = getAdjustedEndPosition(sourceFile, node, options);
  124388. changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  124389. }
  124390. textChanges_3.deleteNode = deleteNode;
  124391. function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
  124392. var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile));
  124393. var index = ts.indexOfNode(containingList, node);
  124394. ts.Debug.assert(index !== -1);
  124395. if (containingList.length === 1) {
  124396. deleteNode(changes, sourceFile, node);
  124397. return;
  124398. }
  124399. // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node.
  124400. // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`.
  124401. ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
  124402. deletedNodesInLists.add(node);
  124403. changes.deleteRange(sourceFile, {
  124404. pos: startPositionToDeleteNodeInList(sourceFile, node),
  124405. end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]),
  124406. });
  124407. }
  124408. })(textChanges = ts.textChanges || (ts.textChanges = {}));
  124409. })(ts || (ts = {}));
  124410. /* @internal */
  124411. var ts;
  124412. (function (ts) {
  124413. var codefix;
  124414. (function (codefix) {
  124415. var errorCodeToFixes = ts.createMultiMap();
  124416. var fixIdToRegistration = ts.createMap();
  124417. function diagnosticToString(diag) {
  124418. return ts.isArray(diag)
  124419. ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1))
  124420. : ts.getLocaleSpecificMessage(diag);
  124421. }
  124422. function createCodeFixActionWithoutFixAll(fixName, changes, description) {
  124423. return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined);
  124424. }
  124425. codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll;
  124426. function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) {
  124427. return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command);
  124428. }
  124429. codefix.createCodeFixAction = createCodeFixAction;
  124430. function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) {
  124431. return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined };
  124432. }
  124433. function registerCodeFix(reg) {
  124434. for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) {
  124435. var error = _a[_i];
  124436. errorCodeToFixes.add(String(error), reg);
  124437. }
  124438. if (reg.fixIds) {
  124439. for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) {
  124440. var fixId = _c[_b];
  124441. ts.Debug.assert(!fixIdToRegistration.has(fixId));
  124442. fixIdToRegistration.set(fixId, reg);
  124443. }
  124444. }
  124445. }
  124446. codefix.registerCodeFix = registerCodeFix;
  124447. function getSupportedErrorCodes() {
  124448. return ts.arrayFrom(errorCodeToFixes.keys());
  124449. }
  124450. codefix.getSupportedErrorCodes = getSupportedErrorCodes;
  124451. function removeFixIdIfFixAllUnavailable(registration, diagnostics) {
  124452. var errorCodes = registration.errorCodes;
  124453. var maybeFixableDiagnostics = 0;
  124454. for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
  124455. var diag = diagnostics_1[_i];
  124456. if (ts.contains(errorCodes, diag.code))
  124457. maybeFixableDiagnostics++;
  124458. if (maybeFixableDiagnostics > 1)
  124459. break;
  124460. }
  124461. var fixAllUnavailable = maybeFixableDiagnostics < 2;
  124462. return function (_a) {
  124463. var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]);
  124464. return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription });
  124465. };
  124466. }
  124467. function getFixes(context) {
  124468. var diagnostics = getDiagnostics(context);
  124469. var registrations = errorCodeToFixes.get(String(context.errorCode));
  124470. return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); });
  124471. }
  124472. codefix.getFixes = getFixes;
  124473. function getAllFixes(context) {
  124474. // Currently fixId is always a string.
  124475. return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context);
  124476. }
  124477. codefix.getAllFixes = getAllFixes;
  124478. function createCombinedCodeActions(changes, commands) {
  124479. return { changes: changes, commands: commands };
  124480. }
  124481. codefix.createCombinedCodeActions = createCombinedCodeActions;
  124482. function createFileTextChanges(fileName, textChanges) {
  124483. return { fileName: fileName, textChanges: textChanges };
  124484. }
  124485. codefix.createFileTextChanges = createFileTextChanges;
  124486. function codeFixAll(context, errorCodes, use) {
  124487. var commands = [];
  124488. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); });
  124489. return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands);
  124490. }
  124491. codefix.codeFixAll = codeFixAll;
  124492. function eachDiagnostic(context, errorCodes, cb) {
  124493. for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) {
  124494. var diag = _a[_i];
  124495. if (ts.contains(errorCodes, diag.code)) {
  124496. cb(diag);
  124497. }
  124498. }
  124499. }
  124500. codefix.eachDiagnostic = eachDiagnostic;
  124501. function getDiagnostics(_a) {
  124502. var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken;
  124503. return program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken));
  124504. }
  124505. })(codefix = ts.codefix || (ts.codefix = {}));
  124506. })(ts || (ts = {}));
  124507. /* @internal */
  124508. var ts;
  124509. (function (ts) {
  124510. var refactor;
  124511. (function (refactor_1) {
  124512. // A map with the refactor code as key, the refactor itself as value
  124513. // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want
  124514. var refactors = ts.createMap();
  124515. /** @param name An unique code associated with each refactor. Does not have to be human-readable. */
  124516. function registerRefactor(name, refactor) {
  124517. refactors.set(name, refactor);
  124518. }
  124519. refactor_1.registerRefactor = registerRefactor;
  124520. function getApplicableRefactors(context) {
  124521. return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) {
  124522. return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context);
  124523. }));
  124524. }
  124525. refactor_1.getApplicableRefactors = getApplicableRefactors;
  124526. function getEditsForRefactor(context, refactorName, actionName) {
  124527. var refactor = refactors.get(refactorName);
  124528. return refactor && refactor.getEditsForAction(context, actionName);
  124529. }
  124530. refactor_1.getEditsForRefactor = getEditsForRefactor;
  124531. })(refactor = ts.refactor || (ts.refactor = {}));
  124532. })(ts || (ts = {}));
  124533. /* @internal */
  124534. var ts;
  124535. (function (ts) {
  124536. var codefix;
  124537. (function (codefix) {
  124538. var fixId = "addConvertToUnknownForNonOverlappingTypes";
  124539. var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code];
  124540. codefix.registerCodeFix({
  124541. errorCodes: errorCodes,
  124542. getCodeActions: function (context) {
  124543. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
  124544. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)];
  124545. },
  124546. fixIds: [fixId],
  124547. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
  124548. });
  124549. function makeChange(changeTracker, sourceFile, pos) {
  124550. var token = ts.getTokenAtPosition(sourceFile, pos);
  124551. var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); }), "Expected to find an assertion expression");
  124552. var replacement = ts.isAsExpression(assertion)
  124553. ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(148 /* UnknownKeyword */))
  124554. : ts.createTypeAssertion(ts.createKeywordTypeNode(148 /* UnknownKeyword */), assertion.expression);
  124555. changeTracker.replaceNode(sourceFile, assertion.expression, replacement);
  124556. }
  124557. })(codefix = ts.codefix || (ts.codefix = {}));
  124558. })(ts || (ts = {}));
  124559. /* @internal */
  124560. var ts;
  124561. (function (ts) {
  124562. var codefix;
  124563. (function (codefix) {
  124564. codefix.registerCodeFix({
  124565. errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code],
  124566. getCodeActions: function (context) {
  124567. var sourceFile = context.sourceFile;
  124568. var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
  124569. var exportDeclaration = ts.createExportDeclaration(
  124570. /*decorators*/ undefined,
  124571. /*modifiers*/ undefined, ts.createNamedExports([]),
  124572. /*moduleSpecifier*/ undefined,
  124573. /*isTypeOnly*/ false);
  124574. changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration);
  124575. });
  124576. return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)];
  124577. },
  124578. });
  124579. })(codefix = ts.codefix || (ts.codefix = {}));
  124580. })(ts || (ts = {}));
  124581. /* @internal */
  124582. var ts;
  124583. (function (ts) {
  124584. var codefix;
  124585. (function (codefix) {
  124586. var fixId = "addMissingAwait";
  124587. var propertyAccessCode = ts.Diagnostics.Property_0_does_not_exist_on_type_1.code;
  124588. var callableConstructableErrorCodes = [
  124589. ts.Diagnostics.This_expression_is_not_callable.code,
  124590. ts.Diagnostics.This_expression_is_not_constructable.code,
  124591. ];
  124592. var errorCodes = __spreadArrays([
  124593. ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  124594. ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  124595. ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  124596. ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code,
  124597. ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code,
  124598. ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code,
  124599. ts.Diagnostics.Type_0_is_not_an_array_type.code,
  124600. ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code,
  124601. ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code,
  124602. ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  124603. ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  124604. ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  124605. ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code,
  124606. ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  124607. propertyAccessCode
  124608. ], callableConstructableErrorCodes);
  124609. codefix.registerCodeFix({
  124610. fixIds: [fixId],
  124611. errorCodes: errorCodes,
  124612. getCodeActions: function (context) {
  124613. var sourceFile = context.sourceFile, errorCode = context.errorCode, span = context.span, cancellationToken = context.cancellationToken, program = context.program;
  124614. var expression = getFixableErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program);
  124615. if (!expression) {
  124616. return;
  124617. }
  124618. var checker = context.program.getTypeChecker();
  124619. var trackChanges = function (cb) { return ts.textChanges.ChangeTracker.with(context, cb); };
  124620. return ts.compact([
  124621. getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges),
  124622. getUseSiteFix(context, expression, errorCode, checker, trackChanges)
  124623. ]);
  124624. },
  124625. getAllCodeActions: function (context) {
  124626. var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
  124627. var checker = context.program.getTypeChecker();
  124628. var fixedDeclarations = ts.createMap();
  124629. return codefix.codeFixAll(context, errorCodes, function (t, diagnostic) {
  124630. var expression = getFixableErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program);
  124631. if (!expression) {
  124632. return;
  124633. }
  124634. var trackChanges = function (cb) { return (cb(t), []); };
  124635. return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations)
  124636. || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations);
  124637. });
  124638. },
  124639. });
  124640. function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
  124641. var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
  124642. var awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker);
  124643. if (awaitableInitializers) {
  124644. var initializerChanges = trackChanges(function (t) {
  124645. ts.forEach(awaitableInitializers.initializers, function (_a) {
  124646. var expression = _a.expression;
  124647. return makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
  124648. });
  124649. if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) {
  124650. makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
  124651. }
  124652. });
  124653. // No fix-all because it will already be included once with the use site fix,
  124654. // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes.
  124655. return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1
  124656. ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name]
  124657. : ts.Diagnostics.Add_await_to_initializers);
  124658. }
  124659. }
  124660. function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
  124661. var changes = trackChanges(function (t) { return makeChange(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations); });
  124662. return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_await, fixId, ts.Diagnostics.Fix_all_expressions_possibly_missing_await);
  124663. }
  124664. function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) {
  124665. var checker = program.getDiagnosticsProducingTypeChecker();
  124666. var diagnostics = checker.getDiagnostics(sourceFile, cancellationToken);
  124667. return ts.some(diagnostics, function (_a) {
  124668. var start = _a.start, length = _a.length, relatedInformation = _a.relatedInformation, code = _a.code;
  124669. return ts.isNumber(start) && ts.isNumber(length) && ts.textSpansEqual({ start: start, length: length }, span) &&
  124670. code === errorCode &&
  124671. !!relatedInformation &&
  124672. ts.some(relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_forget_to_use_await.code; });
  124673. });
  124674. }
  124675. function getFixableErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) {
  124676. var token = ts.getTokenAtPosition(sourceFile, span.start);
  124677. // Checker has already done work to determine that await might be possible, and has attached
  124678. // related info to the node, so start by finding the expression that exactly matches up
  124679. // with the diagnostic range.
  124680. var expression = ts.findAncestor(token, function (node) {
  124681. if (node.getStart(sourceFile) < span.start || node.getEnd() > ts.textSpanEnd(span)) {
  124682. return "quit";
  124683. }
  124684. return ts.isExpression(node) && ts.textSpansEqual(span, ts.createTextSpanFromNode(node, sourceFile));
  124685. });
  124686. return expression
  124687. && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program)
  124688. && isInsideAwaitableBody(expression) ? expression : undefined;
  124689. }
  124690. function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) {
  124691. var identifiers = getIdentifiersFromErrorSpanExpression(expression, checker);
  124692. if (!identifiers) {
  124693. return;
  124694. }
  124695. var isCompleteFix = identifiers.isCompleteFix;
  124696. var initializers;
  124697. var _loop_11 = function (identifier) {
  124698. var symbol = checker.getSymbolAtLocation(identifier);
  124699. if (!symbol) {
  124700. return "continue";
  124701. }
  124702. var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration);
  124703. var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier);
  124704. var variableStatement = ts.getAncestor(declaration, 225 /* VariableStatement */);
  124705. if (!declaration || !variableStatement ||
  124706. declaration.type ||
  124707. !declaration.initializer ||
  124708. variableStatement.getSourceFile() !== sourceFile ||
  124709. ts.hasModifier(variableStatement, 1 /* Export */) ||
  124710. !variableName ||
  124711. !isInsideAwaitableBody(declaration.initializer)) {
  124712. isCompleteFix = false;
  124713. return "continue";
  124714. }
  124715. var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken);
  124716. var isUsedElsewhere = ts.FindAllReferences.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, function (reference) {
  124717. return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker);
  124718. });
  124719. if (isUsedElsewhere) {
  124720. isCompleteFix = false;
  124721. return "continue";
  124722. }
  124723. (initializers || (initializers = [])).push({
  124724. expression: declaration.initializer,
  124725. declarationSymbol: symbol,
  124726. });
  124727. };
  124728. for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) {
  124729. var identifier = _a[_i];
  124730. _loop_11(identifier);
  124731. }
  124732. return initializers && {
  124733. initializers: initializers,
  124734. needsSecondPassForFixAll: !isCompleteFix,
  124735. };
  124736. }
  124737. function getIdentifiersFromErrorSpanExpression(expression, checker) {
  124738. if (ts.isPropertyAccessExpression(expression.parent) && ts.isIdentifier(expression.parent.expression)) {
  124739. return { identifiers: [expression.parent.expression], isCompleteFix: true };
  124740. }
  124741. if (ts.isIdentifier(expression)) {
  124742. return { identifiers: [expression], isCompleteFix: true };
  124743. }
  124744. if (ts.isBinaryExpression(expression)) {
  124745. var sides = void 0;
  124746. var isCompleteFix = true;
  124747. for (var _i = 0, _a = [expression.left, expression.right]; _i < _a.length; _i++) {
  124748. var side = _a[_i];
  124749. var type = checker.getTypeAtLocation(side);
  124750. if (checker.getPromisedTypeOfPromise(type)) {
  124751. if (!ts.isIdentifier(side)) {
  124752. isCompleteFix = false;
  124753. continue;
  124754. }
  124755. (sides || (sides = [])).push(side);
  124756. }
  124757. }
  124758. return sides && { identifiers: sides, isCompleteFix: isCompleteFix };
  124759. }
  124760. }
  124761. function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) {
  124762. var errorNode = ts.isPropertyAccessExpression(reference.parent) ? reference.parent.name :
  124763. ts.isBinaryExpression(reference.parent) ? reference.parent :
  124764. reference;
  124765. var diagnostic = ts.find(diagnostics, function (diagnostic) {
  124766. return diagnostic.start === errorNode.getStart(sourceFile) &&
  124767. diagnostic.start + diagnostic.length === errorNode.getEnd();
  124768. });
  124769. return diagnostic && ts.contains(errorCodes, diagnostic.code) ||
  124770. // A Promise is usually not correct in a binary expression (it’s not valid
  124771. // in an arithmetic expression and an equality comparison seems unusual),
  124772. // but if the other side of the binary expression has an error, the side
  124773. // is typed `any` which will squash the error that would identify this
  124774. // Promise as an invalid operand. So if the whole binary expression is
  124775. // typed `any` as a result, there is a strong likelihood that this Promise
  124776. // is accidentally missing `await`.
  124777. checker.getTypeAtLocation(errorNode).flags & 1 /* Any */;
  124778. }
  124779. function isInsideAwaitableBody(node) {
  124780. return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) {
  124781. return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor ||
  124782. ts.isBlock(ancestor) && (ancestor.parent.kind === 244 /* FunctionDeclaration */ ||
  124783. ancestor.parent.kind === 201 /* FunctionExpression */ ||
  124784. ancestor.parent.kind === 202 /* ArrowFunction */ ||
  124785. ancestor.parent.kind === 161 /* MethodDeclaration */);
  124786. });
  124787. }
  124788. function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) {
  124789. if (ts.isBinaryExpression(insertionSite)) {
  124790. for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) {
  124791. var side = _a[_i];
  124792. if (fixedDeclarations && ts.isIdentifier(side)) {
  124793. var symbol = checker.getSymbolAtLocation(side);
  124794. if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
  124795. continue;
  124796. }
  124797. }
  124798. var type = checker.getTypeAtLocation(side);
  124799. var newNode = checker.getPromisedTypeOfPromise(type) ? ts.createAwait(side) : side;
  124800. changeTracker.replaceNode(sourceFile, side, newNode);
  124801. }
  124802. }
  124803. else if (errorCode === propertyAccessCode && ts.isPropertyAccessExpression(insertionSite.parent)) {
  124804. if (fixedDeclarations && ts.isIdentifier(insertionSite.parent.expression)) {
  124805. var symbol = checker.getSymbolAtLocation(insertionSite.parent.expression);
  124806. if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
  124807. return;
  124808. }
  124809. }
  124810. changeTracker.replaceNode(sourceFile, insertionSite.parent.expression, ts.createParen(ts.createAwait(insertionSite.parent.expression)));
  124811. insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
  124812. }
  124813. else if (ts.contains(callableConstructableErrorCodes, errorCode) && ts.isCallOrNewExpression(insertionSite.parent)) {
  124814. if (fixedDeclarations && ts.isIdentifier(insertionSite)) {
  124815. var symbol = checker.getSymbolAtLocation(insertionSite);
  124816. if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
  124817. return;
  124818. }
  124819. }
  124820. changeTracker.replaceNode(sourceFile, insertionSite, ts.createParen(ts.createAwait(insertionSite)));
  124821. insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile);
  124822. }
  124823. else {
  124824. if (fixedDeclarations && ts.isVariableDeclaration(insertionSite.parent) && ts.isIdentifier(insertionSite.parent.name)) {
  124825. var symbol = checker.getSymbolAtLocation(insertionSite.parent.name);
  124826. if (symbol && !ts.addToSeen(fixedDeclarations, ts.getSymbolId(symbol))) {
  124827. return;
  124828. }
  124829. }
  124830. changeTracker.replaceNode(sourceFile, insertionSite, ts.createAwait(insertionSite));
  124831. }
  124832. }
  124833. function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) {
  124834. var precedingToken = ts.findPrecedingToken(beforeNode.pos, sourceFile);
  124835. if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
  124836. changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";");
  124837. }
  124838. }
  124839. })(codefix = ts.codefix || (ts.codefix = {}));
  124840. })(ts || (ts = {}));
  124841. /* @internal */
  124842. var ts;
  124843. (function (ts) {
  124844. var codefix;
  124845. (function (codefix) {
  124846. var fixId = "addMissingConst";
  124847. var errorCodes = [
  124848. ts.Diagnostics.Cannot_find_name_0.code,
  124849. ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code
  124850. ];
  124851. codefix.registerCodeFix({
  124852. errorCodes: errorCodes,
  124853. getCodeActions: function (context) {
  124854. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start, context.program); });
  124855. if (changes.length > 0) {
  124856. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_const_to_unresolved_variable, fixId, ts.Diagnostics.Add_const_to_all_unresolved_variables)];
  124857. }
  124858. },
  124859. fixIds: [fixId],
  124860. getAllCodeActions: function (context) {
  124861. var fixedNodes = new ts.NodeSet();
  124862. return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start, context.program, fixedNodes); });
  124863. },
  124864. });
  124865. function makeChange(changeTracker, sourceFile, pos, program, fixedNodes) {
  124866. var token = ts.getTokenAtPosition(sourceFile, pos);
  124867. var forInitializer = ts.findAncestor(token, function (node) {
  124868. return ts.isForInOrOfStatement(node.parent) ? node.parent.initializer === node :
  124869. isPossiblyPartOfDestructuring(node) ? false : "quit";
  124870. });
  124871. if (forInitializer)
  124872. return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes);
  124873. var parent = token.parent;
  124874. if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) {
  124875. return applyChange(changeTracker, token, sourceFile, fixedNodes);
  124876. }
  124877. if (ts.isArrayLiteralExpression(parent)) {
  124878. var checker_1 = program.getTypeChecker();
  124879. if (!ts.every(parent.elements, function (element) { return arrayElementCouldBeVariableDeclaration(element, checker_1); })) {
  124880. return;
  124881. }
  124882. return applyChange(changeTracker, parent, sourceFile, fixedNodes);
  124883. }
  124884. var commaExpression = ts.findAncestor(token, function (node) {
  124885. return ts.isExpressionStatement(node.parent) ? true :
  124886. isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit";
  124887. });
  124888. if (commaExpression) {
  124889. var checker = program.getTypeChecker();
  124890. if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) {
  124891. return;
  124892. }
  124893. return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes);
  124894. }
  124895. }
  124896. function applyChange(changeTracker, initializer, sourceFile, fixedNodes) {
  124897. if (!fixedNodes || fixedNodes.tryAdd(initializer)) {
  124898. changeTracker.insertModifierBefore(sourceFile, 81 /* ConstKeyword */, initializer);
  124899. }
  124900. }
  124901. function isPossiblyPartOfDestructuring(node) {
  124902. switch (node.kind) {
  124903. case 75 /* Identifier */:
  124904. case 192 /* ArrayLiteralExpression */:
  124905. case 193 /* ObjectLiteralExpression */:
  124906. case 281 /* PropertyAssignment */:
  124907. case 282 /* ShorthandPropertyAssignment */:
  124908. return true;
  124909. default:
  124910. return false;
  124911. }
  124912. }
  124913. function arrayElementCouldBeVariableDeclaration(expression, checker) {
  124914. var identifier = ts.isIdentifier(expression) ? expression :
  124915. ts.isAssignmentExpression(expression, /*excludeCompoundAssignment*/ true) && ts.isIdentifier(expression.left) ? expression.left :
  124916. undefined;
  124917. return !!identifier && !checker.getSymbolAtLocation(identifier);
  124918. }
  124919. function isPossiblyPartOfCommaSeperatedInitializer(node) {
  124920. switch (node.kind) {
  124921. case 75 /* Identifier */:
  124922. case 209 /* BinaryExpression */:
  124923. case 27 /* CommaToken */:
  124924. return true;
  124925. default:
  124926. return false;
  124927. }
  124928. }
  124929. function expressionCouldBeVariableDeclaration(expression, checker) {
  124930. if (!ts.isBinaryExpression(expression)) {
  124931. return false;
  124932. }
  124933. if (expression.operatorToken.kind === 27 /* CommaToken */) {
  124934. return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); });
  124935. }
  124936. return expression.operatorToken.kind === 62 /* EqualsToken */
  124937. && ts.isIdentifier(expression.left)
  124938. && !checker.getSymbolAtLocation(expression.left);
  124939. }
  124940. })(codefix = ts.codefix || (ts.codefix = {}));
  124941. })(ts || (ts = {}));
  124942. /* @internal */
  124943. var ts;
  124944. (function (ts) {
  124945. var codefix;
  124946. (function (codefix) {
  124947. var fixId = "addMissingDeclareProperty";
  124948. var errorCodes = [
  124949. ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code,
  124950. ];
  124951. codefix.registerCodeFix({
  124952. errorCodes: errorCodes,
  124953. getCodeActions: function (context) {
  124954. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
  124955. if (changes.length > 0) {
  124956. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Prefix_with_declare, fixId, ts.Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)];
  124957. }
  124958. },
  124959. fixIds: [fixId],
  124960. getAllCodeActions: function (context) {
  124961. var fixedNodes = new ts.NodeSet();
  124962. return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start, fixedNodes); });
  124963. },
  124964. });
  124965. function makeChange(changeTracker, sourceFile, pos, fixedNodes) {
  124966. var token = ts.getTokenAtPosition(sourceFile, pos);
  124967. if (!ts.isIdentifier(token)) {
  124968. return;
  124969. }
  124970. var declaration = token.parent;
  124971. if (declaration.kind === 159 /* PropertyDeclaration */ &&
  124972. (!fixedNodes || fixedNodes.tryAdd(declaration))) {
  124973. changeTracker.insertModifierBefore(sourceFile, 130 /* DeclareKeyword */, declaration);
  124974. }
  124975. }
  124976. })(codefix = ts.codefix || (ts.codefix = {}));
  124977. })(ts || (ts = {}));
  124978. /* @internal */
  124979. var ts;
  124980. (function (ts) {
  124981. var codefix;
  124982. (function (codefix) {
  124983. var fixId = "addMissingInvocationForDecorator";
  124984. var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code];
  124985. codefix.registerCodeFix({
  124986. errorCodes: errorCodes,
  124987. getCodeActions: function (context) {
  124988. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
  124989. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)];
  124990. },
  124991. fixIds: [fixId],
  124992. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
  124993. });
  124994. function makeChange(changeTracker, sourceFile, pos) {
  124995. var token = ts.getTokenAtPosition(sourceFile, pos);
  124996. var decorator = ts.findAncestor(token, ts.isDecorator);
  124997. ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
  124998. var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
  124999. changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
  125000. }
  125001. })(codefix = ts.codefix || (ts.codefix = {}));
  125002. })(ts || (ts = {}));
  125003. /* @internal */
  125004. var ts;
  125005. (function (ts) {
  125006. var codefix;
  125007. (function (codefix) {
  125008. var fixId = "addNameToNamelessParameter";
  125009. var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
  125010. codefix.registerCodeFix({
  125011. errorCodes: errorCodes,
  125012. getCodeActions: function (context) {
  125013. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
  125014. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
  125015. },
  125016. fixIds: [fixId],
  125017. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
  125018. });
  125019. function makeChange(changeTracker, sourceFile, pos) {
  125020. var token = ts.getTokenAtPosition(sourceFile, pos);
  125021. if (!ts.isIdentifier(token)) {
  125022. return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind));
  125023. }
  125024. var param = token.parent;
  125025. if (!ts.isParameter(param)) {
  125026. return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind));
  125027. }
  125028. var i = param.parent.parameters.indexOf(param);
  125029. ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
  125030. ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
  125031. var replacement = ts.createParameter(
  125032. /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
  125033. changeTracker.replaceNode(sourceFile, token, replacement);
  125034. }
  125035. })(codefix = ts.codefix || (ts.codefix = {}));
  125036. })(ts || (ts = {}));
  125037. /* @internal */
  125038. var ts;
  125039. (function (ts) {
  125040. var codefix;
  125041. (function (codefix) {
  125042. var fixId = "annotateWithTypeFromJSDoc";
  125043. var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
  125044. codefix.registerCodeFix({
  125045. errorCodes: errorCodes,
  125046. getCodeActions: function (context) {
  125047. var decl = getDeclaration(context.sourceFile, context.span.start);
  125048. if (!decl)
  125049. return;
  125050. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
  125051. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)];
  125052. },
  125053. fixIds: [fixId],
  125054. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  125055. var decl = getDeclaration(diag.file, diag.start);
  125056. if (decl)
  125057. doChange(changes, diag.file, decl);
  125058. }); },
  125059. });
  125060. function getDeclaration(file, pos) {
  125061. var name = ts.getTokenAtPosition(file, pos);
  125062. // For an arrow function with no name, 'name' lands on the first parameter.
  125063. return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
  125064. }
  125065. function parameterShouldGetTypeFromJSDoc(node) {
  125066. return isDeclarationWithType(node) && hasUsableJSDoc(node);
  125067. }
  125068. codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
  125069. function hasUsableJSDoc(decl) {
  125070. return ts.isFunctionLikeDeclaration(decl)
  125071. ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
  125072. : !decl.type && !!ts.getJSDocType(decl);
  125073. }
  125074. function doChange(changes, sourceFile, decl) {
  125075. if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
  125076. if (!decl.typeParameters) {
  125077. var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
  125078. if (typeParameters.length)
  125079. changes.insertTypeParameters(sourceFile, decl, typeParameters);
  125080. }
  125081. var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile);
  125082. if (needParens)
  125083. changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */));
  125084. for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) {
  125085. var param = _a[_i];
  125086. if (!param.type) {
  125087. var paramType = ts.getJSDocType(param);
  125088. if (paramType)
  125089. changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType));
  125090. }
  125091. }
  125092. if (needParens)
  125093. changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */));
  125094. if (!decl.type) {
  125095. var returnType = ts.getJSDocReturnType(decl);
  125096. if (returnType)
  125097. changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType));
  125098. }
  125099. }
  125100. else {
  125101. var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl), "A JSDocType for this declaration should exist"); // If not defined, shouldn't have been an error to fix
  125102. ts.Debug.assert(!decl.type, "The JSDocType decl should have a type"); // If defined, shouldn't have been an error to fix.
  125103. changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType));
  125104. }
  125105. }
  125106. function isDeclarationWithType(node) {
  125107. return ts.isFunctionLikeDeclaration(node) ||
  125108. node.kind === 242 /* VariableDeclaration */ ||
  125109. node.kind === 158 /* PropertySignature */ ||
  125110. node.kind === 159 /* PropertyDeclaration */;
  125111. }
  125112. function transformJSDocType(node) {
  125113. switch (node.kind) {
  125114. case 295 /* JSDocAllType */:
  125115. case 296 /* JSDocUnknownType */:
  125116. return ts.createTypeReferenceNode("any", ts.emptyArray);
  125117. case 299 /* JSDocOptionalType */:
  125118. return transformJSDocOptionalType(node);
  125119. case 298 /* JSDocNonNullableType */:
  125120. return transformJSDocType(node.type);
  125121. case 297 /* JSDocNullableType */:
  125122. return transformJSDocNullableType(node);
  125123. case 301 /* JSDocVariadicType */:
  125124. return transformJSDocVariadicType(node);
  125125. case 300 /* JSDocFunctionType */:
  125126. return transformJSDocFunctionType(node);
  125127. case 169 /* TypeReference */:
  125128. return transformJSDocTypeReference(node);
  125129. default:
  125130. var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217
  125131. ts.setEmitFlags(visited, 1 /* SingleLine */);
  125132. return visited;
  125133. }
  125134. }
  125135. function transformJSDocOptionalType(node) {
  125136. return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
  125137. }
  125138. function transformJSDocNullableType(node) {
  125139. return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
  125140. }
  125141. function transformJSDocVariadicType(node) {
  125142. return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
  125143. }
  125144. function transformJSDocFunctionType(node) {
  125145. return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type);
  125146. }
  125147. function transformJSDocParameter(node) {
  125148. var index = node.parent.parameters.indexOf(node);
  125149. var isRest = node.type.kind === 301 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
  125150. var name = node.name || (isRest ? "rest" : "arg" + index);
  125151. var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
  125152. return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
  125153. }
  125154. function transformJSDocTypeReference(node) {
  125155. var name = node.typeName;
  125156. var args = node.typeArguments;
  125157. if (ts.isIdentifier(node.typeName)) {
  125158. if (ts.isJSDocIndexSignature(node)) {
  125159. return transformJSDocIndexSignature(node);
  125160. }
  125161. var text = node.typeName.text;
  125162. switch (node.typeName.text) {
  125163. case "String":
  125164. case "Boolean":
  125165. case "Object":
  125166. case "Number":
  125167. text = text.toLowerCase();
  125168. break;
  125169. case "array":
  125170. case "date":
  125171. case "promise":
  125172. text = text[0].toUpperCase() + text.slice(1);
  125173. break;
  125174. }
  125175. name = ts.createIdentifier(text);
  125176. if ((text === "Array" || text === "Promise") && !node.typeArguments) {
  125177. args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
  125178. }
  125179. else {
  125180. args = ts.visitNodes(node.typeArguments, transformJSDocType);
  125181. }
  125182. }
  125183. return ts.createTypeReferenceNode(name, args);
  125184. }
  125185. function transformJSDocIndexSignature(node) {
  125186. var index = ts.createParameter(
  125187. /*decorators*/ undefined,
  125188. /*modifiers*/ undefined,
  125189. /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 140 /* NumberKeyword */ ? "n" : "s",
  125190. /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 140 /* NumberKeyword */ ? "number" : "string", []),
  125191. /*initializer*/ undefined);
  125192. var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
  125193. ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
  125194. return indexSignature;
  125195. }
  125196. })(codefix = ts.codefix || (ts.codefix = {}));
  125197. })(ts || (ts = {}));
  125198. /* @internal */
  125199. var ts;
  125200. (function (ts) {
  125201. var codefix;
  125202. (function (codefix) {
  125203. var fixId = "inferFromUsage";
  125204. var errorCodes = [
  125205. // Variable declarations
  125206. ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
  125207. // Variable uses
  125208. ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code,
  125209. // Parameter declarations
  125210. ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
  125211. ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
  125212. // Get Accessor declarations
  125213. ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
  125214. ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
  125215. // Set Accessor declarations
  125216. ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
  125217. // Property declarations
  125218. ts.Diagnostics.Member_0_implicitly_has_an_1_type.code,
  125219. //// Suggestions
  125220. // Variable declarations
  125221. ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code,
  125222. // Variable uses
  125223. ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  125224. // Parameter declarations
  125225. ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  125226. ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code,
  125227. // Get Accessor declarations
  125228. ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code,
  125229. ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code,
  125230. // Set Accessor declarations
  125231. ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code,
  125232. // Property declarations
  125233. ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  125234. // Function expressions and declarations
  125235. ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code,
  125236. ];
  125237. codefix.registerCodeFix({
  125238. errorCodes: errorCodes,
  125239. getCodeActions: function (context) {
  125240. var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences;
  125241. var token = ts.getTokenAtPosition(sourceFile, start);
  125242. var declaration;
  125243. var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); });
  125244. var name = declaration && ts.getNameOfDeclaration(declaration);
  125245. return !name || changes.length === 0 ? undefined
  125246. : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)];
  125247. },
  125248. fixIds: [fixId],
  125249. getAllCodeActions: function (context) {
  125250. var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences;
  125251. var markSeen = ts.nodeSeenTracker();
  125252. return codefix.codeFixAll(context, errorCodes, function (changes, err) {
  125253. doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences);
  125254. });
  125255. },
  125256. });
  125257. function getDiagnostic(errorCode, token) {
  125258. switch (errorCode) {
  125259. case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
  125260. case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
  125261. return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217
  125262. case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
  125263. case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
  125264. return ts.Diagnostics.Infer_parameter_types_from_usage;
  125265. case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
  125266. return ts.Diagnostics.Infer_this_type_of_0_from_usage;
  125267. default:
  125268. return ts.Diagnostics.Infer_type_of_0_from_usage;
  125269. }
  125270. }
  125271. /** Map suggestion code to error code */
  125272. function mapSuggestionDiagnostic(errorCode) {
  125273. switch (errorCode) {
  125274. case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code:
  125275. return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code;
  125276. case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
  125277. return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code;
  125278. case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
  125279. return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code;
  125280. case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
  125281. return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code;
  125282. case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code:
  125283. return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code;
  125284. case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code:
  125285. return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code;
  125286. case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code:
  125287. return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code;
  125288. case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
  125289. return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code;
  125290. }
  125291. return errorCode;
  125292. }
  125293. function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) {
  125294. if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 104 /* ThisKeyword */) {
  125295. return undefined;
  125296. }
  125297. var parent = token.parent;
  125298. errorCode = mapSuggestionDiagnostic(errorCode);
  125299. switch (errorCode) {
  125300. // Variable and Property declarations
  125301. case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
  125302. case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
  125303. if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
  125304. annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences);
  125305. return parent;
  125306. }
  125307. if (ts.isPropertyAccessExpression(parent)) {
  125308. var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
  125309. var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
  125310. if (typeNode) {
  125311. // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
  125312. var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
  125313. addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]);
  125314. }
  125315. return parent;
  125316. }
  125317. return undefined;
  125318. case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
  125319. var symbol = program.getTypeChecker().getSymbolAtLocation(token);
  125320. if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
  125321. annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences);
  125322. return symbol.valueDeclaration;
  125323. }
  125324. return undefined;
  125325. }
  125326. }
  125327. var containingFunction = ts.getContainingFunction(token);
  125328. if (containingFunction === undefined) {
  125329. return undefined;
  125330. }
  125331. switch (errorCode) {
  125332. // Parameter declarations
  125333. case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
  125334. if (ts.isSetAccessorDeclaration(containingFunction)) {
  125335. annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences);
  125336. return containingFunction;
  125337. }
  125338. // falls through
  125339. case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
  125340. if (markSeen(containingFunction)) {
  125341. var param = ts.cast(parent, ts.isParameter);
  125342. annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences);
  125343. return param;
  125344. }
  125345. return undefined;
  125346. // Get Accessor declarations
  125347. case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
  125348. case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
  125349. if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) {
  125350. annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences);
  125351. return containingFunction;
  125352. }
  125353. return undefined;
  125354. // Set Accessor declarations
  125355. case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
  125356. if (ts.isSetAccessorDeclaration(containingFunction)) {
  125357. annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences);
  125358. return containingFunction;
  125359. }
  125360. return undefined;
  125361. // Function 'this'
  125362. case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
  125363. if (ts.textChanges.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) {
  125364. annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken);
  125365. return containingFunction;
  125366. }
  125367. return undefined;
  125368. default:
  125369. return ts.Debug.fail(String(errorCode));
  125370. }
  125371. }
  125372. function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) {
  125373. if (ts.isIdentifier(declaration.name)) {
  125374. annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences);
  125375. }
  125376. }
  125377. function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) {
  125378. if (!ts.isIdentifier(parameterDeclaration.name)) {
  125379. return;
  125380. }
  125381. var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken);
  125382. ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match");
  125383. if (ts.isInJSFile(containingFunction)) {
  125384. annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host);
  125385. }
  125386. else {
  125387. var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile);
  125388. if (needParens)
  125389. changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */));
  125390. for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) {
  125391. var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type;
  125392. if (declaration && !declaration.type && !declaration.initializer) {
  125393. annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences);
  125394. }
  125395. }
  125396. if (needParens)
  125397. changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */));
  125398. }
  125399. }
  125400. function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) {
  125401. var references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken);
  125402. if (!references || !references.length) {
  125403. return;
  125404. }
  125405. var thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter();
  125406. var typeNode = ts.getTypeNodeIfAccessible(thisInference, containingFunction, program, host);
  125407. if (!typeNode) {
  125408. return;
  125409. }
  125410. if (ts.isInJSFile(containingFunction)) {
  125411. annotateJSDocThis(changes, sourceFile, containingFunction, typeNode);
  125412. }
  125413. else {
  125414. changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode);
  125415. }
  125416. }
  125417. function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) {
  125418. addJSDocTags(changes, sourceFile, containingFunction, [
  125419. ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)),
  125420. ]);
  125421. }
  125422. function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) {
  125423. var param = ts.firstOrUndefined(setAccessorDeclaration.parameters);
  125424. if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) {
  125425. var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken);
  125426. if (type === program.getTypeChecker().getAnyType()) {
  125427. type = inferTypeForVariableFromUsage(param.name, program, cancellationToken);
  125428. }
  125429. if (ts.isInJSFile(setAccessorDeclaration)) {
  125430. annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host);
  125431. }
  125432. else {
  125433. annotate(changes, sourceFile, param, type, program, host, formatContext, preferences);
  125434. }
  125435. }
  125436. }
  125437. function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) {
  125438. var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
  125439. if (typeNode) {
  125440. if (ts.isInJSFile(sourceFile) && declaration.kind !== 158 /* PropertySignature */) {
  125441. var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
  125442. if (!parent) {
  125443. return;
  125444. }
  125445. var typeExpression = ts.createJSDocTypeExpression(typeNode);
  125446. var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, "");
  125447. addJSDocTags(changes, sourceFile, parent, [typeTag]);
  125448. }
  125449. else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) {
  125450. changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
  125451. }
  125452. }
  125453. }
  125454. function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) {
  125455. var _a;
  125456. if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) {
  125457. // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible
  125458. var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol;
  125459. // Symbol for the left-most thing after the dot
  125460. if (moduleSymbol) {
  125461. var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol;
  125462. var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences);
  125463. if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) {
  125464. for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) {
  125465. var change = _b[_i];
  125466. var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName));
  125467. changes.pushRaw(file, change);
  125468. }
  125469. return true;
  125470. }
  125471. }
  125472. }
  125473. return false;
  125474. }
  125475. function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) {
  125476. var signature = parameterInferences.length && parameterInferences[0].declaration.parent;
  125477. if (!signature) {
  125478. return;
  125479. }
  125480. var paramTags = ts.mapDefined(parameterInferences, function (inference) {
  125481. var param = inference.declaration;
  125482. // only infer parameters that have (1) no type and (2) an accessible inferred type
  125483. if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
  125484. return;
  125485. var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
  125486. var name = ts.getSynthesizedClone(param.name);
  125487. ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
  125488. return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
  125489. });
  125490. addJSDocTags(changes, sourceFile, signature, paramTags);
  125491. }
  125492. function addJSDocTags(changes, sourceFile, parent, newTags) {
  125493. var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; });
  125494. var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; });
  125495. var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) {
  125496. var merged = tryMergeJsdocTags(tag, newTag);
  125497. if (merged)
  125498. oldTags[i] = merged;
  125499. return !!merged;
  125500. }); });
  125501. var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray(__spreadArrays((oldTags || ts.emptyArray), unmergedNewTags)));
  125502. var jsDocNode = parent.kind === 202 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
  125503. jsDocNode.jsDoc = parent.jsDoc;
  125504. jsDocNode.jsDocCache = parent.jsDocCache;
  125505. changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
  125506. }
  125507. function getJsDocNodeForArrowFunction(signature) {
  125508. if (signature.parent.kind === 159 /* PropertyDeclaration */) {
  125509. return signature.parent;
  125510. }
  125511. return signature.parent.parent;
  125512. }
  125513. function tryMergeJsdocTags(oldTag, newTag) {
  125514. if (oldTag.kind !== newTag.kind) {
  125515. return undefined;
  125516. }
  125517. switch (oldTag.kind) {
  125518. case 316 /* JSDocParameterTag */: {
  125519. var oldParam = oldTag;
  125520. var newParam = newTag;
  125521. return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
  125522. ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
  125523. : undefined;
  125524. }
  125525. case 317 /* JSDocReturnTag */:
  125526. return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
  125527. }
  125528. }
  125529. function getReferences(token, program, cancellationToken) {
  125530. // Position shouldn't matter since token is not a SourceFile.
  125531. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
  125532. return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined;
  125533. });
  125534. }
  125535. function inferTypeForVariableFromUsage(token, program, cancellationToken) {
  125536. var references = getReferences(token, program, cancellationToken);
  125537. return inferTypeFromReferences(program, references, cancellationToken).single();
  125538. }
  125539. function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) {
  125540. var references = getFunctionReferences(func, sourceFile, program, cancellationToken);
  125541. return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) ||
  125542. func.parameters.map(function (p) { return ({
  125543. declaration: p,
  125544. type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType()
  125545. }); });
  125546. }
  125547. function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) {
  125548. var searchToken;
  125549. switch (containingFunction.kind) {
  125550. case 162 /* Constructor */:
  125551. searchToken = ts.findChildOfKind(containingFunction, 129 /* ConstructorKeyword */, sourceFile);
  125552. break;
  125553. case 202 /* ArrowFunction */:
  125554. case 201 /* FunctionExpression */:
  125555. var parent = containingFunction.parent;
  125556. searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ?
  125557. parent.name :
  125558. containingFunction.name;
  125559. break;
  125560. case 244 /* FunctionDeclaration */:
  125561. case 161 /* MethodDeclaration */:
  125562. searchToken = containingFunction.name;
  125563. break;
  125564. }
  125565. if (!searchToken) {
  125566. return undefined;
  125567. }
  125568. return getReferences(searchToken, program, cancellationToken);
  125569. }
  125570. function inferTypeFromReferences(program, references, cancellationToken) {
  125571. var checker = program.getTypeChecker();
  125572. var builtinConstructors = {
  125573. string: function () { return checker.getStringType(); },
  125574. number: function () { return checker.getNumberType(); },
  125575. Array: function (t) { return checker.createArrayType(t); },
  125576. Promise: function (t) { return checker.createPromiseType(t); },
  125577. };
  125578. var builtins = [
  125579. checker.getStringType(),
  125580. checker.getNumberType(),
  125581. checker.createArrayType(checker.getAnyType()),
  125582. checker.createPromiseType(checker.getAnyType()),
  125583. ];
  125584. return {
  125585. single: single,
  125586. parameters: parameters,
  125587. thisParameter: thisParameter,
  125588. };
  125589. function createEmptyUsage() {
  125590. return {
  125591. isNumber: undefined,
  125592. isString: undefined,
  125593. isNumberOrString: undefined,
  125594. candidateTypes: undefined,
  125595. properties: undefined,
  125596. calls: undefined,
  125597. constructs: undefined,
  125598. numberIndex: undefined,
  125599. stringIndex: undefined,
  125600. candidateThisTypes: undefined,
  125601. inferredTypes: undefined,
  125602. };
  125603. }
  125604. function combineUsages(usages) {
  125605. var combinedProperties = ts.createUnderscoreEscapedMap();
  125606. for (var _i = 0, usages_1 = usages; _i < usages_1.length; _i++) {
  125607. var u = usages_1[_i];
  125608. if (u.properties) {
  125609. u.properties.forEach(function (p, name) {
  125610. if (!combinedProperties.has(name)) {
  125611. combinedProperties.set(name, []);
  125612. }
  125613. combinedProperties.get(name).push(p);
  125614. });
  125615. }
  125616. }
  125617. var properties = ts.createUnderscoreEscapedMap();
  125618. combinedProperties.forEach(function (ps, name) {
  125619. properties.set(name, combineUsages(ps));
  125620. });
  125621. return {
  125622. isNumber: usages.some(function (u) { return u.isNumber; }),
  125623. isString: usages.some(function (u) { return u.isString; }),
  125624. isNumberOrString: usages.some(function (u) { return u.isNumberOrString; }),
  125625. candidateTypes: ts.flatMap(usages, function (u) { return u.candidateTypes; }),
  125626. properties: properties,
  125627. calls: ts.flatMap(usages, function (u) { return u.calls; }),
  125628. constructs: ts.flatMap(usages, function (u) { return u.constructs; }),
  125629. numberIndex: ts.forEach(usages, function (u) { return u.numberIndex; }),
  125630. stringIndex: ts.forEach(usages, function (u) { return u.stringIndex; }),
  125631. candidateThisTypes: ts.flatMap(usages, function (u) { return u.candidateThisTypes; }),
  125632. inferredTypes: undefined,
  125633. };
  125634. }
  125635. function single() {
  125636. return combineTypes(inferTypesFromReferencesSingle(references));
  125637. }
  125638. function parameters(declaration) {
  125639. if (references.length === 0 || !declaration.parameters) {
  125640. return undefined;
  125641. }
  125642. var usage = createEmptyUsage();
  125643. for (var _i = 0, references_2 = references; _i < references_2.length; _i++) {
  125644. var reference = references_2[_i];
  125645. cancellationToken.throwIfCancellationRequested();
  125646. calculateUsageOfNode(reference, usage);
  125647. }
  125648. var calls = __spreadArrays(usage.constructs || [], usage.calls || []);
  125649. return declaration.parameters.map(function (parameter, parameterIndex) {
  125650. var types = [];
  125651. var isRest = ts.isRestParameter(parameter);
  125652. var isOptional = false;
  125653. for (var _i = 0, calls_1 = calls; _i < calls_1.length; _i++) {
  125654. var call = calls_1[_i];
  125655. if (call.argumentTypes.length <= parameterIndex) {
  125656. isOptional = ts.isInJSFile(declaration);
  125657. types.push(checker.getUndefinedType());
  125658. }
  125659. else if (isRest) {
  125660. for (var i = parameterIndex; i < call.argumentTypes.length; i++) {
  125661. types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i]));
  125662. }
  125663. }
  125664. else {
  125665. types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex]));
  125666. }
  125667. }
  125668. if (ts.isIdentifier(parameter.name)) {
  125669. var inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken));
  125670. types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
  125671. }
  125672. var type = combineTypes(types);
  125673. return {
  125674. type: isRest ? checker.createArrayType(type) : type,
  125675. isOptional: isOptional && !isRest,
  125676. declaration: parameter
  125677. };
  125678. });
  125679. }
  125680. function thisParameter() {
  125681. var usage = createEmptyUsage();
  125682. for (var _i = 0, references_3 = references; _i < references_3.length; _i++) {
  125683. var reference = references_3[_i];
  125684. cancellationToken.throwIfCancellationRequested();
  125685. calculateUsageOfNode(reference, usage);
  125686. }
  125687. return combineTypes(usage.candidateThisTypes || ts.emptyArray);
  125688. }
  125689. function inferTypesFromReferencesSingle(references) {
  125690. var usage = createEmptyUsage();
  125691. for (var _i = 0, references_4 = references; _i < references_4.length; _i++) {
  125692. var reference = references_4[_i];
  125693. cancellationToken.throwIfCancellationRequested();
  125694. calculateUsageOfNode(reference, usage);
  125695. }
  125696. return inferTypes(usage);
  125697. }
  125698. function calculateUsageOfNode(node, usage) {
  125699. while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
  125700. node = node.parent;
  125701. }
  125702. switch (node.parent.kind) {
  125703. case 226 /* ExpressionStatement */:
  125704. addCandidateType(usage, checker.getVoidType());
  125705. break;
  125706. case 208 /* PostfixUnaryExpression */:
  125707. usage.isNumber = true;
  125708. break;
  125709. case 207 /* PrefixUnaryExpression */:
  125710. inferTypeFromPrefixUnaryExpression(node.parent, usage);
  125711. break;
  125712. case 209 /* BinaryExpression */:
  125713. inferTypeFromBinaryExpression(node, node.parent, usage);
  125714. break;
  125715. case 277 /* CaseClause */:
  125716. case 278 /* DefaultClause */:
  125717. inferTypeFromSwitchStatementLabel(node.parent, usage);
  125718. break;
  125719. case 196 /* CallExpression */:
  125720. case 197 /* NewExpression */:
  125721. if (node.parent.expression === node) {
  125722. inferTypeFromCallExpression(node.parent, usage);
  125723. }
  125724. else {
  125725. inferTypeFromContextualType(node, usage);
  125726. }
  125727. break;
  125728. case 194 /* PropertyAccessExpression */:
  125729. inferTypeFromPropertyAccessExpression(node.parent, usage);
  125730. break;
  125731. case 195 /* ElementAccessExpression */:
  125732. inferTypeFromPropertyElementExpression(node.parent, node, usage);
  125733. break;
  125734. case 281 /* PropertyAssignment */:
  125735. case 282 /* ShorthandPropertyAssignment */:
  125736. inferTypeFromPropertyAssignment(node.parent, usage);
  125737. break;
  125738. case 159 /* PropertyDeclaration */:
  125739. inferTypeFromPropertyDeclaration(node.parent, usage);
  125740. break;
  125741. case 242 /* VariableDeclaration */: {
  125742. var _a = node.parent, name = _a.name, initializer = _a.initializer;
  125743. if (node === name) {
  125744. if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error.
  125745. addCandidateType(usage, checker.getTypeAtLocation(initializer));
  125746. }
  125747. break;
  125748. }
  125749. }
  125750. // falls through
  125751. default:
  125752. return inferTypeFromContextualType(node, usage);
  125753. }
  125754. }
  125755. function inferTypeFromContextualType(node, usage) {
  125756. if (ts.isExpressionNode(node)) {
  125757. addCandidateType(usage, checker.getContextualType(node));
  125758. }
  125759. }
  125760. function inferTypeFromPrefixUnaryExpression(node, usage) {
  125761. switch (node.operator) {
  125762. case 45 /* PlusPlusToken */:
  125763. case 46 /* MinusMinusToken */:
  125764. case 40 /* MinusToken */:
  125765. case 54 /* TildeToken */:
  125766. usage.isNumber = true;
  125767. break;
  125768. case 39 /* PlusToken */:
  125769. usage.isNumberOrString = true;
  125770. break;
  125771. // case SyntaxKind.ExclamationToken:
  125772. // no inferences here;
  125773. }
  125774. }
  125775. function inferTypeFromBinaryExpression(node, parent, usage) {
  125776. switch (parent.operatorToken.kind) {
  125777. // ExponentiationOperator
  125778. case 42 /* AsteriskAsteriskToken */:
  125779. // MultiplicativeOperator
  125780. // falls through
  125781. case 41 /* AsteriskToken */:
  125782. case 43 /* SlashToken */:
  125783. case 44 /* PercentToken */:
  125784. // ShiftOperator
  125785. // falls through
  125786. case 47 /* LessThanLessThanToken */:
  125787. case 48 /* GreaterThanGreaterThanToken */:
  125788. case 49 /* GreaterThanGreaterThanGreaterThanToken */:
  125789. // BitwiseOperator
  125790. // falls through
  125791. case 50 /* AmpersandToken */:
  125792. case 51 /* BarToken */:
  125793. case 52 /* CaretToken */:
  125794. // CompoundAssignmentOperator
  125795. // falls through
  125796. case 64 /* MinusEqualsToken */:
  125797. case 66 /* AsteriskAsteriskEqualsToken */:
  125798. case 65 /* AsteriskEqualsToken */:
  125799. case 67 /* SlashEqualsToken */:
  125800. case 68 /* PercentEqualsToken */:
  125801. case 72 /* AmpersandEqualsToken */:
  125802. case 73 /* BarEqualsToken */:
  125803. case 74 /* CaretEqualsToken */:
  125804. case 69 /* LessThanLessThanEqualsToken */:
  125805. case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
  125806. case 70 /* GreaterThanGreaterThanEqualsToken */:
  125807. // AdditiveOperator
  125808. // falls through
  125809. case 40 /* MinusToken */:
  125810. // RelationalOperator
  125811. // falls through
  125812. case 29 /* LessThanToken */:
  125813. case 32 /* LessThanEqualsToken */:
  125814. case 31 /* GreaterThanToken */:
  125815. case 33 /* GreaterThanEqualsToken */:
  125816. var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
  125817. if (operandType.flags & 1056 /* EnumLike */) {
  125818. addCandidateType(usage, operandType);
  125819. }
  125820. else {
  125821. usage.isNumber = true;
  125822. }
  125823. break;
  125824. case 63 /* PlusEqualsToken */:
  125825. case 39 /* PlusToken */:
  125826. var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
  125827. if (otherOperandType.flags & 1056 /* EnumLike */) {
  125828. addCandidateType(usage, otherOperandType);
  125829. }
  125830. else if (otherOperandType.flags & 296 /* NumberLike */) {
  125831. usage.isNumber = true;
  125832. }
  125833. else if (otherOperandType.flags & 132 /* StringLike */) {
  125834. usage.isString = true;
  125835. }
  125836. else if (otherOperandType.flags & 1 /* Any */) {
  125837. // do nothing, maybe we'll learn something elsewhere
  125838. }
  125839. else {
  125840. usage.isNumberOrString = true;
  125841. }
  125842. break;
  125843. // AssignmentOperators
  125844. case 62 /* EqualsToken */:
  125845. case 34 /* EqualsEqualsToken */:
  125846. case 36 /* EqualsEqualsEqualsToken */:
  125847. case 37 /* ExclamationEqualsEqualsToken */:
  125848. case 35 /* ExclamationEqualsToken */:
  125849. addCandidateType(usage, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left));
  125850. break;
  125851. case 97 /* InKeyword */:
  125852. if (node === parent.left) {
  125853. usage.isString = true;
  125854. }
  125855. break;
  125856. // LogicalOperator Or NullishCoalescing
  125857. case 56 /* BarBarToken */:
  125858. case 60 /* QuestionQuestionToken */:
  125859. if (node === parent.left &&
  125860. (node.parent.parent.kind === 242 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
  125861. // var x = x || {};
  125862. // TODO: use getFalsyflagsOfType
  125863. addCandidateType(usage, checker.getTypeAtLocation(parent.right));
  125864. }
  125865. break;
  125866. case 55 /* AmpersandAmpersandToken */:
  125867. case 27 /* CommaToken */:
  125868. case 98 /* InstanceOfKeyword */:
  125869. // nothing to infer here
  125870. break;
  125871. }
  125872. }
  125873. function inferTypeFromSwitchStatementLabel(parent, usage) {
  125874. addCandidateType(usage, checker.getTypeAtLocation(parent.parent.parent.expression));
  125875. }
  125876. function inferTypeFromCallExpression(parent, usage) {
  125877. var call = {
  125878. argumentTypes: [],
  125879. return_: createEmptyUsage()
  125880. };
  125881. if (parent.arguments) {
  125882. for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) {
  125883. var argument = _a[_i];
  125884. call.argumentTypes.push(checker.getTypeAtLocation(argument));
  125885. }
  125886. }
  125887. calculateUsageOfNode(parent, call.return_);
  125888. if (parent.kind === 196 /* CallExpression */) {
  125889. (usage.calls || (usage.calls = [])).push(call);
  125890. }
  125891. else {
  125892. (usage.constructs || (usage.constructs = [])).push(call);
  125893. }
  125894. }
  125895. function inferTypeFromPropertyAccessExpression(parent, usage) {
  125896. var name = ts.escapeLeadingUnderscores(parent.name.text);
  125897. if (!usage.properties) {
  125898. usage.properties = ts.createUnderscoreEscapedMap();
  125899. }
  125900. var propertyUsage = usage.properties.get(name) || createEmptyUsage();
  125901. calculateUsageOfNode(parent, propertyUsage);
  125902. usage.properties.set(name, propertyUsage);
  125903. }
  125904. function inferTypeFromPropertyElementExpression(parent, node, usage) {
  125905. if (node === parent.argumentExpression) {
  125906. usage.isNumberOrString = true;
  125907. return;
  125908. }
  125909. else {
  125910. var indexType = checker.getTypeAtLocation(parent.argumentExpression);
  125911. var indexUsage = createEmptyUsage();
  125912. calculateUsageOfNode(parent, indexUsage);
  125913. if (indexType.flags & 296 /* NumberLike */) {
  125914. usage.numberIndex = indexUsage;
  125915. }
  125916. else {
  125917. usage.stringIndex = indexUsage;
  125918. }
  125919. }
  125920. }
  125921. function inferTypeFromPropertyAssignment(assignment, usage) {
  125922. var nodeWithRealType = ts.isVariableDeclaration(assignment.parent.parent) ?
  125923. assignment.parent.parent :
  125924. assignment.parent;
  125925. addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType));
  125926. }
  125927. function inferTypeFromPropertyDeclaration(declaration, usage) {
  125928. addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent));
  125929. }
  125930. function removeLowPriorityInferences(inferences, priorities) {
  125931. var toRemove = [];
  125932. for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
  125933. var i = inferences_1[_i];
  125934. for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
  125935. var _b = priorities_1[_a], high = _b.high, low = _b.low;
  125936. if (high(i)) {
  125937. ts.Debug.assert(!low(i), "Priority can't have both low and high");
  125938. toRemove.push(low);
  125939. }
  125940. }
  125941. }
  125942. return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
  125943. }
  125944. function combineFromUsage(usage) {
  125945. return combineTypes(inferTypes(usage));
  125946. }
  125947. function combineTypes(inferences) {
  125948. if (!inferences.length)
  125949. return checker.getAnyType();
  125950. // 1. string or number individually override string | number
  125951. // 2. non-any, non-void overrides any or void
  125952. // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
  125953. var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
  125954. var priorities = [
  125955. {
  125956. high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
  125957. low: function (t) { return t === stringNumber; }
  125958. },
  125959. {
  125960. high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
  125961. low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
  125962. },
  125963. {
  125964. high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(ts.getObjectFlags(t) & 16 /* Anonymous */); },
  125965. low: function (t) { return !!(ts.getObjectFlags(t) & 16 /* Anonymous */); }
  125966. }
  125967. ];
  125968. var good = removeLowPriorityInferences(inferences, priorities);
  125969. var anons = good.filter(function (i) { return ts.getObjectFlags(i) & 16 /* Anonymous */; });
  125970. if (anons.length) {
  125971. good = good.filter(function (i) { return !(ts.getObjectFlags(i) & 16 /* Anonymous */); });
  125972. good.push(combineAnonymousTypes(anons));
  125973. }
  125974. return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */));
  125975. }
  125976. function combineAnonymousTypes(anons) {
  125977. if (anons.length === 1) {
  125978. return anons[0];
  125979. }
  125980. var calls = [];
  125981. var constructs = [];
  125982. var stringIndices = [];
  125983. var numberIndices = [];
  125984. var stringIndexReadonly = false;
  125985. var numberIndexReadonly = false;
  125986. var props = ts.createMultiMap();
  125987. for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) {
  125988. var anon = anons_1[_i];
  125989. for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) {
  125990. var p = _b[_a];
  125991. props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration));
  125992. }
  125993. calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */));
  125994. constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */));
  125995. if (anon.stringIndexInfo) {
  125996. stringIndices.push(anon.stringIndexInfo.type);
  125997. stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly;
  125998. }
  125999. if (anon.numberIndexInfo) {
  126000. numberIndices.push(anon.numberIndexInfo.type);
  126001. numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly;
  126002. }
  126003. }
  126004. var members = ts.mapEntries(props, function (name, types) {
  126005. var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0;
  126006. var s = checker.createSymbol(4 /* Property */ | isOptional, name);
  126007. s.type = checker.getUnionType(types);
  126008. return [name, s];
  126009. });
  126010. return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined);
  126011. }
  126012. function inferTypes(usage) {
  126013. var types = [];
  126014. if (usage.isNumber) {
  126015. types.push(checker.getNumberType());
  126016. }
  126017. if (usage.isString) {
  126018. types.push(checker.getStringType());
  126019. }
  126020. if (usage.isNumberOrString) {
  126021. types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
  126022. }
  126023. if (usage.numberIndex) {
  126024. types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
  126025. }
  126026. if (usage.properties && usage.properties.size
  126027. || usage.calls && usage.calls.length
  126028. || usage.constructs && usage.constructs.length
  126029. || usage.stringIndex) {
  126030. types.push(inferStructuralType(usage));
  126031. }
  126032. types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
  126033. types.push.apply(types, inferNamedTypesFromProperties(usage));
  126034. return types;
  126035. }
  126036. function inferStructuralType(usage) {
  126037. var members = ts.createUnderscoreEscapedMap();
  126038. if (usage.properties) {
  126039. usage.properties.forEach(function (u, name) {
  126040. var symbol = checker.createSymbol(4 /* Property */, name);
  126041. symbol.type = combineFromUsage(u);
  126042. members.set(name, symbol);
  126043. });
  126044. }
  126045. var callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : [];
  126046. var constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : [];
  126047. var stringIndexInfo = usage.stringIndex && checker.createIndexInfo(combineFromUsage(usage.stringIndex), /*isReadonly*/ false);
  126048. return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217
  126049. }
  126050. function inferNamedTypesFromProperties(usage) {
  126051. if (!usage.properties || !usage.properties.size)
  126052. return [];
  126053. var types = builtins.filter(function (t) { return allPropertiesAreAssignableToUsage(t, usage); });
  126054. if (0 < types.length && types.length < 3) {
  126055. return types.map(function (t) { return inferInstantiationFromUsage(t, usage); });
  126056. }
  126057. return [];
  126058. }
  126059. function allPropertiesAreAssignableToUsage(type, usage) {
  126060. if (!usage.properties)
  126061. return false;
  126062. return !ts.forEachEntry(usage.properties, function (propUsage, name) {
  126063. var source = checker.getTypeOfPropertyOfType(type, name);
  126064. if (!source) {
  126065. return true;
  126066. }
  126067. if (propUsage.calls) {
  126068. var sigs = checker.getSignaturesOfType(source, 0 /* Call */);
  126069. return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls));
  126070. }
  126071. else {
  126072. return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage));
  126073. }
  126074. });
  126075. }
  126076. /**
  126077. * inference is limited to
  126078. * 1. generic types with a single parameter
  126079. * 2. inference to/from calls with a single signature
  126080. */
  126081. function inferInstantiationFromUsage(type, usage) {
  126082. if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !usage.properties) {
  126083. return type;
  126084. }
  126085. var generic = type.target;
  126086. var singleTypeParameter = ts.singleOrUndefined(generic.typeParameters);
  126087. if (!singleTypeParameter)
  126088. return type;
  126089. var types = [];
  126090. usage.properties.forEach(function (propUsage, name) {
  126091. var genericPropertyType = checker.getTypeOfPropertyOfType(generic, name);
  126092. ts.Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
  126093. types.push.apply(types, inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter));
  126094. });
  126095. return builtinConstructors[type.symbol.escapedName](combineTypes(types));
  126096. }
  126097. function inferTypeParameters(genericType, usageType, typeParameter) {
  126098. if (genericType === typeParameter) {
  126099. return [usageType];
  126100. }
  126101. else if (genericType.flags & 3145728 /* UnionOrIntersection */) {
  126102. return ts.flatMap(genericType.types, function (t) { return inferTypeParameters(t, usageType, typeParameter); });
  126103. }
  126104. else if (ts.getObjectFlags(genericType) & 4 /* Reference */ && ts.getObjectFlags(usageType) & 4 /* Reference */) {
  126105. // this is wrong because we need a reference to the targetType to, so we can check that it's also a reference
  126106. var genericArgs = checker.getTypeArguments(genericType);
  126107. var usageArgs = checker.getTypeArguments(usageType);
  126108. var types = [];
  126109. if (genericArgs && usageArgs) {
  126110. for (var i = 0; i < genericArgs.length; i++) {
  126111. if (usageArgs[i]) {
  126112. types.push.apply(types, inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter));
  126113. }
  126114. }
  126115. }
  126116. return types;
  126117. }
  126118. var genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */);
  126119. var usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */);
  126120. if (genericSigs.length === 1 && usageSigs.length === 1) {
  126121. return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter);
  126122. }
  126123. return [];
  126124. }
  126125. function inferFromSignatures(genericSig, usageSig, typeParameter) {
  126126. var types = [];
  126127. for (var i = 0; i < genericSig.parameters.length; i++) {
  126128. var genericParam = genericSig.parameters[i];
  126129. var usageParam = usageSig.parameters[i];
  126130. var isRest = genericSig.declaration && ts.isRestParameter(genericSig.declaration.parameters[i]);
  126131. if (!usageParam) {
  126132. break;
  126133. }
  126134. var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration);
  126135. var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType);
  126136. if (elementType) {
  126137. genericParamType = elementType;
  126138. }
  126139. var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration);
  126140. types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter));
  126141. }
  126142. var genericReturn = checker.getReturnTypeOfSignature(genericSig);
  126143. var usageReturn = checker.getReturnTypeOfSignature(usageSig);
  126144. types.push.apply(types, inferTypeParameters(genericReturn, usageReturn, typeParameter));
  126145. return types;
  126146. }
  126147. function getFunctionFromCalls(calls) {
  126148. return checker.createAnonymousType(undefined, ts.createSymbolTable(), [getSignatureFromCalls(calls)], ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
  126149. }
  126150. function getSignatureFromCalls(calls) {
  126151. var parameters = [];
  126152. var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; }));
  126153. var _loop_12 = function (i) {
  126154. var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i));
  126155. symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); }));
  126156. if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) {
  126157. symbol.flags |= 16777216 /* Optional */;
  126158. }
  126159. parameters.push(symbol);
  126160. };
  126161. for (var i = 0; i < length; i++) {
  126162. _loop_12(i);
  126163. }
  126164. var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; })));
  126165. // TODO: GH#18217
  126166. return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */);
  126167. }
  126168. function addCandidateType(usage, type) {
  126169. if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
  126170. (usage.candidateTypes || (usage.candidateTypes = [])).push(type);
  126171. }
  126172. }
  126173. function addCandidateThisType(usage, type) {
  126174. if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
  126175. (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type);
  126176. }
  126177. }
  126178. }
  126179. })(codefix = ts.codefix || (ts.codefix = {}));
  126180. })(ts || (ts = {}));
  126181. /* @internal */
  126182. var ts;
  126183. (function (ts) {
  126184. var codefix;
  126185. (function (codefix) {
  126186. var fixId = "convertFunctionToEs6Class";
  126187. var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
  126188. codefix.registerCodeFix({
  126189. errorCodes: errorCodes,
  126190. getCodeActions: function (context) {
  126191. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
  126192. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)];
  126193. },
  126194. fixIds: [fixId],
  126195. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
  126196. });
  126197. function doChange(changes, sourceFile, position, checker) {
  126198. var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position));
  126199. if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
  126200. // Bad input
  126201. return undefined;
  126202. }
  126203. var ctorDeclaration = ctorSymbol.valueDeclaration;
  126204. var precedingNode;
  126205. var newClassDeclaration;
  126206. switch (ctorDeclaration.kind) {
  126207. case 244 /* FunctionDeclaration */:
  126208. precedingNode = ctorDeclaration;
  126209. changes.delete(sourceFile, ctorDeclaration);
  126210. newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
  126211. break;
  126212. case 242 /* VariableDeclaration */:
  126213. precedingNode = ctorDeclaration.parent.parent;
  126214. newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
  126215. if (ctorDeclaration.parent.declarations.length === 1) {
  126216. ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
  126217. changes.delete(sourceFile, precedingNode);
  126218. }
  126219. else {
  126220. changes.delete(sourceFile, ctorDeclaration);
  126221. }
  126222. break;
  126223. }
  126224. if (!newClassDeclaration) {
  126225. return undefined;
  126226. }
  126227. ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
  126228. // Because the preceding node could be touched, we need to insert nodes before delete nodes.
  126229. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
  126230. function createClassElementsFromSymbol(symbol) {
  126231. var memberElements = [];
  126232. // all instance members are stored in the "member" array of symbol
  126233. if (symbol.members) {
  126234. symbol.members.forEach(function (member) {
  126235. var memberElement = createClassElement(member, /*modifiers*/ undefined);
  126236. if (memberElement) {
  126237. memberElements.push(memberElement);
  126238. }
  126239. });
  126240. }
  126241. // all static members are stored in the "exports" array of symbol
  126242. if (symbol.exports) {
  126243. symbol.exports.forEach(function (member) {
  126244. var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]);
  126245. if (memberElement) {
  126246. memberElements.push(memberElement);
  126247. }
  126248. });
  126249. }
  126250. return memberElements;
  126251. function shouldConvertDeclaration(_target, source) {
  126252. // Right now the only thing we can convert are function expressions - other values shouldn't get
  126253. // transformed. We can update this once ES public class properties are available.
  126254. return ts.isFunctionLike(source);
  126255. }
  126256. function createClassElement(symbol, modifiers) {
  126257. // Right now the only thing we can convert are function expressions, which are marked as methods
  126258. if (!(symbol.flags & 8192 /* Method */)) {
  126259. return;
  126260. }
  126261. var memberDeclaration = symbol.valueDeclaration;
  126262. var assignmentBinaryExpression = memberDeclaration.parent;
  126263. if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
  126264. return;
  126265. }
  126266. // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
  126267. var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */
  126268. ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
  126269. changes.delete(sourceFile, nodeToDelete);
  126270. if (!assignmentBinaryExpression.right) {
  126271. return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
  126272. /*type*/ undefined, /*initializer*/ undefined);
  126273. }
  126274. switch (assignmentBinaryExpression.right.kind) {
  126275. case 201 /* FunctionExpression */: {
  126276. var functionExpression = assignmentBinaryExpression.right;
  126277. var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */));
  126278. var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
  126279. /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
  126280. ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
  126281. return method;
  126282. }
  126283. case 202 /* ArrowFunction */: {
  126284. var arrowFunction = assignmentBinaryExpression.right;
  126285. var arrowFunctionBody = arrowFunction.body;
  126286. var bodyBlock = void 0;
  126287. // case 1: () => { return [1,2,3] }
  126288. if (arrowFunctionBody.kind === 223 /* Block */) {
  126289. bodyBlock = arrowFunctionBody;
  126290. }
  126291. // case 2: () => [1,2,3]
  126292. else {
  126293. bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
  126294. }
  126295. var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */));
  126296. var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
  126297. /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
  126298. ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
  126299. return method;
  126300. }
  126301. default: {
  126302. // Don't try to declare members in JavaScript files
  126303. if (ts.isSourceFileJS(sourceFile)) {
  126304. return;
  126305. }
  126306. var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
  126307. /*type*/ undefined, assignmentBinaryExpression.right);
  126308. ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
  126309. return prop;
  126310. }
  126311. }
  126312. }
  126313. }
  126314. function createClassFromVariableDeclaration(node) {
  126315. var initializer = node.initializer;
  126316. if (!initializer || initializer.kind !== 201 /* FunctionExpression */) {
  126317. return undefined;
  126318. }
  126319. if (node.name.kind !== 75 /* Identifier */) {
  126320. return undefined;
  126321. }
  126322. var memberElements = createClassElementsFromSymbol(node.symbol);
  126323. if (initializer.body) {
  126324. memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
  126325. }
  126326. var modifiers = getModifierKindFromSource(precedingNode, 89 /* ExportKeyword */);
  126327. var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
  126328. /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
  126329. // Don't call copyComments here because we'll already leave them in place
  126330. return cls;
  126331. }
  126332. function createClassFromFunctionDeclaration(node) {
  126333. var memberElements = createClassElementsFromSymbol(ctorSymbol);
  126334. if (node.body) {
  126335. memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
  126336. }
  126337. var modifiers = getModifierKindFromSource(node, 89 /* ExportKeyword */);
  126338. var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
  126339. /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
  126340. // Don't call copyComments here because we'll already leave them in place
  126341. return cls;
  126342. }
  126343. }
  126344. function getModifierKindFromSource(source, kind) {
  126345. return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
  126346. }
  126347. })(codefix = ts.codefix || (ts.codefix = {}));
  126348. })(ts || (ts = {}));
  126349. /* @internal */
  126350. var ts;
  126351. (function (ts) {
  126352. var codefix;
  126353. (function (codefix) {
  126354. var fixId = "convertToAsyncFunction";
  126355. var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code];
  126356. var codeActionSucceeded = true;
  126357. codefix.registerCodeFix({
  126358. errorCodes: errorCodes,
  126359. getCodeActions: function (context) {
  126360. codeActionSucceeded = true;
  126361. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); });
  126362. return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : [];
  126363. },
  126364. fixIds: [fixId],
  126365. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); },
  126366. });
  126367. var SynthBindingNameKind;
  126368. (function (SynthBindingNameKind) {
  126369. SynthBindingNameKind[SynthBindingNameKind["Identifier"] = 0] = "Identifier";
  126370. SynthBindingNameKind[SynthBindingNameKind["BindingPattern"] = 1] = "BindingPattern";
  126371. })(SynthBindingNameKind || (SynthBindingNameKind = {}));
  126372. function convertToAsyncFunction(changes, sourceFile, position, checker, context) {
  126373. // get the function declaration - returns a promise
  126374. var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
  126375. var functionToConvert;
  126376. // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name
  126377. if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) &&
  126378. tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
  126379. functionToConvert = tokenAtPosition.parent.initializer;
  126380. }
  126381. else {
  126382. functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration);
  126383. }
  126384. if (!functionToConvert) {
  126385. return;
  126386. }
  126387. var synthNamesMap = ts.createMap();
  126388. var originalTypeMap = ts.createMap();
  126389. var allVarNames = [];
  126390. var isInJavascript = ts.isInJSFile(functionToConvert);
  126391. var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
  126392. var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames);
  126393. var constIdentifiers = getConstIdentifiers(synthNamesMap);
  126394. var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray;
  126395. var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript };
  126396. if (!returnStatements.length) {
  126397. return;
  126398. }
  126399. // add the async keyword
  126400. changes.insertLastModifierBefore(sourceFile, 126 /* AsyncKeyword */, functionToConvert);
  126401. function startTransformation(node, nodeToReplace) {
  126402. var newNodes = transformExpression(node, transformer, node);
  126403. changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
  126404. }
  126405. var _loop_13 = function (statement) {
  126406. ts.forEachChild(statement, function visit(node) {
  126407. if (ts.isCallExpression(node)) {
  126408. startTransformation(node, statement);
  126409. }
  126410. else if (!ts.isFunctionLike(node)) {
  126411. ts.forEachChild(node, visit);
  126412. }
  126413. });
  126414. };
  126415. for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
  126416. var statement = returnStatements_1[_i];
  126417. _loop_13(statement);
  126418. }
  126419. }
  126420. function getReturnStatementsWithPromiseHandlers(body) {
  126421. var res = [];
  126422. ts.forEachReturnStatement(body, function (ret) {
  126423. if (ts.isReturnStatementWithFixablePromiseHandler(ret))
  126424. res.push(ret);
  126425. });
  126426. return res;
  126427. }
  126428. // Returns the identifiers that are never reassigned in the refactor
  126429. function getConstIdentifiers(synthNamesMap) {
  126430. var constIdentifiers = [];
  126431. synthNamesMap.forEach(function (val) {
  126432. if (val.numberOfAssignmentsOriginal === 0) {
  126433. constIdentifiers.push(val.identifier);
  126434. }
  126435. });
  126436. return constIdentifiers;
  126437. }
  126438. /*
  126439. Finds all of the expressions of promise type that should not be saved in a variable during the refactor
  126440. */
  126441. function getAllPromiseExpressionsToReturn(func, checker) {
  126442. if (!func.body) {
  126443. return ts.createMap();
  126444. }
  126445. var setOfExpressionsToReturn = ts.createMap();
  126446. ts.forEachChild(func.body, function visit(node) {
  126447. if (isPromiseReturningExpression(node, checker, "then")) {
  126448. setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
  126449. ts.forEach(node.arguments, visit);
  126450. }
  126451. else if (isPromiseReturningExpression(node, checker, "catch")) {
  126452. setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
  126453. // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned
  126454. ts.forEachChild(node, visit);
  126455. }
  126456. else if (isPromiseReturningExpression(node, checker)) {
  126457. setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
  126458. // don't recurse here, since we won't refactor any children or arguments of the expression
  126459. }
  126460. else {
  126461. ts.forEachChild(node, visit);
  126462. }
  126463. });
  126464. return setOfExpressionsToReturn;
  126465. }
  126466. /*
  126467. Returns true if node is a promise returning expression
  126468. If name is not undefined, node is a promise returning call of name
  126469. */
  126470. function isPromiseReturningExpression(node, checker, name) {
  126471. var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node);
  126472. var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name));
  126473. var nodeType = isExpressionOfName && checker.getTypeAtLocation(node);
  126474. return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType));
  126475. }
  126476. function declaredInFile(symbol, sourceFile) {
  126477. return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile;
  126478. }
  126479. /*
  126480. Renaming of identifiers may be neccesary as the refactor changes scopes -
  126481. This function collects all existing identifier names and names of identifiers that will be created in the refactor.
  126482. It then checks for any collisions and renames them through getSynthesizedDeepClone
  126483. */
  126484. function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) {
  126485. var identsToRenameMap = ts.createMap(); // key is the symbol id
  126486. var collidingSymbolMap = ts.createMap();
  126487. ts.forEachChild(nodeToRename, function visit(node) {
  126488. if (!ts.isIdentifier(node)) {
  126489. ts.forEachChild(node, visit);
  126490. return;
  126491. }
  126492. var symbol = checker.getSymbolAtLocation(node);
  126493. var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile);
  126494. if (symbol && isDefinedInFile) {
  126495. var type = checker.getTypeAtLocation(node);
  126496. var lastCallSignature = getLastCallSignature(type, checker);
  126497. var symbolIdString = ts.getSymbolId(symbol).toString();
  126498. // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg))
  126499. // Note - the choice of the last call signature is arbitrary
  126500. if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) {
  126501. var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters);
  126502. var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result");
  126503. var synthName = getNewNameIfConflict(ident, collidingSymbolMap);
  126504. synthNamesMap.set(symbolIdString, synthName);
  126505. allVarNames.push({ identifier: synthName.identifier, symbol: symbol });
  126506. addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol);
  126507. }
  126508. // we only care about identifiers that are parameters, declarations, or binding elements (don't care about other uses)
  126509. else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent) || ts.isBindingElement(node.parent))) {
  126510. var originalName = node.text;
  126511. var collidingSymbols = collidingSymbolMap.get(originalName);
  126512. // if the identifier name conflicts with a different identifier that we've already seen
  126513. if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) {
  126514. var newName = getNewNameIfConflict(node, collidingSymbolMap);
  126515. identsToRenameMap.set(symbolIdString, newName.identifier);
  126516. synthNamesMap.set(symbolIdString, newName);
  126517. allVarNames.push({ identifier: newName.identifier, symbol: symbol });
  126518. addNameToFrequencyMap(collidingSymbolMap, originalName, symbol);
  126519. }
  126520. else {
  126521. var identifier = ts.getSynthesizedDeepClone(node);
  126522. identsToRenameMap.set(symbolIdString, identifier);
  126523. synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier, [], allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/));
  126524. if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) {
  126525. allVarNames.push({ identifier: identifier, symbol: symbol });
  126526. addNameToFrequencyMap(collidingSymbolMap, originalName, symbol);
  126527. }
  126528. }
  126529. }
  126530. }
  126531. });
  126532. return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback);
  126533. function isExpressionOrCallOnTypePromise(child) {
  126534. var node = child.parent;
  126535. if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) {
  126536. var nodeType = checker.getTypeAtLocation(node);
  126537. var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType);
  126538. return !!isPromise;
  126539. }
  126540. return false;
  126541. }
  126542. function deepCloneCallback(node, clone) {
  126543. if (ts.isIdentifier(node)) {
  126544. var symbol = checker.getSymbolAtLocation(node);
  126545. var symboldIdString = symbol && ts.getSymbolId(symbol).toString();
  126546. var renameInfo = symbol && synthNamesMap.get(symboldIdString);
  126547. if (renameInfo) {
  126548. var type = checker.getTypeAtLocation(node);
  126549. originalType.set(ts.getNodeId(clone).toString(), type);
  126550. }
  126551. }
  126552. var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString());
  126553. if (val !== undefined) {
  126554. setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString());
  126555. setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val);
  126556. }
  126557. }
  126558. }
  126559. function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) {
  126560. if (renamedVarNameFrequencyMap.has(originalName)) {
  126561. renamedVarNameFrequencyMap.get(originalName).push(symbol);
  126562. }
  126563. else {
  126564. renamedVarNameFrequencyMap.set(originalName, [symbol]);
  126565. }
  126566. }
  126567. function getNewNameIfConflict(name, originalNames) {
  126568. var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length;
  126569. var numberOfAssignmentsOriginal = 0;
  126570. var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName);
  126571. return createSynthIdentifier(identifier, [], numberOfAssignmentsOriginal);
  126572. }
  126573. // dispatch function to recursively build the refactoring
  126574. // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts
  126575. function transformExpression(node, transformer, outermostParent, prevArgName) {
  126576. if (!node) {
  126577. return ts.emptyArray;
  126578. }
  126579. var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString());
  126580. var nodeType = originalType || transformer.checker.getTypeAtLocation(node);
  126581. if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) {
  126582. return transformThen(node, transformer, outermostParent, prevArgName);
  126583. }
  126584. else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) {
  126585. return transformCatch(node, transformer, prevArgName);
  126586. }
  126587. else if (ts.isPropertyAccessExpression(node)) {
  126588. return transformExpression(node.expression, transformer, outermostParent, prevArgName);
  126589. }
  126590. else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) {
  126591. return transformPromiseCall(node, transformer, prevArgName);
  126592. }
  126593. codeActionSucceeded = false;
  126594. return ts.emptyArray;
  126595. }
  126596. function transformCatch(node, transformer, prevArgName) {
  126597. var func = node.arguments[0];
  126598. var argName = getArgBindingName(func, transformer);
  126599. var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString());
  126600. var possibleNameForVarDecl;
  126601. /*
  126602. If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block)
  126603. To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap
  126604. We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step
  126605. */
  126606. if (prevArgName && !shouldReturn) {
  126607. if (isSynthIdentifier(prevArgName)) {
  126608. possibleNameForVarDecl = prevArgName;
  126609. transformer.synthNamesMap.forEach(function (val, key) {
  126610. if (val.identifier.text === prevArgName.identifier.text) {
  126611. var newSynthName = createUniqueSynthName(prevArgName);
  126612. transformer.synthNamesMap.set(key, newSynthName);
  126613. }
  126614. });
  126615. }
  126616. else {
  126617. possibleNameForVarDecl = createSynthIdentifier(ts.createOptimisticUniqueName("result"), prevArgName.types);
  126618. }
  126619. possibleNameForVarDecl.numberOfAssignmentsOriginal = 2; // Try block and catch block
  126620. // update the constIdentifiers list
  126621. if (transformer.constIdentifiers.some(function (elem) { return elem.text === possibleNameForVarDecl.identifier.text; })) {
  126622. transformer.constIdentifiers.push(createUniqueSynthName(possibleNameForVarDecl).identifier);
  126623. }
  126624. }
  126625. var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, possibleNameForVarDecl));
  126626. var transformationBody = getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer);
  126627. var catchArg = argName ? isSynthIdentifier(argName) ? argName.identifier.text : argName.bindingPattern : "e";
  126628. var catchVariableDeclaration = ts.createVariableDeclaration(catchArg);
  126629. var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody));
  126630. /*
  126631. In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block)
  126632. */
  126633. var varDeclList;
  126634. var varDeclIdentifier;
  126635. if (possibleNameForVarDecl && !shouldReturn) {
  126636. varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier);
  126637. var typeArray = possibleNameForVarDecl.types;
  126638. var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */);
  126639. var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType);
  126640. var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)];
  126641. varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */));
  126642. }
  126643. var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined);
  126644. var destructuredResult = prevArgName && varDeclIdentifier && isSynthBindingPattern(prevArgName)
  126645. && ts.createVariableStatement(/* modifiers */ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepCloneWithRenames(prevArgName.bindingPattern), /* type */ undefined, varDeclIdentifier)], 2 /* Const */));
  126646. return ts.compact([varDeclList, tryStatement, destructuredResult]);
  126647. }
  126648. function getIdentifierTextsFromBindingName(bindingName) {
  126649. if (ts.isIdentifier(bindingName))
  126650. return [bindingName.text];
  126651. return ts.flatMap(bindingName.elements, function (element) {
  126652. if (ts.isOmittedExpression(element))
  126653. return [];
  126654. return getIdentifierTextsFromBindingName(element.name);
  126655. });
  126656. }
  126657. function createUniqueSynthName(prevArgName) {
  126658. var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text);
  126659. return createSynthIdentifier(renamedPrevArg);
  126660. }
  126661. function transformThen(node, transformer, outermostParent, prevArgName) {
  126662. var _a = node.arguments, res = _a[0], rej = _a[1];
  126663. if (!res) {
  126664. return transformExpression(node.expression, transformer, outermostParent);
  126665. }
  126666. var argNameRes = getArgBindingName(res, transformer);
  126667. var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer);
  126668. if (rej) {
  126669. var argNameRej = getArgBindingName(rej, transformer);
  126670. var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody));
  126671. var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer);
  126672. var catchArg = argNameRej ? isSynthIdentifier(argNameRej) ? argNameRej.identifier.text : argNameRej.bindingPattern : "e";
  126673. var catchVariableDeclaration = ts.createVariableDeclaration(catchArg);
  126674. var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody2));
  126675. return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)];
  126676. }
  126677. return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody);
  126678. }
  126679. function getFlagOfBindingName(bindingName, constIdentifiers) {
  126680. var identifiers = getIdentifierTextsFromBindingName(getNode(bindingName));
  126681. var inArr = constIdentifiers.some(function (elem) { return ts.contains(identifiers, elem.text); });
  126682. return inArr ? 2 /* Const */ : 1 /* Let */;
  126683. }
  126684. function transformPromiseCall(node, transformer, prevArgName) {
  126685. var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString());
  126686. // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call
  126687. var originalNodeParent = node.original ? node.original.parent : node.parent;
  126688. if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) {
  126689. return createTransformedStatement(prevArgName, ts.createAwait(node), transformer);
  126690. }
  126691. else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) {
  126692. return [ts.createStatement(ts.createAwait(node))];
  126693. }
  126694. return [ts.createReturn(ts.getSynthesizedDeepClone(node))];
  126695. }
  126696. function createTransformedStatement(prevArgName, rightHandSide, transformer) {
  126697. if (!prevArgName || isEmpty(prevArgName)) {
  126698. // if there's no argName to assign to, there still might be side effects
  126699. return [ts.createStatement(rightHandSide)];
  126700. }
  126701. if (isSynthIdentifier(prevArgName) && prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) {
  126702. // if the variable has already been declared, we don't need "let" or "const"
  126703. return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))];
  126704. }
  126705. return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(getNode(prevArgName)), /*type*/ undefined, rightHandSide)], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))];
  126706. }
  126707. // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts
  126708. function getTransformationBody(func, prevArgName, argName, parent, transformer) {
  126709. var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString());
  126710. switch (func.kind) {
  126711. case 100 /* NullKeyword */:
  126712. // do not produce a transformed statement for a null argument
  126713. break;
  126714. case 75 /* Identifier */: // identifier includes undefined
  126715. if (!argName) {
  126716. // undefined was argument passed to promise handler
  126717. break;
  126718. }
  126719. var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, isSynthIdentifier(argName) ? [argName.identifier] : []);
  126720. if (shouldReturn) {
  126721. return [ts.createReturn(synthCall)];
  126722. }
  126723. var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func);
  126724. var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */);
  126725. if (!callSignatures.length) {
  126726. // if identifier in handler has no call signatures, it's invalid
  126727. codeActionSucceeded = false;
  126728. break;
  126729. }
  126730. var returnType = callSignatures[0].getReturnType();
  126731. var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer);
  126732. if (prevArgName) {
  126733. prevArgName.types.push(returnType);
  126734. }
  126735. return varDeclOrAssignment;
  126736. case 201 /* FunctionExpression */:
  126737. case 202 /* ArrowFunction */: {
  126738. var funcBody = func.body;
  126739. // Arrow functions with block bodies { } will enter this control flow
  126740. if (ts.isBlock(funcBody)) {
  126741. var refactoredStmts = [];
  126742. var seenReturnStatement = false;
  126743. for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) {
  126744. var statement = _a[_i];
  126745. if (ts.isReturnStatement(statement)) {
  126746. seenReturnStatement = true;
  126747. }
  126748. if (ts.isReturnStatementWithFixablePromiseHandler(statement)) {
  126749. refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName));
  126750. }
  126751. else {
  126752. refactoredStmts.push(statement);
  126753. }
  126754. }
  126755. return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) :
  126756. removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement);
  126757. }
  126758. else {
  126759. var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray;
  126760. var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName);
  126761. if (innerCbBody.length > 0) {
  126762. return innerCbBody;
  126763. }
  126764. var type_1 = transformer.checker.getTypeAtLocation(func);
  126765. var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
  126766. var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
  126767. var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
  126768. if (!shouldReturn) {
  126769. var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer);
  126770. if (prevArgName) {
  126771. prevArgName.types.push(returnType_1);
  126772. }
  126773. return transformedStatement;
  126774. }
  126775. else {
  126776. return [ts.createReturn(possiblyAwaitedRightHandSide)];
  126777. }
  126778. }
  126779. }
  126780. default:
  126781. // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code.
  126782. codeActionSucceeded = false;
  126783. break;
  126784. }
  126785. return ts.emptyArray;
  126786. }
  126787. function getLastCallSignature(type, checker) {
  126788. var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */);
  126789. return ts.lastOrUndefined(callSignatures);
  126790. }
  126791. function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) {
  126792. var ret = [];
  126793. for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) {
  126794. var stmt = stmts_1[_i];
  126795. if (ts.isReturnStatement(stmt)) {
  126796. if (stmt.expression) {
  126797. var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression;
  126798. if (prevArgName === undefined) {
  126799. ret.push(ts.createExpressionStatement(possiblyAwaitedExpression));
  126800. }
  126801. else {
  126802. ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfBindingName(prevArgName, transformer.constIdentifiers)))));
  126803. }
  126804. }
  126805. }
  126806. else {
  126807. ret.push(ts.getSynthesizedDeepClone(stmt));
  126808. }
  126809. }
  126810. // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables
  126811. if (!seenReturnStatement && prevArgName !== undefined) {
  126812. ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfBindingName(prevArgName, transformer.constIdentifiers)))));
  126813. }
  126814. return ret;
  126815. }
  126816. function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) {
  126817. var innerCbBody = [];
  126818. for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) {
  126819. var stmt = innerRetStmts_1[_i];
  126820. ts.forEachChild(stmt, function visit(node) {
  126821. if (ts.isCallExpression(node)) {
  126822. var temp = transformExpression(node, transformer, node, prevArgName);
  126823. innerCbBody = innerCbBody.concat(temp);
  126824. if (innerCbBody.length > 0) {
  126825. return;
  126826. }
  126827. }
  126828. else if (!ts.isFunctionLike(node)) {
  126829. ts.forEachChild(node, visit);
  126830. }
  126831. });
  126832. }
  126833. return innerCbBody;
  126834. }
  126835. function getArgBindingName(funcNode, transformer) {
  126836. var numberOfAssignmentsOriginal = 0;
  126837. var types = [];
  126838. var name;
  126839. if (ts.isFunctionLikeDeclaration(funcNode)) {
  126840. if (funcNode.parameters.length > 0) {
  126841. var param = funcNode.parameters[0].name;
  126842. name = getMappedBindingNameOrDefault(param);
  126843. }
  126844. }
  126845. else if (ts.isIdentifier(funcNode)) {
  126846. name = getMapEntryOrDefault(funcNode);
  126847. }
  126848. // return undefined argName when arg is null or undefined
  126849. // eslint-disable-next-line no-in-operator
  126850. if (!name || "identifier" in name && name.identifier.text === "undefined") {
  126851. return undefined;
  126852. }
  126853. return name;
  126854. function getMappedBindingNameOrDefault(bindingName) {
  126855. if (ts.isIdentifier(bindingName))
  126856. return getMapEntryOrDefault(bindingName);
  126857. var elements = ts.flatMap(bindingName.elements, function (element) {
  126858. if (ts.isOmittedExpression(element))
  126859. return [];
  126860. return [getMappedBindingNameOrDefault(element.name)];
  126861. });
  126862. return createSynthBindingPattern(bindingName, elements);
  126863. }
  126864. function getMapEntryOrDefault(identifier) {
  126865. var originalNode = getOriginalNode(identifier);
  126866. var symbol = getSymbol(originalNode);
  126867. if (!symbol) {
  126868. return createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal);
  126869. }
  126870. var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString());
  126871. return mapEntry || createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal);
  126872. }
  126873. function getSymbol(node) {
  126874. return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node);
  126875. }
  126876. function getOriginalNode(node) {
  126877. return node.original ? node.original : node;
  126878. }
  126879. }
  126880. function isEmpty(bindingName) {
  126881. if (!bindingName) {
  126882. return true;
  126883. }
  126884. if (isSynthIdentifier(bindingName)) {
  126885. return !bindingName.identifier.text;
  126886. }
  126887. return ts.every(bindingName.elements, isEmpty);
  126888. }
  126889. function getNode(bindingName) {
  126890. return isSynthIdentifier(bindingName) ? bindingName.identifier : bindingName.bindingPattern;
  126891. }
  126892. function createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal) {
  126893. if (types === void 0) { types = []; }
  126894. if (numberOfAssignmentsOriginal === void 0) { numberOfAssignmentsOriginal = 0; }
  126895. return { kind: 0 /* Identifier */, identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal };
  126896. }
  126897. function createSynthBindingPattern(bindingPattern, elements, types) {
  126898. if (elements === void 0) { elements = ts.emptyArray; }
  126899. if (types === void 0) { types = []; }
  126900. return { kind: 1 /* BindingPattern */, bindingPattern: bindingPattern, elements: elements, types: types };
  126901. }
  126902. function isSynthIdentifier(bindingName) {
  126903. return bindingName.kind === 0 /* Identifier */;
  126904. }
  126905. function isSynthBindingPattern(bindingName) {
  126906. return bindingName.kind === 1 /* BindingPattern */;
  126907. }
  126908. })(codefix = ts.codefix || (ts.codefix = {}));
  126909. })(ts || (ts = {}));
  126910. /* @internal */
  126911. var ts;
  126912. (function (ts) {
  126913. var codefix;
  126914. (function (codefix) {
  126915. codefix.registerCodeFix({
  126916. errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
  126917. getCodeActions: function (context) {
  126918. var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences;
  126919. var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
  126920. var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences));
  126921. if (moduleExportsChangedToDefault) {
  126922. for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
  126923. var importingFile = _a[_i];
  126924. fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences));
  126925. }
  126926. }
  126927. });
  126928. // No support for fix-all since this applies to the whole file at once anyway.
  126929. return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)];
  126930. },
  126931. });
  126932. function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) {
  126933. for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
  126934. var moduleSpecifier = _a[_i];
  126935. var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
  126936. if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
  126937. continue;
  126938. }
  126939. var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
  126940. switch (importNode.kind) {
  126941. case 253 /* ImportEqualsDeclaration */:
  126942. changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference));
  126943. break;
  126944. case 196 /* CallExpression */:
  126945. if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
  126946. changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default"));
  126947. }
  126948. break;
  126949. }
  126950. }
  126951. }
  126952. /** @returns Whether we converted a `module.exports =` to a default export. */
  126953. function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) {
  126954. var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
  126955. var exports = collectExportRenames(sourceFile, checker, identifiers);
  126956. convertExportsAccesses(sourceFile, exports, changes);
  126957. var moduleExportsChangedToDefault = false;
  126958. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  126959. var statement = _a[_i];
  126960. var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference);
  126961. moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
  126962. }
  126963. return moduleExportsChangedToDefault;
  126964. }
  126965. function collectExportRenames(sourceFile, checker, identifiers) {
  126966. var res = ts.createMap();
  126967. forEachExportReference(sourceFile, function (node) {
  126968. var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
  126969. if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
  126970. || checker.resolveName(text, node, 111551 /* Value */, /*excludeGlobals*/ true))) {
  126971. // Unconditionally add an underscore in case `text` is a keyword.
  126972. res.set(text, makeUniqueName("_" + text, identifiers));
  126973. }
  126974. });
  126975. return res;
  126976. }
  126977. function convertExportsAccesses(sourceFile, exports, changes) {
  126978. forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
  126979. if (isAssignmentLhs) {
  126980. return;
  126981. }
  126982. var text = node.name.text;
  126983. changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
  126984. });
  126985. }
  126986. function forEachExportReference(sourceFile, cb) {
  126987. sourceFile.forEachChild(function recur(node) {
  126988. if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && ts.isIdentifier(node.name)) {
  126989. var parent = node.parent;
  126990. cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 62 /* EqualsToken */);
  126991. }
  126992. node.forEachChild(recur);
  126993. });
  126994. }
  126995. function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) {
  126996. switch (statement.kind) {
  126997. case 225 /* VariableStatement */:
  126998. convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
  126999. return false;
  127000. case 226 /* ExpressionStatement */: {
  127001. var expression = statement.expression;
  127002. switch (expression.kind) {
  127003. case 196 /* CallExpression */: {
  127004. if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
  127005. // For side-effecting require() call, just make a side-effecting import.
  127006. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference));
  127007. }
  127008. return false;
  127009. }
  127010. case 209 /* BinaryExpression */: {
  127011. var operatorToken = expression.operatorToken;
  127012. return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports);
  127013. }
  127014. }
  127015. }
  127016. // falls through
  127017. default:
  127018. return false;
  127019. }
  127020. }
  127021. function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) {
  127022. var declarationList = statement.declarationList;
  127023. var foundImport = false;
  127024. var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
  127025. var name = decl.name, initializer = decl.initializer;
  127026. if (initializer) {
  127027. if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
  127028. // `const alias = module.exports;` can be removed.
  127029. foundImport = true;
  127030. return [];
  127031. }
  127032. else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
  127033. foundImport = true;
  127034. return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference);
  127035. }
  127036. else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) {
  127037. foundImport = true;
  127038. return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference);
  127039. }
  127040. }
  127041. // Move it out to its own variable statement. (This will not be used if `!foundImport`)
  127042. return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
  127043. });
  127044. if (foundImport) {
  127045. // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
  127046. changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
  127047. }
  127048. }
  127049. /** Converts `const name = require("moduleSpecifier").propertyName` */
  127050. function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
  127051. switch (name.kind) {
  127052. case 189 /* ObjectBindingPattern */:
  127053. case 190 /* ArrayBindingPattern */: {
  127054. // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
  127055. var tmp = makeUniqueName(propertyName, identifiers);
  127056. return [
  127057. makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference),
  127058. makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
  127059. ];
  127060. }
  127061. case 75 /* Identifier */:
  127062. // `const a = require("b").c` --> `import { c as a } from "./b";
  127063. return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)];
  127064. default:
  127065. return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind);
  127066. }
  127067. }
  127068. function convertAssignment(sourceFile, checker, assignment, changes, exports) {
  127069. var left = assignment.left, right = assignment.right;
  127070. if (!ts.isPropertyAccessExpression(left)) {
  127071. return false;
  127072. }
  127073. if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
  127074. if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
  127075. // `const alias = module.exports;` or `module.exports = alias;` can be removed.
  127076. changes.delete(sourceFile, assignment.parent);
  127077. }
  127078. else {
  127079. var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
  127080. : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
  127081. : undefined;
  127082. if (replacement) {
  127083. changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
  127084. return replacement[1];
  127085. }
  127086. else {
  127087. changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default");
  127088. return true;
  127089. }
  127090. }
  127091. }
  127092. else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
  127093. convertNamedExport(sourceFile, assignment, changes, exports);
  127094. }
  127095. return false;
  127096. }
  127097. /**
  127098. * Convert `module.exports = { ... }` to individual exports..
  127099. * We can't always do this if the module has interesting members -- then it will be a default export instead.
  127100. */
  127101. function tryChangeModuleExportsObject(object) {
  127102. var statements = ts.mapAllOrFail(object.properties, function (prop) {
  127103. switch (prop.kind) {
  127104. case 163 /* GetAccessor */:
  127105. case 164 /* SetAccessor */:
  127106. // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
  127107. // falls through
  127108. case 282 /* ShorthandPropertyAssignment */:
  127109. case 283 /* SpreadAssignment */:
  127110. return undefined;
  127111. case 281 /* PropertyAssignment */:
  127112. return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer);
  127113. case 161 /* MethodDeclaration */:
  127114. return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(89 /* ExportKeyword */)], prop);
  127115. default:
  127116. ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind);
  127117. }
  127118. });
  127119. return statements && [statements, false];
  127120. }
  127121. function convertNamedExport(sourceFile, assignment, changes, exports) {
  127122. // If "originalKeywordKind" was set, this is e.g. `exports.
  127123. var text = assignment.left.name.text;
  127124. var rename = exports.get(text);
  127125. if (rename !== undefined) {
  127126. /*
  127127. const _class = 0;
  127128. export { _class as class };
  127129. */
  127130. var newNodes = [
  127131. makeConst(/*modifiers*/ undefined, rename, assignment.right),
  127132. makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
  127133. ];
  127134. changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
  127135. }
  127136. else {
  127137. convertExportsPropertyAssignment(assignment, sourceFile, changes);
  127138. }
  127139. }
  127140. function convertReExportAll(reExported, checker) {
  127141. // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
  127142. var moduleSpecifier = reExported.text;
  127143. var moduleSymbol = checker.getSymbolAtLocation(reExported);
  127144. var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
  127145. return exports.has("export=") ? [[reExportDefault(moduleSpecifier)], true] :
  127146. !exports.has("default") ? [[reExportStar(moduleSpecifier)], false] :
  127147. // If there's some non-default export, must include both `export *` and `export default`.
  127148. exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
  127149. }
  127150. function reExportStar(moduleSpecifier) {
  127151. return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
  127152. }
  127153. function reExportDefault(moduleSpecifier) {
  127154. return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
  127155. }
  127156. function convertExportsPropertyAssignment(_a, sourceFile, changes) {
  127157. var left = _a.left, right = _a.right, parent = _a.parent;
  127158. var name = left.name.text;
  127159. if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) {
  127160. // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`.
  127161. changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(89 /* ExportKeyword */), { suffix: " " });
  127162. if (!right.name)
  127163. changes.insertName(sourceFile, right, name);
  127164. var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile);
  127165. if (semi)
  127166. changes.delete(sourceFile, semi);
  127167. }
  127168. else {
  127169. // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const `
  127170. changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(89 /* ExportKeyword */), ts.createToken(81 /* ConstKeyword */)], { joiner: " ", suffix: " " });
  127171. }
  127172. }
  127173. // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node.
  127174. function convertExportsDotXEquals_replaceNode(name, exported) {
  127175. var modifiers = [ts.createToken(89 /* ExportKeyword */)];
  127176. switch (exported.kind) {
  127177. case 201 /* FunctionExpression */: {
  127178. var expressionName = exported.name;
  127179. if (expressionName && expressionName.text !== name) {
  127180. // `exports.f = function g() {}` -> `export const f = function g() {}`
  127181. return exportConst();
  127182. }
  127183. }
  127184. // falls through
  127185. case 202 /* ArrowFunction */:
  127186. // `exports.f = function() {}` --> `export function f() {}`
  127187. return functionExpressionToDeclaration(name, modifiers, exported);
  127188. case 214 /* ClassExpression */:
  127189. // `exports.C = class {}` --> `export class C {}`
  127190. return classExpressionToDeclaration(name, modifiers, exported);
  127191. default:
  127192. return exportConst();
  127193. }
  127194. function exportConst() {
  127195. // `exports.x = 0;` --> `export const x = 0;`
  127196. return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217
  127197. }
  127198. }
  127199. /**
  127200. * Converts `const <<name>> = require("x");`.
  127201. * Returns nodes that will replace the variable declaration for the commonjs import.
  127202. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
  127203. */
  127204. function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) {
  127205. switch (name.kind) {
  127206. case 189 /* ObjectBindingPattern */: {
  127207. var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
  127208. return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
  127209. ? undefined
  127210. // (TODO: GH#18217)
  127211. // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
  127212. : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
  127213. });
  127214. if (importSpecifiers) {
  127215. return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)];
  127216. }
  127217. }
  127218. // falls through -- object destructuring has an interesting pattern and must be a variable declaration
  127219. case 190 /* ArrayBindingPattern */: {
  127220. /*
  127221. import x from "x";
  127222. const [a, b, c] = x;
  127223. */
  127224. var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
  127225. return [
  127226. ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference),
  127227. makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
  127228. ];
  127229. }
  127230. case 75 /* Identifier */:
  127231. return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference);
  127232. default:
  127233. return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind);
  127234. }
  127235. }
  127236. /**
  127237. * Convert `import x = require("x").`
  127238. * Also converts uses like `x.y()` to `y()` and uses a named import.
  127239. */
  127240. function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) {
  127241. var nameSymbol = checker.getSymbolAtLocation(name);
  127242. // Maps from module property name to name actually used. (The same if there isn't shadowing.)
  127243. var namedBindingsNames = ts.createMap();
  127244. // True if there is some non-property use like `x()` or `f(x)`.
  127245. var needDefaultImport = false;
  127246. for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
  127247. var use = _a[_i];
  127248. if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
  127249. // This was a use of a different symbol with the same name, due to shadowing. Ignore.
  127250. continue;
  127251. }
  127252. var parent = use.parent;
  127253. if (ts.isPropertyAccessExpression(parent)) {
  127254. var expression = parent.expression, propertyName = parent.name.text;
  127255. ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers`
  127256. var idName = namedBindingsNames.get(propertyName);
  127257. if (idName === undefined) {
  127258. idName = makeUniqueName(propertyName, identifiers);
  127259. namedBindingsNames.set(propertyName, idName);
  127260. }
  127261. changes.replaceNode(file, parent, ts.createIdentifier(idName));
  127262. }
  127263. else {
  127264. needDefaultImport = true;
  127265. }
  127266. }
  127267. var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
  127268. var propertyName = _a[0], idName = _a[1];
  127269. return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
  127270. }));
  127271. if (!namedBindings) {
  127272. // If it was unused, ensure that we at least import *something*.
  127273. needDefaultImport = true;
  127274. }
  127275. return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)];
  127276. }
  127277. // Identifiers helpers
  127278. function makeUniqueName(name, identifiers) {
  127279. while (identifiers.original.has(name) || identifiers.additional.has(name)) {
  127280. name = "_" + name;
  127281. }
  127282. identifiers.additional.set(name, true);
  127283. return name;
  127284. }
  127285. function collectFreeIdentifiers(file) {
  127286. var map = ts.createMultiMap();
  127287. forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); });
  127288. return map;
  127289. }
  127290. /**
  127291. * A free identifier is an identifier that can be accessed through name lookup as a local variable.
  127292. * In the expression `x.y`, `x` is a free identifier, but `y` is not.
  127293. */
  127294. function forEachFreeIdentifier(node, cb) {
  127295. if (ts.isIdentifier(node) && isFreeIdentifier(node))
  127296. cb(node);
  127297. node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); });
  127298. }
  127299. function isFreeIdentifier(node) {
  127300. var parent = node.parent;
  127301. switch (parent.kind) {
  127302. case 194 /* PropertyAccessExpression */:
  127303. return parent.name !== node;
  127304. case 191 /* BindingElement */:
  127305. return parent.propertyName !== node;
  127306. case 258 /* ImportSpecifier */:
  127307. return parent.propertyName !== node;
  127308. default:
  127309. return true;
  127310. }
  127311. }
  127312. // Node helpers
  127313. function functionExpressionToDeclaration(name, additionalModifiers, fn) {
  127314. return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
  127315. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
  127316. }
  127317. function classExpressionToDeclaration(name, additionalModifiers, cls) {
  127318. return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
  127319. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
  127320. }
  127321. function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) {
  127322. return propertyName === "default"
  127323. ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference)
  127324. : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference);
  127325. }
  127326. function makeImportSpecifier(propertyName, name) {
  127327. return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
  127328. }
  127329. function makeConst(modifiers, name, init) {
  127330. return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
  127331. }
  127332. function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
  127333. return ts.createExportDeclaration(
  127334. /*decorators*/ undefined,
  127335. /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
  127336. }
  127337. })(codefix = ts.codefix || (ts.codefix = {}));
  127338. })(ts || (ts = {}));
  127339. /* @internal */
  127340. var ts;
  127341. (function (ts) {
  127342. var codefix;
  127343. (function (codefix) {
  127344. var fixId = "correctQualifiedNameToIndexedAccessType";
  127345. var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code];
  127346. codefix.registerCodeFix({
  127347. errorCodes: errorCodes,
  127348. getCodeActions: function (context) {
  127349. var qualifiedName = getQualifiedName(context.sourceFile, context.span.start);
  127350. if (!qualifiedName)
  127351. return undefined;
  127352. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); });
  127353. var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]";
  127354. return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)];
  127355. },
  127356. fixIds: [fixId],
  127357. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  127358. var q = getQualifiedName(diag.file, diag.start);
  127359. if (q) {
  127360. doChange(changes, diag.file, q);
  127361. }
  127362. }); },
  127363. });
  127364. function getQualifiedName(sourceFile, pos) {
  127365. var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName);
  127366. ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
  127367. return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined;
  127368. }
  127369. function doChange(changeTracker, sourceFile, qualifiedName) {
  127370. var rightText = qualifiedName.right.text;
  127371. var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText)));
  127372. changeTracker.replaceNode(sourceFile, qualifiedName, replacement);
  127373. }
  127374. })(codefix = ts.codefix || (ts.codefix = {}));
  127375. })(ts || (ts = {}));
  127376. /* @internal */
  127377. var ts;
  127378. (function (ts) {
  127379. var codefix;
  127380. (function (codefix) {
  127381. var errorCodes = [ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type.code];
  127382. var fixId = "convertToTypeOnlyExport";
  127383. codefix.registerCodeFix({
  127384. errorCodes: errorCodes,
  127385. getCodeActions: function (context) {
  127386. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context); });
  127387. if (changes.length) {
  127388. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_export, fixId, ts.Diagnostics.Convert_all_re_exported_types_to_type_only_exports)];
  127389. }
  127390. },
  127391. fixIds: [fixId],
  127392. getAllCodeActions: function (context) {
  127393. var fixedExportDeclarations = ts.createMap();
  127394. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  127395. var exportSpecifier = getExportSpecifierForDiagnosticSpan(diag, context.sourceFile);
  127396. if (exportSpecifier && !ts.addToSeen(fixedExportDeclarations, ts.getNodeId(exportSpecifier.parent.parent))) {
  127397. fixSingleExportDeclaration(changes, exportSpecifier, context);
  127398. }
  127399. });
  127400. }
  127401. });
  127402. function getExportSpecifierForDiagnosticSpan(span, sourceFile) {
  127403. return ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start).parent, ts.isExportSpecifier);
  127404. }
  127405. function fixSingleExportDeclaration(changes, exportSpecifier, context) {
  127406. if (!exportSpecifier) {
  127407. return;
  127408. }
  127409. var exportClause = exportSpecifier.parent;
  127410. var exportDeclaration = exportClause.parent;
  127411. var typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context);
  127412. if (typeExportSpecifiers.length === exportClause.elements.length) {
  127413. changes.replaceNode(context.sourceFile, exportDeclaration, ts.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, exportClause, exportDeclaration.moduleSpecifier,
  127414. /*isTypeOnly*/ true));
  127415. }
  127416. else {
  127417. var valueExportDeclaration = ts.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, ts.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier,
  127418. /*isTypeOnly*/ false);
  127419. var typeExportDeclaration = ts.createExportDeclaration(
  127420. /*decorators*/ undefined,
  127421. /*modifiers*/ undefined, ts.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier,
  127422. /*isTypeOnly*/ true);
  127423. changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration);
  127424. changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration);
  127425. }
  127426. }
  127427. function getTypeExportSpecifiers(originExportSpecifier, context) {
  127428. var exportClause = originExportSpecifier.parent;
  127429. if (exportClause.elements.length === 1) {
  127430. return exportClause.elements;
  127431. }
  127432. var diagnostics = ts.getDiagnosticsWithinSpan(ts.createTextSpanFromNode(exportClause), context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken));
  127433. return ts.filter(exportClause.elements, function (element) {
  127434. var _a;
  127435. return element === originExportSpecifier || ((_a = ts.findDiagnosticForNode(element, diagnostics)) === null || _a === void 0 ? void 0 : _a.code) === errorCodes[0];
  127436. });
  127437. }
  127438. })(codefix = ts.codefix || (ts.codefix = {}));
  127439. })(ts || (ts = {}));
  127440. /* @internal */
  127441. var ts;
  127442. (function (ts) {
  127443. var codefix;
  127444. (function (codefix) {
  127445. var errorCodes = [
  127446. ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code,
  127447. ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code
  127448. ];
  127449. var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember?
  127450. codefix.registerCodeFix({
  127451. errorCodes: errorCodes,
  127452. getCodeActions: function (context) {
  127453. var sourceFile = context.sourceFile, span = context.span;
  127454. var classDeclaration = getClass(sourceFile, span.start);
  127455. return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) {
  127456. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); });
  127457. return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces);
  127458. });
  127459. },
  127460. fixIds: [fixId],
  127461. getAllCodeActions: function (context) {
  127462. var seenClassDeclarations = ts.createMap();
  127463. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  127464. var classDeclaration = getClass(diag.file, diag.start);
  127465. if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
  127466. for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) {
  127467. var implementedTypeNode = _a[_i];
  127468. addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences);
  127469. }
  127470. }
  127471. });
  127472. },
  127473. });
  127474. function getClass(sourceFile, pos) {
  127475. return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
  127476. }
  127477. function symbolPointsToNonPrivateMember(symbol) {
  127478. return !symbol.valueDeclaration || !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */);
  127479. }
  127480. function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) {
  127481. var checker = context.program.getTypeChecker();
  127482. var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
  127483. // Note that this is ultimately derived from a map indexed by symbol names,
  127484. // so duplicates cannot occur.
  127485. var implementedType = checker.getTypeAtLocation(implementedTypeNode);
  127486. var implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
  127487. var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); }));
  127488. var classType = checker.getTypeAtLocation(classDeclaration);
  127489. var constructor = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m); });
  127490. if (!classType.getNumberIndexType()) {
  127491. createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */);
  127492. }
  127493. if (!classType.getStringIndexType()) {
  127494. createMissingIndexSignatureDeclaration(implementedType, 0 /* String */);
  127495. }
  127496. codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, function (member) { return insertInterfaceMemberNode(sourceFile, classDeclaration, member); });
  127497. function createMissingIndexSignatureDeclaration(type, kind) {
  127498. var indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
  127499. if (indexInfoOfKind) {
  127500. insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context)));
  127501. }
  127502. }
  127503. // Either adds the node at the top of the class, or if there's a constructor right after that
  127504. function insertInterfaceMemberNode(sourceFile, cls, newElement) {
  127505. if (constructor) {
  127506. changeTracker.insertNodeAfter(sourceFile, constructor, newElement);
  127507. }
  127508. else {
  127509. changeTracker.insertNodeAtClassStart(sourceFile, cls, newElement);
  127510. }
  127511. }
  127512. }
  127513. function getHeritageClauseSymbolTable(classDeclaration, checker) {
  127514. var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration);
  127515. if (!heritageClauseNode)
  127516. return ts.createSymbolTable();
  127517. var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
  127518. var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType);
  127519. return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember));
  127520. }
  127521. })(codefix = ts.codefix || (ts.codefix = {}));
  127522. })(ts || (ts = {}));
  127523. /* @internal */
  127524. var ts;
  127525. (function (ts) {
  127526. var codefix;
  127527. (function (codefix) {
  127528. codefix.importFixName = "import";
  127529. var importFixId = "fixMissingImport";
  127530. var errorCodes = [
  127531. ts.Diagnostics.Cannot_find_name_0.code,
  127532. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
  127533. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  127534. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
  127535. ts.Diagnostics.Cannot_find_namespace_0.code,
  127536. ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
  127537. ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
  127538. ];
  127539. codefix.registerCodeFix({
  127540. errorCodes: errorCodes,
  127541. getCodeActions: function (context) {
  127542. var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span;
  127543. var info = getFixesInfo(context, errorCode, span.start);
  127544. if (!info)
  127545. return undefined;
  127546. var fixes = info.fixes, symbolName = info.symbolName;
  127547. var quotePreference = ts.getQuotePreference(sourceFile, preferences);
  127548. return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); });
  127549. },
  127550. fixIds: [importFixId],
  127551. getAllCodeActions: function (context) {
  127552. var sourceFile = context.sourceFile, preferences = context.preferences;
  127553. // Namespace fixes don't conflict, so just build a list.
  127554. var addToNamespace = [];
  127555. var importType = [];
  127556. // Keys are import clause node IDs.
  127557. var addToExisting = ts.createMap();
  127558. var newImports = ts.createMap();
  127559. var lastModuleSpecifier;
  127560. codefix.eachDiagnostic(context, errorCodes, function (diag) {
  127561. var info = getFixesInfo(context, diag.code, diag.start);
  127562. if (!info || !info.fixes.length)
  127563. return;
  127564. var fixes = info.fixes, symbolName = info.symbolName;
  127565. var fix = ts.first(fixes);
  127566. switch (fix.kind) {
  127567. case 0 /* UseNamespace */:
  127568. addToNamespace.push(fix);
  127569. break;
  127570. case 1 /* ImportType */:
  127571. importType.push(fix);
  127572. break;
  127573. case 2 /* AddToExisting */: {
  127574. var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport;
  127575. var key = String(ts.getNodeId(importClause));
  127576. var entry = addToExisting.get(key);
  127577. if (!entry) {
  127578. addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport });
  127579. }
  127580. if (importKind === 0 /* Named */) {
  127581. ts.pushIfUnique(entry.namedImports, symbolName);
  127582. }
  127583. else {
  127584. ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add to Existing) Default import should be missing or match symbolName");
  127585. entry.defaultImport = symbolName;
  127586. }
  127587. break;
  127588. }
  127589. case 3 /* AddNew */: {
  127590. var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind;
  127591. var entry = newImports.get(moduleSpecifier);
  127592. if (!entry) {
  127593. newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined });
  127594. lastModuleSpecifier = moduleSpecifier;
  127595. }
  127596. switch (importKind) {
  127597. case 1 /* Default */:
  127598. ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add new) Default import should be missing or match symbolName");
  127599. entry.defaultImport = symbolName;
  127600. break;
  127601. case 0 /* Named */:
  127602. ts.pushIfUnique(entry.namedImports, symbolName);
  127603. break;
  127604. case 3 /* Equals */:
  127605. case 2 /* Namespace */:
  127606. ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName");
  127607. entry.namespaceLikeImport = { importKind: importKind, name: symbolName };
  127608. break;
  127609. }
  127610. break;
  127611. }
  127612. default:
  127613. ts.Debug.assertNever(fix, "fix wasn't never - got kind " + fix.kind);
  127614. }
  127615. });
  127616. return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
  127617. var quotePreference = ts.getQuotePreference(sourceFile, preferences);
  127618. for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) {
  127619. var fix = addToNamespace_1[_i];
  127620. addNamespaceQualifier(changes, sourceFile, fix);
  127621. }
  127622. for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) {
  127623. var fix = importType_1[_a];
  127624. addImportType(changes, sourceFile, fix, quotePreference);
  127625. }
  127626. addToExisting.forEach(function (_a) {
  127627. var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport;
  127628. doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports, canUseTypeOnlyImport);
  127629. });
  127630. newImports.forEach(function (imports, moduleSpecifier) {
  127631. addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier);
  127632. });
  127633. }));
  127634. },
  127635. });
  127636. // Sorted with the preferred fix coming first.
  127637. var ImportFixKind;
  127638. (function (ImportFixKind) {
  127639. ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace";
  127640. ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType";
  127641. ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting";
  127642. ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew";
  127643. })(ImportFixKind || (ImportFixKind = {}));
  127644. var ImportKind;
  127645. (function (ImportKind) {
  127646. ImportKind[ImportKind["Named"] = 0] = "Named";
  127647. ImportKind[ImportKind["Default"] = 1] = "Default";
  127648. ImportKind[ImportKind["Namespace"] = 2] = "Namespace";
  127649. ImportKind[ImportKind["Equals"] = 3] = "Equals";
  127650. ImportKind[ImportKind["ConstEquals"] = 4] = "ConstEquals";
  127651. })(ImportKind || (ImportKind = {}));
  127652. function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) {
  127653. var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles());
  127654. ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol");
  127655. // We sort the best codefixes first, so taking `first` is best for completions.
  127656. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier;
  127657. var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences));
  127658. return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) };
  127659. }
  127660. codefix.getImportCompletionAction = getImportCompletionAction;
  127661. function codeFixActionToCodeAction(_a) {
  127662. var description = _a.description, changes = _a.changes, commands = _a.commands;
  127663. return { description: description, changes: changes, commands: commands };
  127664. }
  127665. function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) {
  127666. var result = [];
  127667. forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) {
  127668. // Don't import from a re-export when looking "up" like to `./index` or `../index`.
  127669. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) {
  127670. return;
  127671. }
  127672. var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions);
  127673. if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) {
  127674. result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) });
  127675. }
  127676. for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) {
  127677. var exported = _a[_i];
  127678. if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) {
  127679. result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) });
  127680. }
  127681. }
  127682. });
  127683. return result;
  127684. }
  127685. function isTypeOnlySymbol(s, checker) {
  127686. return !(ts.skipAlias(s, checker).flags & 111551 /* Value */);
  127687. }
  127688. function isTypeOnlyPosition(sourceFile, position) {
  127689. return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position));
  127690. }
  127691. function getFixForImport(exportInfos, symbolName,
  127692. /** undefined only for missing JSX namespace */
  127693. position, program, sourceFile, host, preferences) {
  127694. var checker = program.getTypeChecker();
  127695. var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); });
  127696. var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker);
  127697. var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position));
  127698. // Don't bother providing an action to add a new import if we can add to an existing one.
  127699. var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences);
  127700. return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport);
  127701. }
  127702. function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) {
  127703. // It is possible that multiple import statements with the same specifier exist in the file.
  127704. // e.g.
  127705. //
  127706. // import * as ns from "foo";
  127707. // import { member1, member2 } from "foo";
  127708. //
  127709. // member3/**/ <-- cusor here
  127710. //
  127711. // in this case we should provie 2 actions:
  127712. // 1. change "member3" to "ns.member3"
  127713. // 2. add "member3" to the second import statement's import list
  127714. // and it is up to the user to decide which one fits best.
  127715. return ts.firstDefined(existingImports, function (_a) {
  127716. var declaration = _a.declaration;
  127717. var namespace = getNamespaceImportName(declaration);
  127718. if (namespace) {
  127719. var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace));
  127720. if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) {
  127721. return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position };
  127722. }
  127723. }
  127724. });
  127725. }
  127726. function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) {
  127727. return ts.firstDefined(existingImports, function (_a) {
  127728. var declaration = _a.declaration, importKind = _a.importKind;
  127729. if (declaration.kind !== 254 /* ImportDeclaration */)
  127730. return undefined;
  127731. var importClause = declaration.importClause;
  127732. if (!importClause)
  127733. return undefined;
  127734. var name = importClause.name, namedBindings = importClause.namedBindings;
  127735. return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */)
  127736. ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind, canUseTypeOnlyImport: canUseTypeOnlyImport }
  127737. : undefined;
  127738. });
  127739. }
  127740. function getNamespaceImportName(declaration) {
  127741. if (declaration.kind === 254 /* ImportDeclaration */) {
  127742. var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings;
  127743. return namedBindings && namedBindings.kind === 256 /* NamespaceImport */ ? namedBindings.name : undefined;
  127744. }
  127745. else {
  127746. return declaration.name;
  127747. }
  127748. }
  127749. function getExistingImportDeclarations(_a, checker, sourceFile) {
  127750. var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
  127751. // Can't use an es6 import for a type in JS.
  127752. return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) {
  127753. var i = ts.importFromModuleSpecifier(moduleSpecifier);
  127754. return (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */)
  127755. && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, exportedSymbolIsTypeOnly: exportedSymbolIsTypeOnly } : undefined;
  127756. });
  127757. }
  127758. function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) {
  127759. var isJs = ts.isSourceFileJS(sourceFile);
  127760. var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier;
  127761. var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
  127762. var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
  127763. return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap)
  127764. .map(function (moduleSpecifier) {
  127765. // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
  127766. return exportedSymbolIsTypeOnly && isJs
  127767. ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position, "position should be defined") }
  127768. : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind };
  127769. });
  127770. });
  127771. // Sort by presence in package.json, then shortest paths first
  127772. return ts.sort(choicesForEachExportingModule, function (a, b) {
  127773. var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier);
  127774. var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier);
  127775. if (allowsImportingA && !allowsImportingB) {
  127776. return -1;
  127777. }
  127778. if (allowsImportingB && !allowsImportingA) {
  127779. return 1;
  127780. }
  127781. return a.moduleSpecifier.length - b.moduleSpecifier.length;
  127782. });
  127783. }
  127784. function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) {
  127785. var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
  127786. return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences);
  127787. }
  127788. function newImportInfoFromExistingSpecifier(_a) {
  127789. var declaration = _a.declaration, importKind = _a.importKind;
  127790. var expression = declaration.kind === 254 /* ImportDeclaration */
  127791. ? declaration.moduleSpecifier
  127792. : declaration.moduleReference.kind === 265 /* ExternalModuleReference */
  127793. ? declaration.moduleReference.expression
  127794. : undefined;
  127795. return expression && ts.isStringLiteral(expression)
  127796. ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind }
  127797. : undefined;
  127798. }
  127799. function getFixesInfo(context, errorCode, pos) {
  127800. var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos);
  127801. var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
  127802. ? getFixesInfoForUMDImport(context, symbolToken)
  127803. : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined;
  127804. return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) });
  127805. }
  127806. function getFixesInfoForUMDImport(_a, token) {
  127807. var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences;
  127808. var checker = program.getTypeChecker();
  127809. var umdSymbol = getUmdSymbol(token, checker);
  127810. if (!umdSymbol)
  127811. return undefined;
  127812. var symbol = checker.getAliasedSymbol(umdSymbol);
  127813. var symbolName = umdSymbol.name;
  127814. var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }];
  127815. var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences);
  127816. return { fixes: fixes, symbolName: symbolName };
  127817. }
  127818. function getUmdSymbol(token, checker) {
  127819. // try the identifier to see if it is the umd symbol
  127820. var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined;
  127821. if (ts.isUMDExportSymbol(umdSymbol))
  127822. return umdSymbol;
  127823. // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
  127824. var parent = token.parent;
  127825. return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent)
  127826. ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
  127827. : undefined;
  127828. }
  127829. function getUmdImportKind(importingFile, compilerOptions) {
  127830. // Import a synthetic `default` if enabled.
  127831. if (ts.getAllowSyntheticDefaultImports(compilerOptions)) {
  127832. return 1 /* Default */;
  127833. }
  127834. // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it.
  127835. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  127836. switch (moduleKind) {
  127837. case ts.ModuleKind.AMD:
  127838. case ts.ModuleKind.CommonJS:
  127839. case ts.ModuleKind.UMD:
  127840. if (ts.isInJSFile(importingFile)) {
  127841. return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 4 /* ConstEquals */;
  127842. }
  127843. return 3 /* Equals */;
  127844. case ts.ModuleKind.System:
  127845. case ts.ModuleKind.ES2015:
  127846. case ts.ModuleKind.ES2020:
  127847. case ts.ModuleKind.ESNext:
  127848. case ts.ModuleKind.None:
  127849. // Fall back to the `import * as ns` style import.
  127850. return 2 /* Namespace */;
  127851. default:
  127852. return ts.Debug.assertNever(moduleKind, "Unexpected moduleKind " + moduleKind);
  127853. }
  127854. }
  127855. function getFixesInfoForNonUMDImport(_a, symbolToken) {
  127856. var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences;
  127857. var checker = program.getTypeChecker();
  127858. // If we're at `<Foo/>`, we must check if `Foo` is already in scope, and if so, get an import for `React` instead.
  127859. var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent)
  127860. && symbolToken.parent.tagName === symbolToken
  127861. && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false))
  127862. ? checker.getJsxNamespace(sourceFile)
  127863. : symbolToken.text;
  127864. // "default" is a keyword and not a legal identifier for the import, so we don't expect it here
  127865. ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here");
  127866. var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host);
  127867. var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) {
  127868. var _ = _a[0], exportInfos = _a[1];
  127869. return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences);
  127870. }));
  127871. return { fixes: fixes, symbolName: symbolName };
  127872. }
  127873. // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported.
  127874. function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program, host) {
  127875. // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once.
  127876. // Maps symbol id to info for modules providing that symbol (original export + re-exports).
  127877. var originalSymbolToExportInfos = ts.createMultiMap();
  127878. function addSymbol(moduleSymbol, exportedSymbol, importKind) {
  127879. originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) });
  127880. }
  127881. forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, function (moduleSymbol) {
  127882. cancellationToken.throwIfCancellationRequested();
  127883. var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, program.getCompilerOptions());
  127884. if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) {
  127885. addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind);
  127886. }
  127887. // check exports with the same name
  127888. var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
  127889. if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
  127890. addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */);
  127891. }
  127892. });
  127893. return originalSymbolToExportInfos;
  127894. }
  127895. function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) {
  127896. var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions);
  127897. if (!exported)
  127898. return undefined;
  127899. var symbol = exported.symbol, kind = exported.kind;
  127900. var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions);
  127901. return info && __assign({ symbol: symbol, kind: kind }, info);
  127902. }
  127903. function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) {
  127904. var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
  127905. if (defaultExport)
  127906. return { symbol: defaultExport, kind: 1 /* Default */ };
  127907. var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
  127908. return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: getExportEqualsImportKind(importingFile, compilerOptions) };
  127909. }
  127910. function getExportEqualsImportKind(importingFile, compilerOptions) {
  127911. var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions);
  127912. // 1. 'import =' will not work in es2015+, so the decision is between a default
  127913. // and a namespace import, based on allowSyntheticDefaultImports/esModuleInterop.
  127914. if (ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
  127915. return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */;
  127916. }
  127917. // 2. 'import =' will not work in JavaScript, so the decision is between a default
  127918. // and const/require.
  127919. if (ts.isInJSFile(importingFile)) {
  127920. return ts.isExternalModule(importingFile) ? 1 /* Default */ : 4 /* ConstEquals */;
  127921. }
  127922. // 3. At this point the most correct choice is probably 'import =', but people
  127923. // really hate that, so look to see if the importing file has any precedent
  127924. // on how to handle it.
  127925. for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) {
  127926. var statement = _a[_i];
  127927. if (ts.isImportEqualsDeclaration(statement)) {
  127928. return 3 /* Equals */;
  127929. }
  127930. }
  127931. // 4. We have no precedent to go on, so just use a default import if
  127932. // allowSyntheticDefaultImports/esModuleInterop is enabled.
  127933. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* Equals */;
  127934. }
  127935. function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) {
  127936. var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
  127937. if (localSymbol)
  127938. return { symbolForMeaning: localSymbol, name: localSymbol.name };
  127939. var name = getNameForExportDefault(defaultExport);
  127940. if (name !== undefined)
  127941. return { symbolForMeaning: defaultExport, name: name };
  127942. if (defaultExport.flags & 2097152 /* Alias */) {
  127943. var aliased = checker.getImmediateAliasedSymbol(defaultExport);
  127944. return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions);
  127945. }
  127946. if (defaultExport.escapedName !== "default" /* Default */ &&
  127947. defaultExport.escapedName !== "export=" /* ExportEquals */) {
  127948. return { symbolForMeaning: defaultExport, name: defaultExport.getName() };
  127949. }
  127950. return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) };
  127951. }
  127952. function getNameForExportDefault(symbol) {
  127953. return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
  127954. if (ts.isExportAssignment(declaration)) {
  127955. if (ts.isIdentifier(declaration.expression)) {
  127956. return declaration.expression.text;
  127957. }
  127958. }
  127959. else if (ts.isExportSpecifier(declaration)) {
  127960. ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export");
  127961. return declaration.propertyName && declaration.propertyName.text;
  127962. }
  127963. });
  127964. }
  127965. function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) {
  127966. var diag;
  127967. var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
  127968. diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference);
  127969. });
  127970. return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports);
  127971. }
  127972. function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) {
  127973. switch (fix.kind) {
  127974. case 0 /* UseNamespace */:
  127975. addNamespaceQualifier(changes, sourceFile, fix);
  127976. return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName];
  127977. case 1 /* ImportType */:
  127978. addImportType(changes, sourceFile, fix, quotePreference);
  127979. return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName];
  127980. case 2 /* AddToExisting */: {
  127981. var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport;
  127982. doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport);
  127983. var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText());
  127984. return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too!
  127985. }
  127986. case 3 /* AddNew */: {
  127987. var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier;
  127988. addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined }
  127989. : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined }
  127990. : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }, /*blankLineBetween*/ true);
  127991. return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier];
  127992. }
  127993. default:
  127994. return ts.Debug.assertNever(fix, "Unexpected fix kind " + fix.kind);
  127995. }
  127996. }
  127997. function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) {
  127998. var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly;
  127999. if (defaultImport) {
  128000. ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one");
  128001. changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " });
  128002. }
  128003. if (namedImports.length) {
  128004. var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); });
  128005. if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) {
  128006. for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) {
  128007. var spec = specifiers_1[_i];
  128008. changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec);
  128009. }
  128010. }
  128011. else {
  128012. if (specifiers.length) {
  128013. var namedImports_1 = ts.createNamedImports(specifiers);
  128014. if (clause.namedBindings) {
  128015. changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1);
  128016. }
  128017. else {
  128018. changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_1);
  128019. }
  128020. }
  128021. }
  128022. }
  128023. if (convertTypeOnlyToRegular) {
  128024. changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile));
  128025. }
  128026. }
  128027. function addNamespaceQualifier(changes, sourceFile, _a) {
  128028. var namespacePrefix = _a.namespacePrefix, position = _a.position;
  128029. changes.insertText(sourceFile, position, namespacePrefix + ".");
  128030. }
  128031. function addImportType(changes, sourceFile, _a, quotePreference) {
  128032. var moduleSpecifier = _a.moduleSpecifier, position = _a.position;
  128033. changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference));
  128034. }
  128035. function getImportTypePrefix(moduleSpecifier, quotePreference) {
  128036. var quote = ts.getQuoteFromPreference(quotePreference);
  128037. return "import(" + quote + moduleSpecifier + quote + ").";
  128038. }
  128039. function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a, blankLineBetween) {
  128040. var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport;
  128041. var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
  128042. if (defaultImport !== undefined || namedImports.length) {
  128043. ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference), /*blankLineBetween*/ blankLineBetween);
  128044. }
  128045. if (namespaceLikeImport) {
  128046. ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) :
  128047. namespaceLikeImport.importKind === 4 /* ConstEquals */ ? createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier) :
  128048. ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier), /*blankLineBetween*/ blankLineBetween);
  128049. }
  128050. }
  128051. function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) {
  128052. return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
  128053. ts.createVariableDeclaration(ts.createIdentifier(name),
  128054. /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier]))
  128055. ], 2 /* Const */));
  128056. }
  128057. function symbolHasMeaning(_a, meaning) {
  128058. var declarations = _a.declarations;
  128059. return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); });
  128060. }
  128061. function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, cb) {
  128062. var filteredCount = 0;
  128063. var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host);
  128064. var allSourceFiles = program.getSourceFiles();
  128065. var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
  128066. forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) {
  128067. if (sourceFile === undefined) {
  128068. if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) {
  128069. cb(module);
  128070. }
  128071. else if (packageJson) {
  128072. filteredCount++;
  128073. }
  128074. }
  128075. else if (sourceFile &&
  128076. sourceFile !== from &&
  128077. isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) {
  128078. if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) {
  128079. cb(module);
  128080. }
  128081. else if (packageJson) {
  128082. filteredCount++;
  128083. }
  128084. }
  128085. });
  128086. if (host.log) {
  128087. host.log("forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents");
  128088. }
  128089. }
  128090. codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom;
  128091. function forEachExternalModule(checker, allSourceFiles, cb) {
  128092. for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) {
  128093. var ambient = _a[_i];
  128094. cb(ambient, /*sourceFile*/ undefined);
  128095. }
  128096. for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) {
  128097. var sourceFile = allSourceFiles_1[_b];
  128098. if (ts.isExternalOrCommonJsModule(sourceFile)) {
  128099. cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
  128100. }
  128101. }
  128102. }
  128103. /**
  128104. * Don't include something from a `node_modules` that isn't actually reachable by a global import.
  128105. * A relative import to node_modules is usually a bad idea.
  128106. */
  128107. function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) {
  128108. // If it's in a `node_modules` but is not reachable from here via a global import, don't bother.
  128109. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; });
  128110. var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules));
  128111. return toNodeModulesParent === undefined
  128112. || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent)
  128113. || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent));
  128114. }
  128115. function moduleSymbolToValidIdentifier(moduleSymbol, target) {
  128116. return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target);
  128117. }
  128118. codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier;
  128119. function moduleSpecifierToValidIdentifier(moduleSpecifier, target) {
  128120. var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index"));
  128121. var res = "";
  128122. var lastCharWasValid = true;
  128123. var firstCharCode = baseName.charCodeAt(0);
  128124. if (ts.isIdentifierStart(firstCharCode, target)) {
  128125. res += String.fromCharCode(firstCharCode);
  128126. }
  128127. else {
  128128. lastCharWasValid = false;
  128129. }
  128130. for (var i = 1; i < baseName.length; i++) {
  128131. var ch = baseName.charCodeAt(i);
  128132. var isValid = ts.isIdentifierPart(ch, target);
  128133. if (isValid) {
  128134. var char = String.fromCharCode(ch);
  128135. if (!lastCharWasValid) {
  128136. char = char.toUpperCase();
  128137. }
  128138. res += char;
  128139. }
  128140. lastCharWasValid = isValid;
  128141. }
  128142. // Need `|| "_"` to ensure result isn't empty.
  128143. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res;
  128144. }
  128145. codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier;
  128146. function createAutoImportFilter(fromFile, program, host) {
  128147. var packageJsons = host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host);
  128148. var dependencyGroups = 1 /* Dependencies */ | 2 /* DevDependencies */ | 8 /* OptionalDependencies */;
  128149. // Mix in `getProbablySymlinks` from Program when host doesn't have it
  128150. // in order for non-Project hosts to have a symlinks cache.
  128151. var moduleSpecifierResolutionHost = {
  128152. directoryExists: ts.maybeBind(host, host.directoryExists),
  128153. fileExists: ts.maybeBind(host, host.fileExists),
  128154. getCurrentDirectory: ts.maybeBind(host, host.getCurrentDirectory),
  128155. readFile: ts.maybeBind(host, host.readFile),
  128156. useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
  128157. getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks,
  128158. getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation),
  128159. };
  128160. var usesNodeCoreModules;
  128161. return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier };
  128162. function moduleSpecifierIsCoveredByPackageJson(specifier) {
  128163. var packageName = getNodeModuleRootSpecifier(specifier);
  128164. for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) {
  128165. var packageJson = packageJsons_1[_i];
  128166. if (packageJson.has(packageName, dependencyGroups) || packageJson.has(ts.getTypesPackageName(packageName), dependencyGroups)) {
  128167. return true;
  128168. }
  128169. }
  128170. return false;
  128171. }
  128172. function allowsImportingAmbientModule(moduleSymbol, allSourceFiles) {
  128173. if (!packageJsons.length) {
  128174. return true;
  128175. }
  128176. var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
  128177. var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, allSourceFiles);
  128178. if (typeof declaringNodeModuleName === "undefined") {
  128179. return true;
  128180. }
  128181. var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName());
  128182. if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) {
  128183. return true;
  128184. }
  128185. return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName)
  128186. || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
  128187. }
  128188. function allowsImportingSourceFile(sourceFile, allSourceFiles) {
  128189. if (!packageJsons.length) {
  128190. return true;
  128191. }
  128192. var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, allSourceFiles);
  128193. if (!moduleSpecifier) {
  128194. return true;
  128195. }
  128196. return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
  128197. }
  128198. /**
  128199. * Use for a specific module specifier that has already been resolved.
  128200. * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve
  128201. * the best module specifier for a given module _and_ determine if it’s importable.
  128202. */
  128203. function allowsImportingSpecifier(moduleSpecifier) {
  128204. if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) {
  128205. return true;
  128206. }
  128207. if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) {
  128208. return true;
  128209. }
  128210. return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
  128211. }
  128212. function isAllowedCoreNodeModulesImport(moduleSpecifier) {
  128213. // If we’re in JavaScript, it can be difficult to tell whether the user wants to import
  128214. // from Node core modules or not. We can start by seeing if the user is actually using
  128215. // any node core modules, as opposed to simply having @types/node accidentally as a
  128216. // dependency of a dependency.
  128217. if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) {
  128218. if (usesNodeCoreModules === undefined) {
  128219. usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile);
  128220. }
  128221. if (usesNodeCoreModules) {
  128222. return true;
  128223. }
  128224. }
  128225. return false;
  128226. }
  128227. function getNodeModulesPackageNameFromFileName(importedFileName, allSourceFiles) {
  128228. if (!ts.stringContains(importedFileName, "node_modules")) {
  128229. return undefined;
  128230. }
  128231. var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost, allSourceFiles, program.redirectTargetsMap);
  128232. if (!specifier) {
  128233. return undefined;
  128234. }
  128235. // Paths here are not node_modules, so we don’t care about them;
  128236. // returning anything will trigger a lookup in package.json.
  128237. if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) {
  128238. return getNodeModuleRootSpecifier(specifier);
  128239. }
  128240. }
  128241. function getNodeModuleRootSpecifier(fullSpecifier) {
  128242. var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1);
  128243. // Scoped packages
  128244. if (ts.startsWith(components[0], "@")) {
  128245. return components[0] + "/" + components[1];
  128246. }
  128247. return components[0];
  128248. }
  128249. }
  128250. })(codefix = ts.codefix || (ts.codefix = {}));
  128251. })(ts || (ts = {}));
  128252. /* @internal */
  128253. var ts;
  128254. (function (ts) {
  128255. var codefix;
  128256. (function (codefix) {
  128257. var fixId = "fixSpelling";
  128258. var errorCodes = [
  128259. ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
  128260. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
  128261. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  128262. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
  128263. ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code,
  128264. ];
  128265. codefix.registerCodeFix({
  128266. errorCodes: errorCodes,
  128267. getCodeActions: function (context) {
  128268. var sourceFile = context.sourceFile;
  128269. var info = getInfo(sourceFile, context.span.start, context);
  128270. if (!info)
  128271. return undefined;
  128272. var node = info.node, suggestedSymbol = info.suggestedSymbol;
  128273. var target = context.host.getCompilationSettings().target;
  128274. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); });
  128275. return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)];
  128276. },
  128277. fixIds: [fixId],
  128278. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  128279. var info = getInfo(diag.file, diag.start, context);
  128280. var target = context.host.getCompilationSettings().target;
  128281. if (info)
  128282. doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target);
  128283. }); },
  128284. });
  128285. function getInfo(sourceFile, pos, context) {
  128286. // This is the identifier of the misspelled word. eg:
  128287. // this.speling = 1;
  128288. // ^^^^^^^
  128289. var node = ts.getTokenAtPosition(sourceFile, pos);
  128290. var checker = context.program.getTypeChecker();
  128291. var suggestedSymbol;
  128292. if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) {
  128293. ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)");
  128294. var containingType = checker.getTypeAtLocation(node.parent.expression);
  128295. if (node.parent.flags & 32 /* OptionalChain */) {
  128296. containingType = checker.getNonNullableType(containingType);
  128297. }
  128298. var name = node;
  128299. suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType);
  128300. }
  128301. else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) {
  128302. ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (import)");
  128303. var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration);
  128304. var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration);
  128305. if (resolvedSourceFile && resolvedSourceFile.symbol) {
  128306. suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol);
  128307. }
  128308. }
  128309. else {
  128310. var meaning = ts.getMeaningFromLocation(node);
  128311. var name = ts.getTextOfNode(node);
  128312. ts.Debug.assert(name !== undefined, "name should be defined");
  128313. suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
  128314. }
  128315. return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol };
  128316. }
  128317. function doChange(changes, sourceFile, node, suggestedSymbol, target) {
  128318. var suggestion = ts.symbolName(suggestedSymbol);
  128319. if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) {
  128320. var valDecl = suggestedSymbol.valueDeclaration;
  128321. if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) {
  128322. changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
  128323. }
  128324. else {
  128325. changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion)));
  128326. }
  128327. }
  128328. else {
  128329. changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
  128330. }
  128331. }
  128332. function convertSemanticMeaningToSymbolFlags(meaning) {
  128333. var flags = 0;
  128334. if (meaning & 4 /* Namespace */) {
  128335. flags |= 1920 /* Namespace */;
  128336. }
  128337. if (meaning & 2 /* Type */) {
  128338. flags |= 788968 /* Type */;
  128339. }
  128340. if (meaning & 1 /* Value */) {
  128341. flags |= 111551 /* Value */;
  128342. }
  128343. return flags;
  128344. }
  128345. function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) {
  128346. if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier))
  128347. return undefined;
  128348. var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text);
  128349. if (!resolvedModule)
  128350. return undefined;
  128351. return context.program.getSourceFile(resolvedModule.resolvedFileName);
  128352. }
  128353. })(codefix = ts.codefix || (ts.codefix = {}));
  128354. })(ts || (ts = {}));
  128355. /* @internal */
  128356. var ts;
  128357. (function (ts) {
  128358. var codefix;
  128359. (function (codefix) {
  128360. var fixName = "addMissingMember";
  128361. var errorCodes = [
  128362. ts.Diagnostics.Property_0_does_not_exist_on_type_1.code,
  128363. ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
  128364. ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
  128365. ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
  128366. ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code
  128367. ];
  128368. var fixId = "addMissingMember";
  128369. codefix.registerCodeFix({
  128370. errorCodes: errorCodes,
  128371. getCodeActions: function (context) {
  128372. var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker(), context.program);
  128373. if (!info)
  128374. return undefined;
  128375. if (info.kind === 0 /* Enum */) {
  128376. var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration;
  128377. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); });
  128378. return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)];
  128379. }
  128380. var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
  128381. var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences);
  128382. var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ?
  128383. ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) :
  128384. getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic);
  128385. return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember);
  128386. },
  128387. fixIds: [fixId],
  128388. getAllCodeActions: function (context) {
  128389. var program = context.program, preferences = context.preferences;
  128390. var checker = program.getTypeChecker();
  128391. var seen = ts.createMap();
  128392. var typeDeclToMembers = new ts.NodeMap();
  128393. return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
  128394. codefix.eachDiagnostic(context, errorCodes, function (diag) {
  128395. var info = getInfo(diag.file, diag.start, checker, context.program);
  128396. if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
  128397. return;
  128398. }
  128399. if (info.kind === 0 /* Enum */) {
  128400. var token = info.token, parentDeclaration = info.parentDeclaration;
  128401. addEnumMemberDeclaration(changes, checker, token, parentDeclaration);
  128402. }
  128403. else {
  128404. var parentDeclaration = info.parentDeclaration, token_2 = info.token;
  128405. var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; });
  128406. if (!infos.some(function (i) { return i.token.text === token_2.text; }))
  128407. infos.push(info);
  128408. }
  128409. });
  128410. typeDeclToMembers.forEach(function (infos, classDeclaration) {
  128411. var supers = getAllSupers(classDeclaration, checker);
  128412. var _loop_14 = function (info) {
  128413. // If some superclass added this property, don't add it again.
  128414. if (supers.some(function (superClassOrInterface) {
  128415. var superInfos = typeDeclToMembers.get(superClassOrInterface);
  128416. return !!superInfos && superInfos.some(function (_a) {
  128417. var token = _a.token;
  128418. return token.text === info.token.text;
  128419. });
  128420. }))
  128421. return "continue";
  128422. var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
  128423. // Always prefer to add a method declaration if possible.
  128424. if (call && !ts.isPrivateIdentifier(token)) {
  128425. addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences);
  128426. }
  128427. else {
  128428. if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) {
  128429. addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, makeStatic);
  128430. }
  128431. else {
  128432. var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token);
  128433. addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic);
  128434. }
  128435. }
  128436. };
  128437. for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
  128438. var info = infos_1[_i];
  128439. _loop_14(info);
  128440. }
  128441. });
  128442. }));
  128443. },
  128444. });
  128445. function getAllSupers(decl, checker) {
  128446. var res = [];
  128447. while (decl) {
  128448. var superElement = ts.getClassExtendsHeritageElement(decl);
  128449. var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
  128450. var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike);
  128451. if (superDecl) {
  128452. res.push(superDecl);
  128453. }
  128454. decl = superDecl;
  128455. }
  128456. return res;
  128457. }
  128458. var InfoKind;
  128459. (function (InfoKind) {
  128460. InfoKind[InfoKind["Enum"] = 0] = "Enum";
  128461. InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface";
  128462. })(InfoKind || (InfoKind = {}));
  128463. function getInfo(tokenSourceFile, tokenPos, checker, program) {
  128464. // The identifier of the missing property. eg:
  128465. // this.missing = 1;
  128466. // ^^^^^^^
  128467. var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos);
  128468. if (!ts.isIdentifier(token) && !ts.isPrivateIdentifier(token)) {
  128469. return undefined;
  128470. }
  128471. var parent = token.parent;
  128472. if (!ts.isPropertyAccessExpression(parent))
  128473. return undefined;
  128474. var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression));
  128475. var symbol = leftExpressionType.symbol;
  128476. if (!symbol || !symbol.declarations)
  128477. return undefined;
  128478. var isClass = ts.find(symbol.declarations, ts.isClassLike);
  128479. // Don't suggest adding private identifiers to anything other than a class.
  128480. if (!isClass && ts.isPrivateIdentifier(token)) {
  128481. return undefined;
  128482. }
  128483. // Prefer to change the class instead of the interface if they are merged
  128484. var classOrInterface = isClass || ts.find(symbol.declarations, ts.isInterfaceDeclaration);
  128485. if (classOrInterface && !program.isSourceFileFromExternalLibrary(classOrInterface.getSourceFile())) {
  128486. var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
  128487. // Static private identifier properties are not supported yet.
  128488. if (makeStatic && ts.isPrivateIdentifier(token))
  128489. return undefined;
  128490. var declSourceFile = classOrInterface.getSourceFile();
  128491. var inJs = ts.isSourceFileJS(declSourceFile);
  128492. var call = ts.tryCast(parent.parent, ts.isCallExpression);
  128493. return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call };
  128494. }
  128495. var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration);
  128496. if (enumDeclaration && !ts.isPrivateIdentifier(token) && !program.isSourceFileFromExternalLibrary(enumDeclaration.getSourceFile())) {
  128497. return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration };
  128498. }
  128499. return undefined;
  128500. }
  128501. function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
  128502. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, token, makeStatic); });
  128503. if (changes.length === 0) {
  128504. return undefined;
  128505. }
  128506. var diagnostic = makeStatic ? ts.Diagnostics.Initialize_static_property_0 :
  128507. ts.isPrivateIdentifier(token) ? ts.Diagnostics.Declare_a_private_field_named_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor;
  128508. return codefix.createCodeFixAction(fixName, changes, [diagnostic, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
  128509. }
  128510. function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) {
  128511. var tokenName = token.text;
  128512. if (makeStatic) {
  128513. if (classDeclaration.kind === 214 /* ClassExpression */) {
  128514. return;
  128515. }
  128516. var className = classDeclaration.name.getText();
  128517. var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName);
  128518. changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization);
  128519. }
  128520. else if (ts.isPrivateIdentifier(token)) {
  128521. var property = ts.createProperty(
  128522. /*decorators*/ undefined,
  128523. /*modifiers*/ undefined, tokenName,
  128524. /*questionToken*/ undefined,
  128525. /*type*/ undefined,
  128526. /*initializer*/ undefined);
  128527. var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
  128528. if (lastProp) {
  128529. changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
  128530. }
  128531. else {
  128532. changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
  128533. }
  128534. }
  128535. else {
  128536. var classConstructor = ts.getFirstConstructorWithBody(classDeclaration);
  128537. if (!classConstructor) {
  128538. return;
  128539. }
  128540. var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName);
  128541. changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization);
  128542. }
  128543. }
  128544. function initializePropertyToUndefined(obj, propertyName) {
  128545. return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined")));
  128546. }
  128547. function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
  128548. var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token);
  128549. var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode);
  128550. return makeStatic || ts.isPrivateIdentifier(token) ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)];
  128551. }
  128552. function getTypeNode(checker, classDeclaration, token) {
  128553. var typeNode;
  128554. if (token.parent.parent.kind === 209 /* BinaryExpression */) {
  128555. var binaryExpression = token.parent.parent;
  128556. var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
  128557. var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
  128558. typeNode = checker.typeToTypeNode(widenedType, classDeclaration);
  128559. }
  128560. else {
  128561. var contextualType = checker.getContextualType(token.parent);
  128562. typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined;
  128563. }
  128564. return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */);
  128565. }
  128566. function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) {
  128567. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); });
  128568. return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members);
  128569. }
  128570. function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) {
  128571. var property = ts.createProperty(
  128572. /*decorators*/ undefined,
  128573. /*modifiers*/ makeStatic ? [ts.createToken(120 /* StaticKeyword */)] : undefined, tokenName,
  128574. /*questionToken*/ undefined, typeNode,
  128575. /*initializer*/ undefined);
  128576. var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
  128577. if (lastProp) {
  128578. changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
  128579. }
  128580. else {
  128581. changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
  128582. }
  128583. }
  128584. // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
  128585. function getNodeToInsertPropertyAfter(cls) {
  128586. var res;
  128587. for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
  128588. var member = _a[_i];
  128589. if (!ts.isPropertyDeclaration(member))
  128590. break;
  128591. res = member;
  128592. }
  128593. return res;
  128594. }
  128595. function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) {
  128596. // Index signatures cannot have the static modifier.
  128597. var stringTypeNode = ts.createKeywordTypeNode(143 /* StringKeyword */);
  128598. var indexingParameter = ts.createParameter(
  128599. /*decorators*/ undefined,
  128600. /*modifiers*/ undefined,
  128601. /*dotDotDotToken*/ undefined, "x",
  128602. /*questionToken*/ undefined, stringTypeNode,
  128603. /*initializer*/ undefined);
  128604. var indexSignature = ts.createIndexSignature(
  128605. /*decorators*/ undefined,
  128606. /*modifiers*/ undefined, [indexingParameter], typeNode);
  128607. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); });
  128608. // No fixId here because code-fix-all currently only works on adding individual named properties.
  128609. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
  128610. }
  128611. function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) {
  128612. // Private methods are not implemented yet.
  128613. if (ts.isPrivateIdentifier(token)) {
  128614. return undefined;
  128615. }
  128616. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); });
  128617. return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
  128618. }
  128619. function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) {
  128620. var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl);
  128621. var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */);
  128622. if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) {
  128623. changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration);
  128624. }
  128625. else {
  128626. changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration);
  128627. }
  128628. }
  128629. function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) {
  128630. /**
  128631. * create initializer only literal enum that has string initializer.
  128632. * value of initializer is a string literal that equal to name of enum member.
  128633. * numeric enum or empty enum will not create initializer.
  128634. */
  128635. var hasStringInitializer = ts.some(enumDeclaration.members, function (member) {
  128636. var type = checker.getTypeAtLocation(member);
  128637. return !!(type && type.flags & 132 /* StringLike */);
  128638. });
  128639. var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined);
  128640. changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))));
  128641. }
  128642. })(codefix = ts.codefix || (ts.codefix = {}));
  128643. })(ts || (ts = {}));
  128644. /* @internal */
  128645. var ts;
  128646. (function (ts) {
  128647. var codefix;
  128648. (function (codefix) {
  128649. var fixId = "addMissingNewOperator";
  128650. var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
  128651. codefix.registerCodeFix({
  128652. errorCodes: errorCodes,
  128653. getCodeActions: function (context) {
  128654. var sourceFile = context.sourceFile, span = context.span;
  128655. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
  128656. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
  128657. },
  128658. fixIds: [fixId],
  128659. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  128660. return addMissingNewOperator(changes, context.sourceFile, diag);
  128661. }); },
  128662. });
  128663. function addMissingNewOperator(changes, sourceFile, span) {
  128664. var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
  128665. var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
  128666. changes.replaceNode(sourceFile, call, newExpression);
  128667. }
  128668. function findAncestorMatchingSpan(sourceFile, span) {
  128669. var token = ts.getTokenAtPosition(sourceFile, span.start);
  128670. var end = ts.textSpanEnd(span);
  128671. while (token.end < end) {
  128672. token = token.parent;
  128673. }
  128674. return token;
  128675. }
  128676. })(codefix = ts.codefix || (ts.codefix = {}));
  128677. })(ts || (ts = {}));
  128678. /* @internal */
  128679. var ts;
  128680. (function (ts) {
  128681. var codefix;
  128682. (function (codefix) {
  128683. var fixName = "fixCannotFindModule";
  128684. var fixIdInstallTypesPackage = "installTypesPackage";
  128685. var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code;
  128686. var errorCodes = [
  128687. errorCodeCannotFindModule,
  128688. ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code,
  128689. ];
  128690. codefix.registerCodeFix({
  128691. errorCodes: errorCodes,
  128692. getCodeActions: function (context) {
  128693. var host = context.host, sourceFile = context.sourceFile, start = context.span.start;
  128694. var packageName = tryGetImportedPackageName(sourceFile, start);
  128695. if (packageName === undefined)
  128696. return undefined;
  128697. var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode);
  128698. return typesPackageName === undefined
  128699. ? []
  128700. : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))];
  128701. },
  128702. fixIds: [fixIdInstallTypesPackage],
  128703. getAllCodeActions: function (context) {
  128704. return codefix.codeFixAll(context, errorCodes, function (_changes, diag, commands) {
  128705. var packageName = tryGetImportedPackageName(diag.file, diag.start);
  128706. if (packageName === undefined)
  128707. return undefined;
  128708. switch (context.fixId) {
  128709. case fixIdInstallTypesPackage: {
  128710. var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code);
  128711. if (pkg) {
  128712. commands.push(getInstallCommand(diag.file.fileName, pkg));
  128713. }
  128714. break;
  128715. }
  128716. default:
  128717. ts.Debug.fail("Bad fixId: " + context.fixId);
  128718. }
  128719. });
  128720. },
  128721. });
  128722. function getInstallCommand(fileName, packageName) {
  128723. return { type: "install package", file: fileName, packageName: packageName };
  128724. }
  128725. function tryGetImportedPackageName(sourceFile, pos) {
  128726. var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text;
  128727. var packageName = ts.parsePackageName(moduleName).packageName;
  128728. return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName;
  128729. }
  128730. function getTypesPackageNameToInstall(packageName, host, diagCode) {
  128731. return diagCode === errorCodeCannotFindModule
  128732. ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
  128733. : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217
  128734. }
  128735. })(codefix = ts.codefix || (ts.codefix = {}));
  128736. })(ts || (ts = {}));
  128737. /* @internal */
  128738. var ts;
  128739. (function (ts) {
  128740. var codefix;
  128741. (function (codefix) {
  128742. var errorCodes = [
  128743. ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code,
  128744. ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code,
  128745. ];
  128746. var fixId = "fixClassDoesntImplementInheritedAbstractMember";
  128747. codefix.registerCodeFix({
  128748. errorCodes: errorCodes,
  128749. getCodeActions: function (context) {
  128750. var sourceFile = context.sourceFile, span = context.span;
  128751. var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
  128752. return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences);
  128753. });
  128754. return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)];
  128755. },
  128756. fixIds: [fixId],
  128757. getAllCodeActions: function (context) {
  128758. var seenClassDeclarations = ts.createMap();
  128759. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  128760. var classDeclaration = getClass(diag.file, diag.start);
  128761. if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
  128762. addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences);
  128763. }
  128764. });
  128765. },
  128766. });
  128767. function getClass(sourceFile, pos) {
  128768. // Token is the identifier in the case of a class declaration
  128769. // or the class keyword token in the case of a class expression.
  128770. var token = ts.getTokenAtPosition(sourceFile, pos);
  128771. return ts.cast(token.parent, ts.isClassLike);
  128772. }
  128773. function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) {
  128774. var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration);
  128775. var checker = context.program.getTypeChecker();
  128776. var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
  128777. // Note that this is ultimately derived from a map indexed by symbol names,
  128778. // so duplicates cannot occur.
  128779. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
  128780. codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); });
  128781. }
  128782. function symbolPointsToNonPrivateAndAbstractMember(symbol) {
  128783. // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files
  128784. // (now named `codeFixClassExtendAbstractPrivateProperty.ts`)
  128785. var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations()));
  128786. return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */);
  128787. }
  128788. })(codefix = ts.codefix || (ts.codefix = {}));
  128789. })(ts || (ts = {}));
  128790. /* @internal */
  128791. var ts;
  128792. (function (ts) {
  128793. var codefix;
  128794. (function (codefix) {
  128795. var fixId = "classSuperMustPrecedeThisAccess";
  128796. var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code];
  128797. codefix.registerCodeFix({
  128798. errorCodes: errorCodes,
  128799. getCodeActions: function (context) {
  128800. var sourceFile = context.sourceFile, span = context.span;
  128801. var nodes = getNodes(sourceFile, span.start);
  128802. if (!nodes)
  128803. return undefined;
  128804. var constructor = nodes.constructor, superCall = nodes.superCall;
  128805. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); });
  128806. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)];
  128807. },
  128808. fixIds: [fixId],
  128809. getAllCodeActions: function (context) {
  128810. var sourceFile = context.sourceFile;
  128811. var seenClasses = ts.createMap(); // Ensure we only do this once per class.
  128812. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  128813. var nodes = getNodes(diag.file, diag.start);
  128814. if (!nodes)
  128815. return;
  128816. var constructor = nodes.constructor, superCall = nodes.superCall;
  128817. if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) {
  128818. doChange(changes, sourceFile, constructor, superCall);
  128819. }
  128820. });
  128821. },
  128822. });
  128823. function doChange(changes, sourceFile, constructor, superCall) {
  128824. changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
  128825. changes.delete(sourceFile, superCall);
  128826. }
  128827. function getNodes(sourceFile, pos) {
  128828. var token = ts.getTokenAtPosition(sourceFile, pos);
  128829. if (token.kind !== 104 /* ThisKeyword */)
  128830. return undefined;
  128831. var constructor = ts.getContainingFunction(token);
  128832. var superCall = findSuperCall(constructor.body);
  128833. // figure out if the `this` access is actually inside the supercall
  128834. // i.e. super(this.a), since in that case we won't suggest a fix
  128835. return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined;
  128836. }
  128837. function findSuperCall(n) {
  128838. return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression)
  128839. ? n
  128840. : ts.isFunctionLike(n)
  128841. ? undefined
  128842. : ts.forEachChild(n, findSuperCall);
  128843. }
  128844. })(codefix = ts.codefix || (ts.codefix = {}));
  128845. })(ts || (ts = {}));
  128846. /* @internal */
  128847. var ts;
  128848. (function (ts) {
  128849. var codefix;
  128850. (function (codefix) {
  128851. var fixId = "constructorForDerivedNeedSuperCall";
  128852. var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code];
  128853. codefix.registerCodeFix({
  128854. errorCodes: errorCodes,
  128855. getCodeActions: function (context) {
  128856. var sourceFile = context.sourceFile, span = context.span;
  128857. var ctr = getNode(sourceFile, span.start);
  128858. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); });
  128859. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)];
  128860. },
  128861. fixIds: [fixId],
  128862. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  128863. return doChange(changes, context.sourceFile, getNode(diag.file, diag.start));
  128864. }); },
  128865. });
  128866. function getNode(sourceFile, pos) {
  128867. var token = ts.getTokenAtPosition(sourceFile, pos);
  128868. ts.Debug.assert(token.kind === 129 /* ConstructorKeyword */, "token should be at the constructor keyword");
  128869. return token.parent;
  128870. }
  128871. function doChange(changes, sourceFile, ctr) {
  128872. var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray));
  128873. changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall);
  128874. }
  128875. })(codefix = ts.codefix || (ts.codefix = {}));
  128876. })(ts || (ts = {}));
  128877. /* @internal */
  128878. var ts;
  128879. (function (ts) {
  128880. var codefix;
  128881. (function (codefix) {
  128882. var fixId = "enableExperimentalDecorators";
  128883. var errorCodes = [
  128884. ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning.code
  128885. ];
  128886. codefix.registerCodeFix({
  128887. errorCodes: errorCodes,
  128888. getCodeActions: function (context) {
  128889. var configFile = context.program.getCompilerOptions().configFile;
  128890. if (configFile === undefined) {
  128891. return undefined;
  128892. }
  128893. var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); });
  128894. return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
  128895. },
  128896. fixIds: [fixId],
  128897. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) {
  128898. var configFile = context.program.getCompilerOptions().configFile;
  128899. if (configFile === undefined) {
  128900. return undefined;
  128901. }
  128902. doChange(changes, configFile);
  128903. }); },
  128904. });
  128905. function doChange(changeTracker, configFile) {
  128906. codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue());
  128907. }
  128908. })(codefix = ts.codefix || (ts.codefix = {}));
  128909. })(ts || (ts = {}));
  128910. /* @internal */
  128911. var ts;
  128912. (function (ts) {
  128913. var codefix;
  128914. (function (codefix) {
  128915. var fixID = "fixEnableJsxFlag";
  128916. var errorCodes = [ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code];
  128917. codefix.registerCodeFix({
  128918. errorCodes: errorCodes,
  128919. getCodeActions: function (context) {
  128920. var configFile = context.program.getCompilerOptions().configFile;
  128921. if (configFile === undefined) {
  128922. return undefined;
  128923. }
  128924. var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) {
  128925. return doChange(changeTracker, configFile);
  128926. });
  128927. return [
  128928. codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file)
  128929. ];
  128930. },
  128931. fixIds: [fixID],
  128932. getAllCodeActions: function (context) {
  128933. return codefix.codeFixAll(context, errorCodes, function (changes) {
  128934. var configFile = context.program.getCompilerOptions().configFile;
  128935. if (configFile === undefined) {
  128936. return undefined;
  128937. }
  128938. doChange(changes, configFile);
  128939. });
  128940. }
  128941. });
  128942. function doChange(changeTracker, configFile) {
  128943. codefix.setJsonCompilerOptionValue(changeTracker, configFile, "jsx", ts.createStringLiteral("react"));
  128944. }
  128945. })(codefix = ts.codefix || (ts.codefix = {}));
  128946. })(ts || (ts = {}));
  128947. /* @internal */
  128948. var ts;
  128949. (function (ts) {
  128950. var codefix;
  128951. (function (codefix) {
  128952. codefix.registerCodeFix({
  128953. errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code],
  128954. getCodeActions: function (context) {
  128955. var compilerOptions = context.program.getCompilerOptions();
  128956. var configFile = compilerOptions.configFile;
  128957. if (configFile === undefined) {
  128958. return undefined;
  128959. }
  128960. var codeFixes = [];
  128961. var moduleKind = ts.getEmitModuleKind(compilerOptions);
  128962. var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext;
  128963. if (moduleOutOfRange) {
  128964. var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
  128965. codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext"));
  128966. });
  128967. codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"]));
  128968. }
  128969. var target = ts.getEmitScriptTarget(compilerOptions);
  128970. var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */;
  128971. if (targetOutOfRange) {
  128972. var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
  128973. var configObject = ts.getTsConfigObjectLiteralExpression(configFile);
  128974. if (!configObject)
  128975. return;
  128976. var options = [["target", ts.createStringLiteral("es2017")]];
  128977. if (moduleKind === ts.ModuleKind.CommonJS) {
  128978. // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015.
  128979. options.push(["module", ts.createStringLiteral("commonjs")]);
  128980. }
  128981. codefix.setJsonCompilerOptionValues(tracker, configFile, options);
  128982. });
  128983. codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"]));
  128984. }
  128985. return codeFixes.length ? codeFixes : undefined;
  128986. }
  128987. });
  128988. })(codefix = ts.codefix || (ts.codefix = {}));
  128989. })(ts || (ts = {}));
  128990. /* @internal */
  128991. var ts;
  128992. (function (ts) {
  128993. var codefix;
  128994. (function (codefix) {
  128995. var fixId = "extendsInterfaceBecomesImplements";
  128996. var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
  128997. codefix.registerCodeFix({
  128998. errorCodes: errorCodes,
  128999. getCodeActions: function (context) {
  129000. var sourceFile = context.sourceFile;
  129001. var nodes = getNodes(sourceFile, context.span.start);
  129002. if (!nodes)
  129003. return undefined;
  129004. var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses;
  129005. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); });
  129006. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)];
  129007. },
  129008. fixIds: [fixId],
  129009. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  129010. var nodes = getNodes(diag.file, diag.start);
  129011. if (nodes)
  129012. doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses);
  129013. }); },
  129014. });
  129015. function getNodes(sourceFile, pos) {
  129016. var token = ts.getTokenAtPosition(sourceFile, pos);
  129017. var heritageClauses = ts.getContainingClass(token).heritageClauses;
  129018. var extendsToken = heritageClauses[0].getFirstToken();
  129019. return extendsToken.kind === 90 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined;
  129020. }
  129021. function doChanges(changes, sourceFile, extendsToken, heritageClauses) {
  129022. changes.replaceNode(sourceFile, extendsToken, ts.createToken(113 /* ImplementsKeyword */));
  129023. // If there is already an implements clause, replace the implements keyword with a comma.
  129024. if (heritageClauses.length === 2 &&
  129025. heritageClauses[0].token === 90 /* ExtendsKeyword */ &&
  129026. heritageClauses[1].token === 113 /* ImplementsKeyword */) {
  129027. var implementsToken = heritageClauses[1].getFirstToken();
  129028. var implementsFullStart = implementsToken.getFullStart();
  129029. changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */));
  129030. // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive.
  129031. // (Trailing because leading might be indentation, which is more sensitive.)
  129032. var text = sourceFile.text;
  129033. var end = implementsToken.end;
  129034. while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) {
  129035. end++;
  129036. }
  129037. changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end });
  129038. }
  129039. }
  129040. })(codefix = ts.codefix || (ts.codefix = {}));
  129041. })(ts || (ts = {}));
  129042. /* @internal */
  129043. var ts;
  129044. (function (ts) {
  129045. var codefix;
  129046. (function (codefix) {
  129047. var fixId = "forgottenThisPropertyAccess";
  129048. var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
  129049. var errorCodes = [
  129050. ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  129051. ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
  129052. didYouMeanStaticMemberCode,
  129053. ];
  129054. codefix.registerCodeFix({
  129055. errorCodes: errorCodes,
  129056. getCodeActions: function (context) {
  129057. var sourceFile = context.sourceFile;
  129058. var info = getInfo(sourceFile, context.span.start, context.errorCode);
  129059. if (!info) {
  129060. return undefined;
  129061. }
  129062. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
  129063. return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)];
  129064. },
  129065. fixIds: [fixId],
  129066. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  129067. var info = getInfo(diag.file, diag.start, diag.code);
  129068. if (info)
  129069. doChange(changes, context.sourceFile, info);
  129070. }); },
  129071. });
  129072. function getInfo(sourceFile, pos, diagCode) {
  129073. var node = ts.getTokenAtPosition(sourceFile, pos);
  129074. if (ts.isIdentifier(node)) {
  129075. return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined };
  129076. }
  129077. }
  129078. function doChange(changes, sourceFile, _a) {
  129079. var node = _a.node, className = _a.className;
  129080. // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper
  129081. ts.suppressLeadingAndTrailingTrivia(node);
  129082. changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node));
  129083. }
  129084. })(codefix = ts.codefix || (ts.codefix = {}));
  129085. })(ts || (ts = {}));
  129086. /* @internal */
  129087. var ts;
  129088. (function (ts) {
  129089. var codefix;
  129090. (function (codefix) {
  129091. var fixName = "unusedIdentifier";
  129092. var fixIdPrefix = "unusedIdentifier_prefix";
  129093. var fixIdDelete = "unusedIdentifier_delete";
  129094. var fixIdInfer = "unusedIdentifier_infer";
  129095. var errorCodes = [
  129096. ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code,
  129097. ts.Diagnostics._0_is_declared_but_never_used.code,
  129098. ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
  129099. ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
  129100. ts.Diagnostics.All_destructured_elements_are_unused.code,
  129101. ts.Diagnostics.All_variables_are_unused.code,
  129102. ts.Diagnostics.All_type_parameters_are_unused.code,
  129103. ];
  129104. codefix.registerCodeFix({
  129105. errorCodes: errorCodes,
  129106. getCodeActions: function (context) {
  129107. var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program;
  129108. var checker = program.getTypeChecker();
  129109. var sourceFiles = program.getSourceFiles();
  129110. var token = ts.getTokenAtPosition(sourceFile, context.span.start);
  129111. if (ts.isJSDocTemplateTag(token)) {
  129112. return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)];
  129113. }
  129114. if (token.kind === 29 /* LessThanToken */) {
  129115. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); });
  129116. return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)];
  129117. }
  129118. var importDecl = tryGetFullImport(token);
  129119. if (importDecl) {
  129120. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); });
  129121. return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])];
  129122. }
  129123. var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) {
  129124. return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false);
  129125. });
  129126. if (delDestructure.length) {
  129127. return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)];
  129128. }
  129129. var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); });
  129130. if (delVar.length) {
  129131. return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)];
  129132. }
  129133. var result = [];
  129134. if (token.kind === 132 /* InferKeyword */) {
  129135. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); });
  129136. var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text;
  129137. result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown));
  129138. }
  129139. else {
  129140. var deletion = ts.textChanges.ChangeTracker.with(context, function (t) {
  129141. return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false);
  129142. });
  129143. if (deletion.length) {
  129144. var name = ts.isComputedPropertyName(token.parent) ? token.parent : token;
  129145. result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)]));
  129146. }
  129147. }
  129148. var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); });
  129149. if (prefix.length) {
  129150. result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible));
  129151. }
  129152. return result;
  129153. },
  129154. fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer],
  129155. getAllCodeActions: function (context) {
  129156. var sourceFile = context.sourceFile, program = context.program;
  129157. var checker = program.getTypeChecker();
  129158. var sourceFiles = program.getSourceFiles();
  129159. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  129160. var token = ts.getTokenAtPosition(sourceFile, diag.start);
  129161. switch (context.fixId) {
  129162. case fixIdPrefix:
  129163. tryPrefixDeclaration(changes, diag.code, sourceFile, token);
  129164. break;
  129165. case fixIdDelete: {
  129166. if (token.kind === 132 /* InferKeyword */)
  129167. break; // Can't delete
  129168. var importDecl = tryGetFullImport(token);
  129169. if (importDecl) {
  129170. changes.delete(sourceFile, importDecl);
  129171. }
  129172. else if (ts.isJSDocTemplateTag(token)) {
  129173. changes.delete(sourceFile, token);
  129174. }
  129175. else if (token.kind === 29 /* LessThanToken */) {
  129176. deleteTypeParameters(changes, sourceFile, token);
  129177. }
  129178. else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) &&
  129179. !tryDeleteFullVariableStatement(sourceFile, token, changes)) {
  129180. tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true);
  129181. }
  129182. break;
  129183. }
  129184. case fixIdInfer:
  129185. if (token.kind === 132 /* InferKeyword */) {
  129186. changeInferToUnknown(changes, sourceFile, token);
  129187. }
  129188. break;
  129189. default:
  129190. ts.Debug.fail(JSON.stringify(context.fixId));
  129191. }
  129192. });
  129193. },
  129194. });
  129195. function changeInferToUnknown(changes, sourceFile, token) {
  129196. changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(148 /* UnknownKeyword */));
  129197. }
  129198. function createDeleteFix(changes, diag) {
  129199. return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations);
  129200. }
  129201. function deleteTypeParameters(changes, sourceFile, token) {
  129202. changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
  129203. }
  129204. // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
  129205. function tryGetFullImport(token) {
  129206. return token.kind === 96 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined;
  129207. }
  129208. function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
  129209. if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent))
  129210. return false;
  129211. var decl = token.parent.parent;
  129212. if (decl.kind === 156 /* Parameter */) {
  129213. tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll);
  129214. }
  129215. else {
  129216. changes.delete(sourceFile, decl);
  129217. }
  129218. return true;
  129219. }
  129220. function tryDeleteFullVariableStatement(sourceFile, token, changes) {
  129221. var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList);
  129222. if (declarationList && declarationList.getChildren(sourceFile)[0] === token) {
  129223. changes.delete(sourceFile, declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList);
  129224. return true;
  129225. }
  129226. return false;
  129227. }
  129228. function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
  129229. // Don't offer to prefix a property.
  129230. if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code)
  129231. return;
  129232. if (token.kind === 132 /* InferKeyword */) {
  129233. token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name;
  129234. }
  129235. if (ts.isIdentifier(token) && canPrefix(token)) {
  129236. changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text));
  129237. }
  129238. }
  129239. function canPrefix(token) {
  129240. switch (token.parent.kind) {
  129241. case 156 /* Parameter */:
  129242. case 155 /* TypeParameter */:
  129243. return true;
  129244. case 242 /* VariableDeclaration */: {
  129245. var varDecl = token.parent;
  129246. switch (varDecl.parent.parent.kind) {
  129247. case 232 /* ForOfStatement */:
  129248. case 231 /* ForInStatement */:
  129249. return true;
  129250. }
  129251. }
  129252. }
  129253. return false;
  129254. }
  129255. function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) {
  129256. tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll);
  129257. if (ts.isIdentifier(token))
  129258. deleteAssignments(changes, sourceFile, token, checker);
  129259. }
  129260. function deleteAssignments(changes, sourceFile, token, checker) {
  129261. ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
  129262. if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref)
  129263. ref = ref.parent;
  129264. if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) {
  129265. changes.delete(sourceFile, ref.parent.parent);
  129266. }
  129267. });
  129268. }
  129269. function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
  129270. var parent = token.parent;
  129271. if (ts.isParameter(parent)) {
  129272. tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll);
  129273. }
  129274. else {
  129275. changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent);
  129276. }
  129277. }
  129278. function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) {
  129279. if (mayDeleteParameter(p, checker, isFixAll)) {
  129280. if (p.modifiers && p.modifiers.length > 0
  129281. && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) {
  129282. p.modifiers.forEach(function (modifier) {
  129283. changes.deleteModifier(sourceFile, modifier);
  129284. });
  129285. }
  129286. else {
  129287. changes.delete(sourceFile, p);
  129288. deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker);
  129289. }
  129290. }
  129291. }
  129292. function mayDeleteParameter(p, checker, isFixAll) {
  129293. var parent = p.parent;
  129294. switch (parent.kind) {
  129295. case 161 /* MethodDeclaration */:
  129296. // Don't remove a parameter if this overrides something.
  129297. var symbol = checker.getSymbolAtLocation(parent.name);
  129298. if (ts.isMemberSymbolInBaseType(symbol, checker))
  129299. return false;
  129300. // falls through
  129301. case 162 /* Constructor */:
  129302. case 244 /* FunctionDeclaration */:
  129303. return true;
  129304. case 201 /* FunctionExpression */:
  129305. case 202 /* ArrowFunction */: {
  129306. // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused.
  129307. var parameters = parent.parameters;
  129308. var index = parameters.indexOf(p);
  129309. ts.Debug.assert(index !== -1, "The parameter should already be in the list");
  129310. return isFixAll
  129311. ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 75 /* Identifier */ && !p.symbol.isReferenced; })
  129312. : index === parameters.length - 1;
  129313. }
  129314. case 164 /* SetAccessor */:
  129315. // Setter must have a parameter
  129316. return false;
  129317. default:
  129318. return ts.Debug.failBadSyntaxKind(parent);
  129319. }
  129320. }
  129321. function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) {
  129322. ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) {
  129323. var index = deletedParameter.parent.parameters.indexOf(deletedParameter);
  129324. if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments.
  129325. changes.delete(sourceFile, call.arguments[index]);
  129326. }
  129327. });
  129328. }
  129329. })(codefix = ts.codefix || (ts.codefix = {}));
  129330. })(ts || (ts = {}));
  129331. /* @internal */
  129332. var ts;
  129333. (function (ts) {
  129334. var codefix;
  129335. (function (codefix) {
  129336. var fixId = "fixUnreachableCode";
  129337. var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
  129338. codefix.registerCodeFix({
  129339. errorCodes: errorCodes,
  129340. getCodeActions: function (context) {
  129341. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length, context.errorCode); });
  129342. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
  129343. },
  129344. fixIds: [fixId],
  129345. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length, diag.code); }); },
  129346. });
  129347. function doChange(changes, sourceFile, start, length, errorCode) {
  129348. var token = ts.getTokenAtPosition(sourceFile, start);
  129349. var statement = ts.findAncestor(token, ts.isStatement);
  129350. if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) {
  129351. var logData = JSON.stringify({
  129352. statementKind: ts.Debug.formatSyntaxKind(statement.kind),
  129353. tokenKind: ts.Debug.formatSyntaxKind(token.kind),
  129354. errorCode: errorCode,
  129355. start: start,
  129356. length: length
  129357. });
  129358. ts.Debug.fail("Token and statement should start at the same point. " + logData);
  129359. }
  129360. var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent;
  129361. if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) {
  129362. switch (container.kind) {
  129363. case 227 /* IfStatement */:
  129364. if (container.elseStatement) {
  129365. if (ts.isBlock(statement.parent)) {
  129366. break;
  129367. }
  129368. else {
  129369. changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
  129370. }
  129371. return;
  129372. }
  129373. // falls through
  129374. case 229 /* WhileStatement */:
  129375. case 230 /* ForStatement */:
  129376. changes.delete(sourceFile, container);
  129377. return;
  129378. }
  129379. }
  129380. if (ts.isBlock(statement.parent)) {
  129381. var end_3 = start + length;
  129382. var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_3; }), "Some statement should be last");
  129383. changes.deleteNodeRange(sourceFile, statement, lastStatement);
  129384. }
  129385. else {
  129386. changes.delete(sourceFile, statement);
  129387. }
  129388. }
  129389. function lastWhere(a, pred) {
  129390. var last;
  129391. for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
  129392. var value = a_1[_i];
  129393. if (!pred(value))
  129394. break;
  129395. last = value;
  129396. }
  129397. return last;
  129398. }
  129399. })(codefix = ts.codefix || (ts.codefix = {}));
  129400. })(ts || (ts = {}));
  129401. /* @internal */
  129402. var ts;
  129403. (function (ts) {
  129404. var codefix;
  129405. (function (codefix) {
  129406. var fixId = "fixUnusedLabel";
  129407. var errorCodes = [ts.Diagnostics.Unused_label.code];
  129408. codefix.registerCodeFix({
  129409. errorCodes: errorCodes,
  129410. getCodeActions: function (context) {
  129411. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
  129412. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
  129413. },
  129414. fixIds: [fixId],
  129415. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
  129416. });
  129417. function doChange(changes, sourceFile, start) {
  129418. var token = ts.getTokenAtPosition(sourceFile, start);
  129419. var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
  129420. var pos = token.getStart(sourceFile);
  129421. var statementPos = labeledStatement.statement.getStart(sourceFile);
  129422. // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
  129423. var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
  129424. : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 58 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
  129425. changes.deleteRange(sourceFile, { pos: pos, end: end });
  129426. }
  129427. })(codefix = ts.codefix || (ts.codefix = {}));
  129428. })(ts || (ts = {}));
  129429. /* @internal */
  129430. var ts;
  129431. (function (ts) {
  129432. var codefix;
  129433. (function (codefix) {
  129434. var fixIdPlain = "fixJSDocTypes_plain";
  129435. var fixIdNullable = "fixJSDocTypes_nullable";
  129436. var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code];
  129437. codefix.registerCodeFix({
  129438. errorCodes: errorCodes,
  129439. getCodeActions: function (context) {
  129440. var sourceFile = context.sourceFile;
  129441. var checker = context.program.getTypeChecker();
  129442. var info = getInfo(sourceFile, context.span.start, checker);
  129443. if (!info)
  129444. return undefined;
  129445. var typeNode = info.typeNode, type = info.type;
  129446. var original = typeNode.getText(sourceFile);
  129447. var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
  129448. if (typeNode.kind === 297 /* JSDocNullableType */) {
  129449. // for nullable types, suggest the flow-compatible `T | null | undefined`
  129450. // in addition to the jsdoc/closure-compatible `T | null`
  129451. actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
  129452. }
  129453. return actions;
  129454. function fix(type, fixId, fixAllDescription) {
  129455. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); });
  129456. return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription);
  129457. }
  129458. },
  129459. fixIds: [fixIdPlain, fixIdNullable],
  129460. getAllCodeActions: function (context) {
  129461. var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile;
  129462. var checker = program.getTypeChecker();
  129463. return codefix.codeFixAll(context, errorCodes, function (changes, err) {
  129464. var info = getInfo(err.file, err.start, checker);
  129465. if (!info)
  129466. return;
  129467. var typeNode = info.typeNode, type = info.type;
  129468. var fixedType = typeNode.kind === 297 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
  129469. doChange(changes, sourceFile, typeNode, fixedType, checker);
  129470. });
  129471. }
  129472. });
  129473. function doChange(changes, sourceFile, oldTypeNode, newType, checker) {
  129474. changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217
  129475. }
  129476. function getInfo(sourceFile, pos, checker) {
  129477. var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer);
  129478. var typeNode = decl && decl.type;
  129479. return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) };
  129480. }
  129481. function isTypeContainer(node) {
  129482. // NOTE: Some locations are not handled yet:
  129483. // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments
  129484. switch (node.kind) {
  129485. case 217 /* AsExpression */:
  129486. case 165 /* CallSignature */:
  129487. case 166 /* ConstructSignature */:
  129488. case 244 /* FunctionDeclaration */:
  129489. case 163 /* GetAccessor */:
  129490. case 167 /* IndexSignature */:
  129491. case 186 /* MappedType */:
  129492. case 161 /* MethodDeclaration */:
  129493. case 160 /* MethodSignature */:
  129494. case 156 /* Parameter */:
  129495. case 159 /* PropertyDeclaration */:
  129496. case 158 /* PropertySignature */:
  129497. case 164 /* SetAccessor */:
  129498. case 247 /* TypeAliasDeclaration */:
  129499. case 199 /* TypeAssertionExpression */:
  129500. case 242 /* VariableDeclaration */:
  129501. return true;
  129502. default:
  129503. return false;
  129504. }
  129505. }
  129506. })(codefix = ts.codefix || (ts.codefix = {}));
  129507. })(ts || (ts = {}));
  129508. /* @internal */
  129509. var ts;
  129510. (function (ts) {
  129511. var codefix;
  129512. (function (codefix) {
  129513. var fixId = "fixAwaitInSyncFunction";
  129514. var errorCodes = [
  129515. ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
  129516. ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code,
  129517. ];
  129518. codefix.registerCodeFix({
  129519. errorCodes: errorCodes,
  129520. getCodeActions: function (context) {
  129521. var sourceFile = context.sourceFile, span = context.span;
  129522. var nodes = getNodes(sourceFile, span.start);
  129523. if (!nodes)
  129524. return undefined;
  129525. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); });
  129526. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)];
  129527. },
  129528. fixIds: [fixId],
  129529. getAllCodeActions: function (context) {
  129530. var seen = ts.createMap();
  129531. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  129532. var nodes = getNodes(diag.file, diag.start);
  129533. if (!nodes || !ts.addToSeen(seen, ts.getNodeId(nodes.insertBefore)))
  129534. return;
  129535. doChange(changes, context.sourceFile, nodes);
  129536. });
  129537. },
  129538. });
  129539. function getReturnType(expr) {
  129540. if (expr.type) {
  129541. return expr.type;
  129542. }
  129543. if (ts.isVariableDeclaration(expr.parent) &&
  129544. expr.parent.type &&
  129545. ts.isFunctionTypeNode(expr.parent.type)) {
  129546. return expr.parent.type.type;
  129547. }
  129548. }
  129549. function getNodes(sourceFile, start) {
  129550. var token = ts.getTokenAtPosition(sourceFile, start);
  129551. var containingFunction = ts.getContainingFunction(token);
  129552. if (!containingFunction) {
  129553. return;
  129554. }
  129555. var insertBefore;
  129556. switch (containingFunction.kind) {
  129557. case 161 /* MethodDeclaration */:
  129558. insertBefore = containingFunction.name;
  129559. break;
  129560. case 244 /* FunctionDeclaration */:
  129561. case 201 /* FunctionExpression */:
  129562. insertBefore = ts.findChildOfKind(containingFunction, 94 /* FunctionKeyword */, sourceFile);
  129563. break;
  129564. case 202 /* ArrowFunction */:
  129565. insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters);
  129566. break;
  129567. default:
  129568. return;
  129569. }
  129570. return insertBefore && {
  129571. insertBefore: insertBefore,
  129572. returnType: getReturnType(containingFunction)
  129573. };
  129574. }
  129575. function doChange(changes, sourceFile, _a) {
  129576. var insertBefore = _a.insertBefore, returnType = _a.returnType;
  129577. if (returnType) {
  129578. var entityName = ts.getEntityNameFromTypeNode(returnType);
  129579. if (!entityName || entityName.kind !== 75 /* Identifier */ || entityName.text !== "Promise") {
  129580. changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType])));
  129581. }
  129582. }
  129583. changes.insertModifierBefore(sourceFile, 126 /* AsyncKeyword */, insertBefore);
  129584. }
  129585. })(codefix = ts.codefix || (ts.codefix = {}));
  129586. })(ts || (ts = {}));
  129587. /* @internal */
  129588. var ts;
  129589. (function (ts) {
  129590. var codefix;
  129591. (function (codefix) {
  129592. var fixName = "disableJsDiagnostics";
  129593. var fixId = "disableJsDiagnostics";
  129594. var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) {
  129595. var diag = ts.Diagnostics[key];
  129596. return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined;
  129597. });
  129598. codefix.registerCodeFix({
  129599. errorCodes: errorCodes,
  129600. getCodeActions: function (context) {
  129601. var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext;
  129602. if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
  129603. return undefined;
  129604. }
  129605. var fixes = [
  129606. // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
  129607. codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [
  129608. ts.createTextChange(sourceFile.checkJsDirective
  129609. ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end)
  129610. : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)),
  129611. ])], ts.Diagnostics.Disable_checking_for_this_file),
  129612. ];
  129613. if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) {
  129614. fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages));
  129615. }
  129616. return fixes;
  129617. },
  129618. fixIds: [fixId],
  129619. getAllCodeActions: function (context) {
  129620. var seenLines = ts.createMap();
  129621. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  129622. if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) {
  129623. makeChange(changes, diag.file, diag.start, seenLines);
  129624. }
  129625. });
  129626. },
  129627. });
  129628. function makeChange(changes, sourceFile, position, seenLines) {
  129629. var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line;
  129630. // Only need to add `// @ts-ignore` for a line once.
  129631. if (!seenLines || ts.addToSeen(seenLines, lineNumber)) {
  129632. changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
  129633. }
  129634. }
  129635. })(codefix = ts.codefix || (ts.codefix = {}));
  129636. })(ts || (ts = {}));
  129637. /* @internal */
  129638. var ts;
  129639. (function (ts) {
  129640. var codefix;
  129641. (function (codefix) {
  129642. /**
  129643. * Finds members of the resolved type that are missing in the class pointed to by class decl
  129644. * and generates source code for the missing members.
  129645. * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
  129646. * @returns Empty string iff there are no member insertions.
  129647. */
  129648. function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, out) {
  129649. var classMembers = classDeclaration.symbol.members;
  129650. for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) {
  129651. var symbol = possiblyMissingSymbols_1[_i];
  129652. if (!classMembers.has(symbol.escapedName)) {
  129653. addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out);
  129654. }
  129655. }
  129656. }
  129657. codefix.createMissingMemberNodes = createMissingMemberNodes;
  129658. function getModuleSpecifierResolverHost(context) {
  129659. return {
  129660. directoryExists: context.host.directoryExists ? function (d) { return context.host.directoryExists(d); } : undefined,
  129661. fileExists: context.host.fileExists ? function (f) { return context.host.fileExists(f); } : undefined,
  129662. getCurrentDirectory: context.host.getCurrentDirectory ? function () { return context.host.getCurrentDirectory(); } : undefined,
  129663. readFile: context.host.readFile ? function (f) { return context.host.readFile(f); } : undefined,
  129664. useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? function () { return context.host.useCaseSensitiveFileNames(); } : undefined,
  129665. getSourceFiles: function () { return context.program.getSourceFiles(); },
  129666. getCommonSourceDirectory: function () { return context.program.getCommonSourceDirectory(); },
  129667. };
  129668. }
  129669. function getNoopSymbolTrackerWithResolver(context) {
  129670. return {
  129671. trackSymbol: ts.noop,
  129672. moduleResolverHost: getModuleSpecifierResolverHost(context),
  129673. };
  129674. }
  129675. codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver;
  129676. /**
  129677. * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
  129678. */
  129679. function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, out) {
  129680. var declarations = symbol.getDeclarations();
  129681. if (!(declarations && declarations.length)) {
  129682. return undefined;
  129683. }
  129684. var checker = context.program.getTypeChecker();
  129685. var declaration = declarations[0];
  129686. var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false);
  129687. var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration));
  129688. var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined;
  129689. var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
  129690. var optional = !!(symbol.flags & 16777216 /* Optional */);
  129691. var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */);
  129692. switch (declaration.kind) {
  129693. case 158 /* PropertySignature */:
  129694. case 159 /* PropertyDeclaration */:
  129695. var flags = preferences.quotePreference === "single" ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined;
  129696. var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context));
  129697. out(ts.createProperty(
  129698. /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeNode,
  129699. /*initializer*/ undefined));
  129700. break;
  129701. case 163 /* GetAccessor */:
  129702. case 164 /* SetAccessor */: {
  129703. var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration);
  129704. var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context));
  129705. var orderedAccessors = allAccessors.secondAccessor
  129706. ? [allAccessors.firstAccessor, allAccessors.secondAccessor]
  129707. : [allAccessors.firstAccessor];
  129708. for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) {
  129709. var accessor = orderedAccessors_1[_i];
  129710. if (ts.isGetAccessorDeclaration(accessor)) {
  129711. out(ts.createGetAccessor(
  129712. /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(preferences)));
  129713. }
  129714. else {
  129715. ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter");
  129716. var parameter = ts.getSetAccessorValueParameter(accessor);
  129717. var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined;
  129718. out(ts.createSetAccessor(
  129719. /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(preferences)));
  129720. }
  129721. }
  129722. break;
  129723. }
  129724. case 160 /* MethodSignature */:
  129725. case 161 /* MethodDeclaration */:
  129726. // The signature for the implementation appears as an entry in `signatures` iff
  129727. // there is only one signature.
  129728. // If there are overloads and an implementation signature, it appears as an
  129729. // extra declaration that isn't a signature for `type`.
  129730. // If there is more than one overload but no implementation signature
  129731. // (eg: an abstract method or interface declaration), there is a 1-1
  129732. // correspondence of declarations and signatures.
  129733. var signatures = checker.getSignaturesOfType(type, 0 /* Call */);
  129734. if (!ts.some(signatures)) {
  129735. break;
  129736. }
  129737. if (declarations.length === 1) {
  129738. ts.Debug.assert(signatures.length === 1, "One declaration implies one signature");
  129739. var signature = signatures[0];
  129740. outputMethod(signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(preferences));
  129741. break;
  129742. }
  129743. for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) {
  129744. var signature = signatures_1[_a];
  129745. // Need to ensure nodes are fresh each time so they can have different positions.
  129746. outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
  129747. }
  129748. if (!ambient) {
  129749. if (declarations.length > signatures.length) {
  129750. var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
  129751. outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
  129752. }
  129753. else {
  129754. ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count");
  129755. out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences));
  129756. }
  129757. }
  129758. break;
  129759. }
  129760. function outputMethod(signature, modifiers, name, body) {
  129761. var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body);
  129762. if (method)
  129763. out(method);
  129764. }
  129765. }
  129766. function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body) {
  129767. var program = context.program;
  129768. var signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, 161 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context));
  129769. if (!signatureDeclaration) {
  129770. return undefined;
  129771. }
  129772. signatureDeclaration.decorators = undefined;
  129773. signatureDeclaration.modifiers = modifiers;
  129774. signatureDeclaration.name = name;
  129775. signatureDeclaration.questionToken = optional ? ts.createToken(57 /* QuestionToken */) : undefined;
  129776. signatureDeclaration.body = body;
  129777. return signatureDeclaration;
  129778. }
  129779. function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) {
  129780. var body = !ts.isInterfaceDeclaration(contextNode);
  129781. var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
  129782. var checker = context.program.getTypeChecker();
  129783. var tracker = getNoopSymbolTrackerWithResolver(context);
  129784. var types = ts.map(args, function (arg) {
  129785. // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
  129786. return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker);
  129787. });
  129788. var names = ts.map(args, function (arg) {
  129789. return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined;
  129790. });
  129791. var contextualType = checker.getContextualType(call);
  129792. var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
  129793. return ts.createMethod(
  129794. /*decorators*/ undefined,
  129795. /*modifiers*/ makeStatic ? [ts.createToken(120 /* StaticKeyword */)] : undefined,
  129796. /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(41 /* AsteriskToken */) : undefined, methodName,
  129797. /*questionToken*/ undefined,
  129798. /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) {
  129799. return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
  129800. }),
  129801. /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs),
  129802. /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined);
  129803. }
  129804. codefix.createMethodFromCallExpression = createMethodFromCallExpression;
  129805. function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
  129806. var parameters = [];
  129807. for (var i = 0; i < argCount; i++) {
  129808. var newParameter = ts.createParameter(
  129809. /*decorators*/ undefined,
  129810. /*modifiers*/ undefined,
  129811. /*dotDotDotToken*/ undefined,
  129812. /*name*/ names && names[i] || "arg" + i,
  129813. /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(57 /* QuestionToken */) : undefined,
  129814. /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(125 /* AnyKeyword */),
  129815. /*initializer*/ undefined);
  129816. parameters.push(newParameter);
  129817. }
  129818. return parameters;
  129819. }
  129820. function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) {
  129821. /** This is *a* signature with the maximal number of arguments,
  129822. * such that if there is a "maximal" signature without rest arguments,
  129823. * this is one of them.
  129824. */
  129825. var maxArgsSignature = signatures[0];
  129826. var minArgumentCount = signatures[0].minArgumentCount;
  129827. var someSigHasRestParameter = false;
  129828. for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
  129829. var sig = signatures_2[_i];
  129830. minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
  129831. if (ts.signatureHasRestParameter(sig)) {
  129832. someSigHasRestParameter = true;
  129833. }
  129834. if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) {
  129835. maxArgsSignature = sig;
  129836. }
  129837. }
  129838. var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0);
  129839. var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; });
  129840. var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false);
  129841. if (someSigHasRestParameter) {
  129842. var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(125 /* AnyKeyword */));
  129843. var restParameter = ts.createParameter(
  129844. /*decorators*/ undefined,
  129845. /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest",
  129846. /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(57 /* QuestionToken */) : undefined, anyArrayType,
  129847. /*initializer*/ undefined);
  129848. parameters.push(restParameter);
  129849. }
  129850. return createStubbedMethod(modifiers, name, optional,
  129851. /*typeParameters*/ undefined, parameters,
  129852. /*returnType*/ undefined, preferences);
  129853. }
  129854. function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) {
  129855. return ts.createMethod(
  129856. /*decorators*/ undefined, modifiers,
  129857. /*asteriskToken*/ undefined, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences));
  129858. }
  129859. function createStubbedMethodBody(preferences) {
  129860. return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"),
  129861. /*typeArguments*/ undefined,
  129862. // TODO Handle auto quote preference.
  129863. [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))],
  129864. /*multiline*/ true);
  129865. }
  129866. function createVisibilityModifier(flags) {
  129867. if (flags & 4 /* Public */) {
  129868. return ts.createToken(119 /* PublicKeyword */);
  129869. }
  129870. else if (flags & 16 /* Protected */) {
  129871. return ts.createToken(118 /* ProtectedKeyword */);
  129872. }
  129873. return undefined;
  129874. }
  129875. function setJsonCompilerOptionValues(changeTracker, configFile, options) {
  129876. var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
  129877. if (!tsconfigObjectLiteral)
  129878. return undefined;
  129879. var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
  129880. if (compilerOptionsProperty === undefined) {
  129881. changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) {
  129882. var optionName = _a[0], optionValue = _a[1];
  129883. return createJsonPropertyAssignment(optionName, optionValue);
  129884. }), /*multiLine*/ true)));
  129885. return;
  129886. }
  129887. var compilerOptions = compilerOptionsProperty.initializer;
  129888. if (!ts.isObjectLiteralExpression(compilerOptions)) {
  129889. return;
  129890. }
  129891. for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
  129892. var _a = options_1[_i], optionName = _a[0], optionValue = _a[1];
  129893. var optionProperty = findJsonProperty(compilerOptions, optionName);
  129894. if (optionProperty === undefined) {
  129895. changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue));
  129896. }
  129897. else {
  129898. changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue);
  129899. }
  129900. }
  129901. }
  129902. codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues;
  129903. function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) {
  129904. setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]);
  129905. }
  129906. codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue;
  129907. function createJsonPropertyAssignment(name, initializer) {
  129908. return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer);
  129909. }
  129910. codefix.createJsonPropertyAssignment = createJsonPropertyAssignment;
  129911. function findJsonProperty(obj, name) {
  129912. return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; });
  129913. }
  129914. codefix.findJsonProperty = findJsonProperty;
  129915. })(codefix = ts.codefix || (ts.codefix = {}));
  129916. })(ts || (ts = {}));
  129917. /* @internal */
  129918. var ts;
  129919. (function (ts) {
  129920. var codefix;
  129921. (function (codefix) {
  129922. var fixName = "invalidImportSyntax";
  129923. function getCodeFixesForImportDeclaration(context, node) {
  129924. var sourceFile = ts.getSourceFileOfNode(node);
  129925. var namespace = ts.getNamespaceDeclarationNode(node);
  129926. var opts = context.program.getCompilerOptions();
  129927. var variations = [];
  129928. // import Bluebird from "bluebird";
  129929. variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences))));
  129930. if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
  129931. // import Bluebird = require("bluebird");
  129932. variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
  129933. /*decorators*/ undefined,
  129934. /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier))));
  129935. }
  129936. return variations;
  129937. }
  129938. function createAction(context, sourceFile, node, replacement) {
  129939. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); });
  129940. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]);
  129941. }
  129942. codefix.registerCodeFix({
  129943. errorCodes: [
  129944. ts.Diagnostics.This_expression_is_not_callable.code,
  129945. ts.Diagnostics.This_expression_is_not_constructable.code,
  129946. ],
  129947. getCodeActions: getActionsForUsageOfInvalidImport
  129948. });
  129949. function getActionsForUsageOfInvalidImport(context) {
  129950. var sourceFile = context.sourceFile;
  129951. var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 196 /* CallExpression */ : 197 /* NewExpression */;
  129952. var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; });
  129953. if (!node) {
  129954. return [];
  129955. }
  129956. var expr = node.expression;
  129957. return getImportCodeFixesForExpression(context, expr);
  129958. }
  129959. codefix.registerCodeFix({
  129960. errorCodes: [
  129961. // The following error codes cover pretty much all assignability errors that could involve an expression
  129962. ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  129963. ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code,
  129964. ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  129965. ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
  129966. ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code,
  129967. ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code,
  129968. ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code,
  129969. ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code,
  129970. ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code,
  129971. ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
  129972. ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code,
  129973. ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code,
  129974. ],
  129975. getCodeActions: getActionsForInvalidImportLocation
  129976. });
  129977. function getActionsForInvalidImportLocation(context) {
  129978. var sourceFile = context.sourceFile;
  129979. var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
  129980. if (!node) {
  129981. return [];
  129982. }
  129983. return getImportCodeFixesForExpression(context, node);
  129984. }
  129985. function getImportCodeFixesForExpression(context, expr) {
  129986. var type = context.program.getTypeChecker().getTypeAtLocation(expr);
  129987. if (!(type.symbol && type.symbol.originatingImport)) {
  129988. return [];
  129989. }
  129990. var fixes = [];
  129991. var relatedImport = type.symbol.originatingImport; // TODO: GH#18217
  129992. if (!ts.isImportCall(relatedImport)) {
  129993. ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
  129994. }
  129995. if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
  129996. var sourceFile_1 = context.sourceFile;
  129997. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
  129998. fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
  129999. }
  130000. return fixes;
  130001. }
  130002. })(codefix = ts.codefix || (ts.codefix = {}));
  130003. })(ts || (ts = {}));
  130004. /* @internal */
  130005. var ts;
  130006. (function (ts) {
  130007. var codefix;
  130008. (function (codefix) {
  130009. var fixName = "strictClassInitialization";
  130010. var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
  130011. var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
  130012. var fixIdAddInitializer = "addMissingPropertyInitializer";
  130013. var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
  130014. codefix.registerCodeFix({
  130015. errorCodes: errorCodes,
  130016. getCodeActions: function (context) {
  130017. var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
  130018. if (!propertyDeclaration)
  130019. return;
  130020. var result = [
  130021. getActionForAddMissingUndefinedType(context, propertyDeclaration),
  130022. getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration)
  130023. ];
  130024. ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration));
  130025. return result;
  130026. },
  130027. fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
  130028. getAllCodeActions: function (context) {
  130029. return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  130030. var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
  130031. if (!propertyDeclaration)
  130032. return;
  130033. switch (context.fixId) {
  130034. case fixIdAddDefiniteAssignmentAssertions:
  130035. addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration);
  130036. break;
  130037. case fixIdAddUndefinedType:
  130038. addUndefinedType(changes, diag.file, propertyDeclaration);
  130039. break;
  130040. case fixIdAddInitializer:
  130041. var checker = context.program.getTypeChecker();
  130042. var initializer = getInitializer(checker, propertyDeclaration);
  130043. if (!initializer)
  130044. return;
  130045. addInitializer(changes, diag.file, propertyDeclaration, initializer);
  130046. break;
  130047. default:
  130048. ts.Debug.fail(JSON.stringify(context.fixId));
  130049. }
  130050. });
  130051. },
  130052. });
  130053. function getPropertyDeclaration(sourceFile, pos) {
  130054. var token = ts.getTokenAtPosition(sourceFile, pos);
  130055. return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
  130056. }
  130057. function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) {
  130058. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); });
  130059. return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties);
  130060. }
  130061. function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
  130062. var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(53 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
  130063. changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
  130064. }
  130065. function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
  130066. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
  130067. return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties);
  130068. }
  130069. function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
  130070. var undefinedTypeNode = ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
  130071. var type = propertyDeclaration.type; // TODO: GH#18217
  130072. var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode];
  130073. changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types));
  130074. }
  130075. function getActionForAddMissingInitializer(context, propertyDeclaration) {
  130076. var checker = context.program.getTypeChecker();
  130077. var initializer = getInitializer(checker, propertyDeclaration);
  130078. if (!initializer)
  130079. return undefined;
  130080. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); });
  130081. return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties);
  130082. }
  130083. function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) {
  130084. var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
  130085. changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
  130086. }
  130087. function getInitializer(checker, propertyDeclaration) {
  130088. return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217
  130089. }
  130090. function getDefaultValueFromType(checker, type) {
  130091. if (type.flags & 512 /* BooleanLiteral */) {
  130092. return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue();
  130093. }
  130094. else if (type.isLiteral()) {
  130095. return ts.createLiteral(type.value);
  130096. }
  130097. else if (type.isUnion()) {
  130098. return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
  130099. }
  130100. else if (type.isClass()) {
  130101. var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
  130102. if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
  130103. return undefined;
  130104. var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration);
  130105. if (constructorDeclaration && constructorDeclaration.parameters.length)
  130106. return undefined;
  130107. return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
  130108. }
  130109. else if (checker.isArrayLikeType(type)) {
  130110. return ts.createArrayLiteral();
  130111. }
  130112. return undefined;
  130113. }
  130114. })(codefix = ts.codefix || (ts.codefix = {}));
  130115. })(ts || (ts = {}));
  130116. /* @internal */
  130117. var ts;
  130118. (function (ts) {
  130119. var codefix;
  130120. (function (codefix) {
  130121. var fixId = "requireInTs";
  130122. var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code];
  130123. codefix.registerCodeFix({
  130124. errorCodes: errorCodes,
  130125. getCodeActions: function (context) {
  130126. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); });
  130127. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)];
  130128. },
  130129. fixIds: [fixId],
  130130. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); },
  130131. });
  130132. function doChange(changes, sourceFile, pos, program) {
  130133. var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required;
  130134. changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())
  130135. ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required)
  130136. : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required)));
  130137. }
  130138. function getInfo(sourceFile, pos) {
  130139. var parent = ts.getTokenAtPosition(sourceFile, pos).parent;
  130140. if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true))
  130141. throw ts.Debug.failBadSyntaxKind(parent);
  130142. var decl = ts.cast(parent.parent, ts.isVariableDeclaration);
  130143. return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] };
  130144. }
  130145. })(codefix = ts.codefix || (ts.codefix = {}));
  130146. })(ts || (ts = {}));
  130147. /* @internal */
  130148. var ts;
  130149. (function (ts) {
  130150. var codefix;
  130151. (function (codefix) {
  130152. var fixId = "useDefaultImport";
  130153. var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
  130154. codefix.registerCodeFix({
  130155. errorCodes: errorCodes,
  130156. getCodeActions: function (context) {
  130157. var sourceFile = context.sourceFile, start = context.span.start;
  130158. var info = getInfo(sourceFile, start);
  130159. if (!info)
  130160. return undefined;
  130161. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); });
  130162. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)];
  130163. },
  130164. fixIds: [fixId],
  130165. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  130166. var info = getInfo(diag.file, diag.start);
  130167. if (info)
  130168. doChange(changes, diag.file, info, context.preferences);
  130169. }); },
  130170. });
  130171. function getInfo(sourceFile, pos) {
  130172. var name = ts.getTokenAtPosition(sourceFile, pos);
  130173. if (!ts.isIdentifier(name))
  130174. return undefined; // bad input
  130175. var parent = name.parent;
  130176. if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
  130177. return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
  130178. }
  130179. else if (ts.isNamespaceImport(parent)) {
  130180. var importNode = parent.parent.parent;
  130181. return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
  130182. }
  130183. }
  130184. function doChange(changes, sourceFile, info, preferences) {
  130185. changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences)));
  130186. }
  130187. })(codefix = ts.codefix || (ts.codefix = {}));
  130188. })(ts || (ts = {}));
  130189. /* @internal */
  130190. var ts;
  130191. (function (ts) {
  130192. var codefix;
  130193. (function (codefix) {
  130194. var fixId = "useBigintLiteral";
  130195. var errorCodes = [
  130196. ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code,
  130197. ];
  130198. codefix.registerCodeFix({
  130199. errorCodes: errorCodes,
  130200. getCodeActions: function (context) {
  130201. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); });
  130202. if (changes.length > 0) {
  130203. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_a_bigint_numeric_literal, fixId, ts.Diagnostics.Convert_all_to_bigint_numeric_literals)];
  130204. }
  130205. },
  130206. fixIds: [fixId],
  130207. getAllCodeActions: function (context) {
  130208. return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag); });
  130209. },
  130210. });
  130211. function makeChange(changeTracker, sourceFile, span) {
  130212. var numericLiteral = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), ts.isNumericLiteral);
  130213. if (!numericLiteral) {
  130214. return;
  130215. }
  130216. // We use .getText to overcome parser inaccuracies: https://github.com/microsoft/TypeScript/issues/33298
  130217. var newText = numericLiteral.getText(sourceFile) + "n";
  130218. changeTracker.replaceNode(sourceFile, numericLiteral, ts.createBigIntLiteral(newText));
  130219. }
  130220. })(codefix = ts.codefix || (ts.codefix = {}));
  130221. })(ts || (ts = {}));
  130222. /* @internal */
  130223. var ts;
  130224. (function (ts) {
  130225. var codefix;
  130226. (function (codefix) {
  130227. var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
  130228. var fixId = fixIdAddMissingTypeof;
  130229. var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code];
  130230. codefix.registerCodeFix({
  130231. errorCodes: errorCodes,
  130232. getCodeActions: function (context) {
  130233. var sourceFile = context.sourceFile, span = context.span;
  130234. var importType = getImportTypeNode(sourceFile, span.start);
  130235. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
  130236. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
  130237. },
  130238. fixIds: [fixId],
  130239. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  130240. return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
  130241. }); },
  130242. });
  130243. function getImportTypeNode(sourceFile, pos) {
  130244. var token = ts.getTokenAtPosition(sourceFile, pos);
  130245. ts.Debug.assert(token.kind === 96 /* ImportKeyword */, "This token should be an ImportKeyword");
  130246. ts.Debug.assert(token.parent.kind === 188 /* ImportType */, "Token parent should be an ImportType");
  130247. return token.parent;
  130248. }
  130249. function doChange(changes, sourceFile, importType) {
  130250. var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
  130251. changes.replaceNode(sourceFile, importType, newTypeNode);
  130252. }
  130253. })(codefix = ts.codefix || (ts.codefix = {}));
  130254. })(ts || (ts = {}));
  130255. /* @internal */
  130256. var ts;
  130257. (function (ts) {
  130258. var codefix;
  130259. (function (codefix) {
  130260. var fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
  130261. var fixId = fixIdAddMissingTypeof;
  130262. var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
  130263. codefix.registerCodeFix({
  130264. errorCodes: errorCodes,
  130265. getCodeActions: function (context) {
  130266. var sourceFile = context.sourceFile, span = context.span;
  130267. var info = getInfo(sourceFile, span.start);
  130268. if (!info)
  130269. return undefined;
  130270. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
  130271. var name = ts.idText(info.container.name);
  130272. return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])];
  130273. },
  130274. fixIds: [fixId],
  130275. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
  130276. var info = getInfo(diag.file, diag.start);
  130277. if (info)
  130278. doChange(changes, diag.file, info);
  130279. }); }
  130280. });
  130281. function getInfo(sourceFile, pos) {
  130282. var token = ts.getTokenAtPosition(sourceFile, pos);
  130283. var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration);
  130284. if (ts.isClassDeclaration(indexSignature.parent))
  130285. return undefined;
  130286. var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration);
  130287. return { indexSignature: indexSignature, container: container };
  130288. }
  130289. function createTypeAliasFromInterface(declaration, type) {
  130290. return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
  130291. }
  130292. function doChange(changes, sourceFile, _a) {
  130293. var indexSignature = _a.indexSignature, container = _a.container;
  130294. var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members;
  130295. var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); });
  130296. var parameter = ts.first(indexSignature.parameters);
  130297. var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type);
  130298. var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(138 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type);
  130299. var intersectionType = ts.createIntersectionTypeNode(__spreadArrays(ts.getAllSuperTypeNodes(container), [
  130300. mappedIntersectionType
  130301. ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray)));
  130302. changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
  130303. }
  130304. })(codefix = ts.codefix || (ts.codefix = {}));
  130305. })(ts || (ts = {}));
  130306. /* @internal */
  130307. var ts;
  130308. (function (ts) {
  130309. var codefix;
  130310. (function (codefix) {
  130311. var fixId = "removeUnnecessaryAwait";
  130312. var errorCodes = [
  130313. ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code,
  130314. ];
  130315. codefix.registerCodeFix({
  130316. errorCodes: errorCodes,
  130317. getCodeActions: function (context) {
  130318. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); });
  130319. if (changes.length > 0) {
  130320. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unnecessary_await, fixId, ts.Diagnostics.Remove_all_unnecessary_uses_of_await)];
  130321. }
  130322. },
  130323. fixIds: [fixId],
  130324. getAllCodeActions: function (context) {
  130325. return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag); });
  130326. },
  130327. });
  130328. function makeChange(changeTracker, sourceFile, span) {
  130329. var awaitKeyword = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), function (node) { return node.kind === 127 /* AwaitKeyword */; });
  130330. var awaitExpression = awaitKeyword && ts.tryCast(awaitKeyword.parent, ts.isAwaitExpression);
  130331. if (!awaitExpression) {
  130332. return;
  130333. }
  130334. var expressionToReplace = awaitExpression;
  130335. var hasSurroundingParens = ts.isParenthesizedExpression(awaitExpression.parent);
  130336. if (hasSurroundingParens) {
  130337. var leftMostExpression = ts.getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ false);
  130338. if (ts.isIdentifier(leftMostExpression)) {
  130339. var precedingToken = ts.findPrecedingToken(awaitExpression.parent.pos, sourceFile);
  130340. if (precedingToken && precedingToken.kind !== 99 /* NewKeyword */) {
  130341. expressionToReplace = awaitExpression.parent;
  130342. }
  130343. }
  130344. }
  130345. changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression);
  130346. }
  130347. })(codefix = ts.codefix || (ts.codefix = {}));
  130348. })(ts || (ts = {}));
  130349. /* @internal */
  130350. var ts;
  130351. (function (ts) {
  130352. var codefix;
  130353. (function (codefix) {
  130354. var errorCodes = [ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code];
  130355. var fixId = "splitTypeOnlyImport";
  130356. codefix.registerCodeFix({
  130357. errorCodes: errorCodes,
  130358. fixIds: [fixId],
  130359. getCodeActions: function (context) {
  130360. var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
  130361. return splitTypeOnlyImport(t, getImportDeclaration(context.sourceFile, context.span), context);
  130362. });
  130363. if (changes.length) {
  130364. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Split_into_two_separate_import_declarations, fixId, ts.Diagnostics.Split_all_invalid_type_only_imports)];
  130365. }
  130366. },
  130367. getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, error) {
  130368. splitTypeOnlyImport(changes, getImportDeclaration(context.sourceFile, error), context);
  130369. }); },
  130370. });
  130371. function getImportDeclaration(sourceFile, span) {
  130372. return ts.findAncestor(ts.getTokenAtPosition(sourceFile, span.start), ts.isImportDeclaration);
  130373. }
  130374. function splitTypeOnlyImport(changes, importDeclaration, context) {
  130375. if (!importDeclaration) {
  130376. return;
  130377. }
  130378. var importClause = ts.Debug.assertDefined(importDeclaration.importClause);
  130379. changes.replaceNode(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, importClause.name, /*namedBindings*/ undefined, importClause.isTypeOnly), importDeclaration.moduleSpecifier));
  130380. changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.createImportDeclaration(
  130381. /*decorators*/ undefined,
  130382. /*modifiers*/ undefined, ts.updateImportClause(importClause, /*name*/ undefined, importClause.namedBindings, importClause.isTypeOnly), importDeclaration.moduleSpecifier));
  130383. }
  130384. })(codefix = ts.codefix || (ts.codefix = {}));
  130385. })(ts || (ts = {}));
  130386. /* @internal */
  130387. var ts;
  130388. (function (ts) {
  130389. var codefix;
  130390. (function (codefix) {
  130391. var fixId = "fixConvertConstToLet";
  130392. var errorCodes = [ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];
  130393. codefix.registerCodeFix({
  130394. errorCodes: errorCodes,
  130395. getCodeActions: function (context) {
  130396. var sourceFile = context.sourceFile, span = context.span, program = context.program;
  130397. var variableStatement = getVariableStatement(sourceFile, span.start, program);
  130398. var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, variableStatement); });
  130399. return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_const_to_let, fixId, ts.Diagnostics.Convert_const_to_let)];
  130400. },
  130401. fixIds: [fixId]
  130402. });
  130403. function getVariableStatement(sourceFile, pos, program) {
  130404. var token = ts.getTokenAtPosition(sourceFile, pos);
  130405. var checker = program.getTypeChecker();
  130406. var symbol = checker.getSymbolAtLocation(token);
  130407. if (symbol) {
  130408. return symbol.valueDeclaration.parent.parent;
  130409. }
  130410. }
  130411. function doChange(changes, sourceFile, variableStatement) {
  130412. if (!variableStatement) {
  130413. return;
  130414. }
  130415. var start = variableStatement.getStart();
  130416. changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 5 }, "let");
  130417. }
  130418. })(codefix = ts.codefix || (ts.codefix = {}));
  130419. })(ts || (ts = {}));
  130420. /* @internal */
  130421. var ts;
  130422. (function (ts) {
  130423. var refactor;
  130424. (function (refactor) {
  130425. var refactorName = "Convert export";
  130426. var actionNameDefaultToNamed = "Convert default export to named export";
  130427. var actionNameNamedToDefault = "Convert named export to default export";
  130428. refactor.registerRefactor(refactorName, {
  130429. getAvailableActions: function (context) {
  130430. var info = getInfo(context);
  130431. if (!info)
  130432. return ts.emptyArray;
  130433. var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message;
  130434. var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault;
  130435. return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
  130436. },
  130437. getEditsForAction: function (context, actionName) {
  130438. ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault, "Unexpected action name");
  130439. var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context), "context must have info"), t, context.cancellationToken); });
  130440. return { edits: edits, renameFilename: undefined, renameLocation: undefined };
  130441. },
  130442. });
  130443. function getInfo(context) {
  130444. var file = context.file;
  130445. var span = ts.getRefactorContextSpan(context);
  130446. var token = ts.getTokenAtPosition(file, span.start);
  130447. var exportNode = ts.getParentNodeInSpan(token, file, span);
  130448. if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) {
  130449. return undefined;
  130450. }
  130451. var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol;
  130452. var flags = ts.getModifierFlags(exportNode);
  130453. var wasDefault = !!(flags & 512 /* Default */);
  130454. // If source file already has a default export, don't offer refactor.
  130455. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
  130456. return undefined;
  130457. }
  130458. switch (exportNode.kind) {
  130459. case 244 /* FunctionDeclaration */:
  130460. case 245 /* ClassDeclaration */:
  130461. case 246 /* InterfaceDeclaration */:
  130462. case 248 /* EnumDeclaration */:
  130463. case 247 /* TypeAliasDeclaration */:
  130464. case 249 /* ModuleDeclaration */: {
  130465. var node = exportNode;
  130466. return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
  130467. }
  130468. case 225 /* VariableStatement */: {
  130469. var vs = exportNode;
  130470. // Must be `export const x = something;`.
  130471. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
  130472. return undefined;
  130473. }
  130474. var decl = ts.first(vs.declarationList.declarations);
  130475. if (!decl.initializer)
  130476. return undefined;
  130477. ts.Debug.assert(!wasDefault, "Can't have a default flag here");
  130478. return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
  130479. }
  130480. default:
  130481. return undefined;
  130482. }
  130483. }
  130484. function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
  130485. changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
  130486. changeImports(program, info, changes, cancellationToken);
  130487. }
  130488. function changeExport(exportingSourceFile, _a, changes, checker) {
  130489. var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName;
  130490. if (wasDefault) {
  130491. changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* DefaultKeyword */), "Should find a default keyword in modifier list"));
  130492. }
  130493. else {
  130494. var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 89 /* ExportKeyword */), "Should find an export keyword in modifier list");
  130495. switch (exportNode.kind) {
  130496. case 244 /* FunctionDeclaration */:
  130497. case 245 /* ClassDeclaration */:
  130498. case 246 /* InterfaceDeclaration */:
  130499. changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(84 /* DefaultKeyword */));
  130500. break;
  130501. case 225 /* VariableStatement */:
  130502. // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;`
  130503. if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) {
  130504. // We checked in `getInfo` that an initializer exists.
  130505. changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present")));
  130506. break;
  130507. }
  130508. // falls through
  130509. case 248 /* EnumDeclaration */:
  130510. case 247 /* TypeAliasDeclaration */:
  130511. case 249 /* ModuleDeclaration */:
  130512. // `export type T = number;` -> `type T = number; export default T;`
  130513. changes.deleteModifier(exportingSourceFile, exportKeyword);
  130514. changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text)));
  130515. break;
  130516. default:
  130517. ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind);
  130518. }
  130519. }
  130520. }
  130521. function changeImports(program, _a, changes, cancellationToken) {
  130522. var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol;
  130523. var checker = program.getTypeChecker();
  130524. var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
  130525. ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) {
  130526. var importingSourceFile = ref.getSourceFile();
  130527. if (wasDefault) {
  130528. changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
  130529. }
  130530. else {
  130531. changeNamedToDefaultImport(importingSourceFile, ref, changes);
  130532. }
  130533. });
  130534. }
  130535. function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
  130536. var parent = ref.parent;
  130537. switch (parent.kind) {
  130538. case 194 /* PropertyAccessExpression */:
  130539. // `a.default` --> `a.foo`
  130540. changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName));
  130541. break;
  130542. case 258 /* ImportSpecifier */:
  130543. case 263 /* ExportSpecifier */: {
  130544. var spec = parent;
  130545. // `default as foo` --> `foo`, `default as bar` --> `foo as bar`
  130546. changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
  130547. break;
  130548. }
  130549. case 255 /* ImportClause */: {
  130550. var clause = parent;
  130551. ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref");
  130552. var spec = makeImportSpecifier(exportName, ref.text);
  130553. var namedBindings = clause.namedBindings;
  130554. if (!namedBindings) {
  130555. // `import foo from "./a";` --> `import { foo } from "./a";`
  130556. changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec]));
  130557. }
  130558. else if (namedBindings.kind === 256 /* NamespaceImport */) {
  130559. // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";`
  130560. changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
  130561. var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
  130562. var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference);
  130563. changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
  130564. }
  130565. else {
  130566. // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";`
  130567. changes.delete(importingSourceFile, ref);
  130568. changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
  130569. }
  130570. break;
  130571. }
  130572. default:
  130573. ts.Debug.failBadSyntaxKind(parent);
  130574. }
  130575. }
  130576. function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
  130577. var parent = ref.parent;
  130578. switch (parent.kind) {
  130579. case 194 /* PropertyAccessExpression */:
  130580. // `a.foo` --> `a.default`
  130581. changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default"));
  130582. break;
  130583. case 258 /* ImportSpecifier */: {
  130584. // `import { foo } from "./a";` --> `import foo from "./a";`
  130585. // `import { foo as bar } from "./a";` --> `import bar from "./a";`
  130586. var defaultImport = ts.createIdentifier(parent.name.text);
  130587. if (parent.parent.elements.length === 1) {
  130588. changes.replaceNode(importingSourceFile, parent.parent, defaultImport);
  130589. }
  130590. else {
  130591. changes.delete(importingSourceFile, parent);
  130592. changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport);
  130593. }
  130594. break;
  130595. }
  130596. case 263 /* ExportSpecifier */: {
  130597. // `export { foo } from "./a";` --> `export { default as foo } from "./a";`
  130598. // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";`
  130599. // `export { foo as default } from "./a";` --> `export { default } from "./a";`
  130600. // (Because `export foo from "./a";` isn't valid syntax.)
  130601. changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text));
  130602. break;
  130603. }
  130604. default:
  130605. ts.Debug.assertNever(parent, "Unexpected parent kind " + parent.kind);
  130606. }
  130607. }
  130608. function makeImportSpecifier(propertyName, name) {
  130609. return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
  130610. }
  130611. function makeExportSpecifier(propertyName, name) {
  130612. return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
  130613. }
  130614. })(refactor = ts.refactor || (ts.refactor = {}));
  130615. })(ts || (ts = {}));
  130616. /* @internal */
  130617. var ts;
  130618. (function (ts) {
  130619. var refactor;
  130620. (function (refactor) {
  130621. var refactorName = "Convert import";
  130622. var actionNameNamespaceToNamed = "Convert namespace import to named imports";
  130623. var actionNameNamedToNamespace = "Convert named imports to namespace import";
  130624. refactor.registerRefactor(refactorName, {
  130625. getAvailableActions: function (context) {
  130626. var i = getImportToConvert(context);
  130627. if (!i)
  130628. return ts.emptyArray;
  130629. var description = i.kind === 256 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
  130630. var actionName = i.kind === 256 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
  130631. return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
  130632. },
  130633. getEditsForAction: function (context, actionName) {
  130634. ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace, "Unexpected action name");
  130635. var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context), "Context must provide an import to convert")); });
  130636. return { edits: edits, renameFilename: undefined, renameLocation: undefined };
  130637. }
  130638. });
  130639. // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`.
  130640. function getImportToConvert(context) {
  130641. var file = context.file;
  130642. var span = ts.getRefactorContextSpan(context);
  130643. var token = ts.getTokenAtPosition(file, span.start);
  130644. var importDecl = ts.getParentNodeInSpan(token, file, span);
  130645. if (!importDecl || !ts.isImportDeclaration(importDecl))
  130646. return undefined;
  130647. var importClause = importDecl.importClause;
  130648. return importClause && importClause.namedBindings;
  130649. }
  130650. function doChange(sourceFile, program, changes, toConvert) {
  130651. var checker = program.getTypeChecker();
  130652. if (toConvert.kind === 256 /* NamespaceImport */) {
  130653. doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()));
  130654. }
  130655. else {
  130656. doChangeNamedToNamespace(sourceFile, checker, changes, toConvert);
  130657. }
  130658. }
  130659. function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
  130660. var usedAsNamespaceOrDefault = false;
  130661. var nodesToReplace = [];
  130662. var conflictingNames = ts.createMap();
  130663. ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
  130664. if (!ts.isPropertyAccessExpression(id.parent)) {
  130665. usedAsNamespaceOrDefault = true;
  130666. }
  130667. else {
  130668. var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
  130669. var exportName = parent.name.text;
  130670. if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
  130671. conflictingNames.set(exportName, true);
  130672. }
  130673. ts.Debug.assert(parent.expression === id, "Parent expression should match id");
  130674. nodesToReplace.push(parent);
  130675. }
  130676. });
  130677. // We may need to change `mod.x` to `_x` to avoid a name conflict.
  130678. var exportNameToImportName = ts.createMap();
  130679. for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
  130680. var propertyAccess = nodesToReplace_1[_i];
  130681. var exportName = propertyAccess.name.text;
  130682. var importName = exportNameToImportName.get(exportName);
  130683. if (importName === undefined) {
  130684. exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
  130685. }
  130686. changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName));
  130687. }
  130688. var importSpecifiers = [];
  130689. exportNameToImportName.forEach(function (name, propertyName) {
  130690. importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)));
  130691. });
  130692. var importDecl = toConvert.parent.parent;
  130693. if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
  130694. // Need to leave the namespace import alone
  130695. changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers));
  130696. }
  130697. else {
  130698. changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
  130699. }
  130700. }
  130701. function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) {
  130702. var importDecl = toConvert.parent.parent;
  130703. var moduleSpecifier = importDecl.moduleSpecifier;
  130704. var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module";
  130705. var namespaceNameConflicts = toConvert.elements.some(function (element) {
  130706. return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
  130707. return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true);
  130708. }) || false;
  130709. });
  130710. var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
  130711. var neededNamedImports = [];
  130712. var _loop_15 = function (element) {
  130713. var propertyName = (element.propertyName || element.name).text;
  130714. ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
  130715. var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
  130716. if (ts.isShorthandPropertyAssignment(id.parent)) {
  130717. changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access));
  130718. }
  130719. else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) {
  130720. if (!neededNamedImports.some(function (n) { return n.name === element.name; })) {
  130721. neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text)));
  130722. }
  130723. }
  130724. else {
  130725. changes.replaceNode(sourceFile, id, access);
  130726. }
  130727. });
  130728. };
  130729. for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
  130730. var element = _a[_i];
  130731. _loop_15(element);
  130732. }
  130733. changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
  130734. if (neededNamedImports.length) {
  130735. changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports));
  130736. }
  130737. }
  130738. function updateImport(old, defaultImportName, elements) {
  130739. return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier);
  130740. }
  130741. })(refactor = ts.refactor || (ts.refactor = {}));
  130742. })(ts || (ts = {}));
  130743. /* @internal */
  130744. var ts;
  130745. (function (ts) {
  130746. var refactor;
  130747. (function (refactor) {
  130748. var extractSymbol;
  130749. (function (extractSymbol) {
  130750. var refactorName = "Extract Symbol";
  130751. refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction });
  130752. /**
  130753. * Compute the associated code actions
  130754. * Exported for tests.
  130755. */
  130756. function getAvailableActions(context) {
  130757. var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
  130758. var targetRange = rangeToExtract.targetRange;
  130759. if (targetRange === undefined) {
  130760. return ts.emptyArray;
  130761. }
  130762. var extractions = getPossibleExtractions(targetRange, context);
  130763. if (extractions === undefined) {
  130764. // No extractions possible
  130765. return ts.emptyArray;
  130766. }
  130767. var functionActions = [];
  130768. var usedFunctionNames = ts.createMap();
  130769. var constantActions = [];
  130770. var usedConstantNames = ts.createMap();
  130771. var i = 0;
  130772. for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) {
  130773. var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction;
  130774. // Skip these since we don't have a way to report errors yet
  130775. if (functionExtraction.errors.length === 0) {
  130776. // Don't issue refactorings with duplicated names.
  130777. // Scopes come back in "innermost first" order, so extractions will
  130778. // preferentially go into nearer scopes
  130779. var description = functionExtraction.description;
  130780. if (!usedFunctionNames.has(description)) {
  130781. usedFunctionNames.set(description, true);
  130782. functionActions.push({
  130783. description: description,
  130784. name: "function_scope_" + i
  130785. });
  130786. }
  130787. }
  130788. // Skip these since we don't have a way to report errors yet
  130789. if (constantExtraction.errors.length === 0) {
  130790. // Don't issue refactorings with duplicated names.
  130791. // Scopes come back in "innermost first" order, so extractions will
  130792. // preferentially go into nearer scopes
  130793. var description = constantExtraction.description;
  130794. if (!usedConstantNames.has(description)) {
  130795. usedConstantNames.set(description, true);
  130796. constantActions.push({
  130797. description: description,
  130798. name: "constant_scope_" + i
  130799. });
  130800. }
  130801. }
  130802. // *do* increment i anyway because we'll look for the i-th scope
  130803. // later when actually doing the refactoring if the user requests it
  130804. i++;
  130805. }
  130806. var infos = [];
  130807. if (constantActions.length) {
  130808. infos.push({
  130809. name: refactorName,
  130810. description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
  130811. actions: constantActions
  130812. });
  130813. }
  130814. if (functionActions.length) {
  130815. infos.push({
  130816. name: refactorName,
  130817. description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
  130818. actions: functionActions
  130819. });
  130820. }
  130821. return infos.length ? infos : ts.emptyArray;
  130822. }
  130823. extractSymbol.getAvailableActions = getAvailableActions;
  130824. /* Exported for tests */
  130825. function getEditsForAction(context, actionName) {
  130826. var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
  130827. var targetRange = rangeToExtract.targetRange; // TODO:GH#18217
  130828. var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
  130829. if (parsedFunctionIndexMatch) {
  130830. var index = +parsedFunctionIndexMatch[1];
  130831. ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
  130832. return getFunctionExtractionAtIndex(targetRange, context, index);
  130833. }
  130834. var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName);
  130835. if (parsedConstantIndexMatch) {
  130836. var index = +parsedConstantIndexMatch[1];
  130837. ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
  130838. return getConstantExtractionAtIndex(targetRange, context, index);
  130839. }
  130840. ts.Debug.fail("Unrecognized action name");
  130841. }
  130842. extractSymbol.getEditsForAction = getEditsForAction;
  130843. // Move these into diagnostic messages if they become user-facing
  130844. var Messages;
  130845. (function (Messages) {
  130846. function createMessage(message) {
  130847. return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message };
  130848. }
  130849. Messages.cannotExtractRange = createMessage("Cannot extract range.");
  130850. Messages.cannotExtractImport = createMessage("Cannot extract import statement.");
  130851. Messages.cannotExtractSuper = createMessage("Cannot extract super call.");
  130852. Messages.cannotExtractJSDoc = createMessage("Cannot extract JSDoc.");
  130853. Messages.cannotExtractEmpty = createMessage("Cannot extract empty range.");
  130854. Messages.expressionExpected = createMessage("expression expected.");
  130855. Messages.uselessConstantType = createMessage("No reason to extract constant of type.");
  130856. Messages.statementOrExpressionExpected = createMessage("Statement or expression expected.");
  130857. Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements.");
  130858. Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement.");
  130859. Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
  130860. Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
  130861. Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
  130862. Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
  130863. Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier.");
  130864. Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
  130865. Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
  130866. Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
  130867. Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
  130868. Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
  130869. Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
  130870. Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
  130871. Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
  130872. })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {}));
  130873. var RangeFacts;
  130874. (function (RangeFacts) {
  130875. RangeFacts[RangeFacts["None"] = 0] = "None";
  130876. RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn";
  130877. RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator";
  130878. RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction";
  130879. RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis";
  130880. /**
  130881. * The range is in a function which needs the 'static' modifier in a class
  130882. */
  130883. RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion";
  130884. })(RangeFacts || (RangeFacts = {}));
  130885. /**
  130886. * getRangeToExtract takes a span inside a text file and returns either an expression or an array
  130887. * of statements representing the minimum set of nodes needed to extract the entire span. This
  130888. * process may fail, in which case a set of errors is returned instead (these are currently
  130889. * not shown to the user, but can be used by us diagnostically)
  130890. */
  130891. // exported only for tests
  130892. function getRangeToExtract(sourceFile, span) {
  130893. var length = span.length;
  130894. if (length === 0) {
  130895. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] };
  130896. }
  130897. // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
  130898. // This may fail (e.g. you select two statements in the root of a source file)
  130899. var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span);
  130900. // Do the same for the ending position
  130901. var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span);
  130902. var declarations = [];
  130903. // We'll modify these flags as we walk the tree to collect data
  130904. // about what things need to be done as part of the extraction.
  130905. var rangeFacts = RangeFacts.None;
  130906. if (!start || !end) {
  130907. // cannot find either start or end node
  130908. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
  130909. }
  130910. if (start.parent !== end.parent) {
  130911. // start and end nodes belong to different subtrees
  130912. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
  130913. }
  130914. if (start !== end) {
  130915. // start and end should be statements and parent should be either block or a source file
  130916. if (!isBlockLike(start.parent)) {
  130917. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
  130918. }
  130919. var statements = [];
  130920. var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248
  130921. for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) {
  130922. var statement = _a[_i];
  130923. if (statement === start || statements.length) {
  130924. var errors_1 = checkNode(statement);
  130925. if (errors_1) {
  130926. return { errors: errors_1 };
  130927. }
  130928. statements.push(statement);
  130929. }
  130930. if (statement === end) {
  130931. break;
  130932. }
  130933. }
  130934. if (!statements.length) {
  130935. // https://github.com/Microsoft/TypeScript/issues/20559
  130936. // Ranges like [|case 1: break;|] will fail to populate `statements` because
  130937. // they will never find `start` in `start.parent.statements`.
  130938. // Consider: We could support ranges like [|case 1:|] by refining them to just
  130939. // the expression.
  130940. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
  130941. }
  130942. return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } };
  130943. }
  130944. if (ts.isJSDoc(start)) {
  130945. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] };
  130946. }
  130947. if (ts.isReturnStatement(start) && !start.expression) {
  130948. // Makes no sense to extract an expression-less return statement.
  130949. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
  130950. }
  130951. // We have a single node (start)
  130952. var node = refineNode(start);
  130953. var errors = checkRootNode(node) || checkNode(node);
  130954. if (errors) {
  130955. return { errors: errors };
  130956. }
  130957. return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217
  130958. /**
  130959. * Attempt to refine the extraction node (generally, by shrinking it) to produce better results.
  130960. * @param node The unrefined extraction node.
  130961. */
  130962. function refineNode(node) {
  130963. if (ts.isReturnStatement(node)) {
  130964. if (node.expression) {
  130965. return node.expression;
  130966. }
  130967. }
  130968. else if (ts.isVariableStatement(node)) {
  130969. var numInitializers = 0;
  130970. var lastInitializer = void 0;
  130971. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
  130972. var declaration = _a[_i];
  130973. if (declaration.initializer) {
  130974. numInitializers++;
  130975. lastInitializer = declaration.initializer;
  130976. }
  130977. }
  130978. if (numInitializers === 1) {
  130979. return lastInitializer;
  130980. }
  130981. // No special handling if there are multiple initializers.
  130982. }
  130983. else if (ts.isVariableDeclaration(node)) {
  130984. if (node.initializer) {
  130985. return node.initializer;
  130986. }
  130987. }
  130988. return node;
  130989. }
  130990. function checkRootNode(node) {
  130991. if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) {
  130992. return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
  130993. }
  130994. return undefined;
  130995. }
  130996. function checkForStaticContext(nodeToCheck, containingClass) {
  130997. var current = nodeToCheck;
  130998. while (current !== containingClass) {
  130999. if (current.kind === 159 /* PropertyDeclaration */) {
  131000. if (ts.hasModifier(current, 32 /* Static */)) {
  131001. rangeFacts |= RangeFacts.InStaticRegion;
  131002. }
  131003. break;
  131004. }
  131005. else if (current.kind === 156 /* Parameter */) {
  131006. var ctorOrMethod = ts.getContainingFunction(current);
  131007. if (ctorOrMethod.kind === 162 /* Constructor */) {
  131008. rangeFacts |= RangeFacts.InStaticRegion;
  131009. }
  131010. break;
  131011. }
  131012. else if (current.kind === 161 /* MethodDeclaration */) {
  131013. if (ts.hasModifier(current, 32 /* Static */)) {
  131014. rangeFacts |= RangeFacts.InStaticRegion;
  131015. }
  131016. }
  131017. current = current.parent;
  131018. }
  131019. }
  131020. // Verifies whether we can actually extract this node or not.
  131021. function checkNode(nodeToCheck) {
  131022. var PermittedJumps;
  131023. (function (PermittedJumps) {
  131024. PermittedJumps[PermittedJumps["None"] = 0] = "None";
  131025. PermittedJumps[PermittedJumps["Break"] = 1] = "Break";
  131026. PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue";
  131027. PermittedJumps[PermittedJumps["Return"] = 4] = "Return";
  131028. })(PermittedJumps || (PermittedJumps = {}));
  131029. // We believe it's true because the node is from the (unmodified) tree.
  131030. ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)");
  131031. // For understanding how skipTrivia functioned:
  131032. ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)");
  131033. if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) {
  131034. return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
  131035. }
  131036. if (nodeToCheck.flags & 8388608 /* Ambient */) {
  131037. return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
  131038. }
  131039. // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)
  131040. var containingClass = ts.getContainingClass(nodeToCheck);
  131041. if (containingClass) {
  131042. checkForStaticContext(nodeToCheck, containingClass);
  131043. }
  131044. var errors;
  131045. var permittedJumps = 4 /* Return */;
  131046. var seenLabels;
  131047. visit(nodeToCheck);
  131048. return errors;
  131049. function visit(node) {
  131050. if (errors) {
  131051. // already found an error - can stop now
  131052. return true;
  131053. }
  131054. if (ts.isDeclaration(node)) {
  131055. var declaringNode = (node.kind === 242 /* VariableDeclaration */) ? node.parent.parent : node;
  131056. if (ts.hasModifier(declaringNode, 1 /* Export */)) {
  131057. // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)
  131058. // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!
  131059. // Also TODO: GH#19956
  131060. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
  131061. return true;
  131062. }
  131063. declarations.push(node.symbol);
  131064. }
  131065. // Some things can't be extracted in certain situations
  131066. switch (node.kind) {
  131067. case 254 /* ImportDeclaration */:
  131068. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport));
  131069. return true;
  131070. case 102 /* SuperKeyword */:
  131071. // For a super *constructor call*, we have to be extracting the entire class,
  131072. // but a super *method call* simply implies a 'this' reference
  131073. if (node.parent.kind === 196 /* CallExpression */) {
  131074. // Super constructor call
  131075. var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217
  131076. if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) {
  131077. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper));
  131078. return true;
  131079. }
  131080. }
  131081. else {
  131082. rangeFacts |= RangeFacts.UsesThis;
  131083. }
  131084. break;
  131085. }
  131086. if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) {
  131087. switch (node.kind) {
  131088. case 244 /* FunctionDeclaration */:
  131089. case 245 /* ClassDeclaration */:
  131090. if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
  131091. // You cannot extract global declarations
  131092. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
  131093. }
  131094. break;
  131095. }
  131096. // do not dive into functions or classes
  131097. return false;
  131098. }
  131099. var savedPermittedJumps = permittedJumps;
  131100. switch (node.kind) {
  131101. case 227 /* IfStatement */:
  131102. permittedJumps = 0 /* None */;
  131103. break;
  131104. case 240 /* TryStatement */:
  131105. // forbid all jumps inside try blocks
  131106. permittedJumps = 0 /* None */;
  131107. break;
  131108. case 223 /* Block */:
  131109. if (node.parent && node.parent.kind === 240 /* TryStatement */ && node.parent.finallyBlock === node) {
  131110. // allow unconditional returns from finally blocks
  131111. permittedJumps = 4 /* Return */;
  131112. }
  131113. break;
  131114. case 278 /* DefaultClause */:
  131115. case 277 /* CaseClause */:
  131116. // allow unlabeled break inside case clauses
  131117. permittedJumps |= 1 /* Break */;
  131118. break;
  131119. default:
  131120. if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) {
  131121. // allow unlabeled break/continue inside loops
  131122. permittedJumps |= 1 /* Break */ | 2 /* Continue */;
  131123. }
  131124. break;
  131125. }
  131126. switch (node.kind) {
  131127. case 183 /* ThisType */:
  131128. case 104 /* ThisKeyword */:
  131129. rangeFacts |= RangeFacts.UsesThis;
  131130. break;
  131131. case 238 /* LabeledStatement */: {
  131132. var label = node.label;
  131133. (seenLabels || (seenLabels = [])).push(label.escapedText);
  131134. ts.forEachChild(node, visit);
  131135. seenLabels.pop();
  131136. break;
  131137. }
  131138. case 234 /* BreakStatement */:
  131139. case 233 /* ContinueStatement */: {
  131140. var label = node.label;
  131141. if (label) {
  131142. if (!ts.contains(seenLabels, label.escapedText)) {
  131143. // attempts to jump to label that is not in range to be extracted
  131144. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
  131145. }
  131146. }
  131147. else {
  131148. if (!(permittedJumps & (node.kind === 234 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
  131149. // attempt to break or continue in a forbidden context
  131150. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
  131151. }
  131152. }
  131153. break;
  131154. }
  131155. case 206 /* AwaitExpression */:
  131156. rangeFacts |= RangeFacts.IsAsyncFunction;
  131157. break;
  131158. case 212 /* YieldExpression */:
  131159. rangeFacts |= RangeFacts.IsGenerator;
  131160. break;
  131161. case 235 /* ReturnStatement */:
  131162. if (permittedJumps & 4 /* Return */) {
  131163. rangeFacts |= RangeFacts.HasReturn;
  131164. }
  131165. else {
  131166. (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement));
  131167. }
  131168. break;
  131169. default:
  131170. ts.forEachChild(node, visit);
  131171. break;
  131172. }
  131173. permittedJumps = savedPermittedJumps;
  131174. }
  131175. }
  131176. }
  131177. extractSymbol.getRangeToExtract = getRangeToExtract;
  131178. function getStatementOrExpressionRange(node) {
  131179. if (ts.isStatement(node)) {
  131180. return [node];
  131181. }
  131182. else if (ts.isExpressionNode(node)) {
  131183. // If our selection is the expression in an ExpressionStatement, expand
  131184. // the selection to include the enclosing Statement (this stops us
  131185. // from trying to care about the return value of the extracted function
  131186. // and eliminates double semicolon insertion in certain scenarios)
  131187. return ts.isExpressionStatement(node.parent) ? [node.parent] : node;
  131188. }
  131189. return undefined;
  131190. }
  131191. function isScope(node) {
  131192. return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node);
  131193. }
  131194. /**
  131195. * Computes possible places we could extract the function into. For example,
  131196. * you may be able to extract into a class method *or* local closure *or* namespace function,
  131197. * depending on what's in the extracted body.
  131198. */
  131199. function collectEnclosingScopes(range) {
  131200. var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
  131201. if (range.facts & RangeFacts.UsesThis) {
  131202. // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class
  131203. var containingClass = ts.getContainingClass(current);
  131204. if (containingClass) {
  131205. var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration);
  131206. return containingFunction
  131207. ? [containingFunction, containingClass]
  131208. : [containingClass];
  131209. }
  131210. }
  131211. var scopes = [];
  131212. while (true) {
  131213. current = current.parent;
  131214. // A function parameter's initializer is actually in the outer scope, not the function declaration
  131215. if (current.kind === 156 /* Parameter */) {
  131216. // Skip all the way to the outer scope of the function that declared this parameter
  131217. current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent;
  131218. }
  131219. // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of.
  131220. // Walk up to the closest parent of a place where we can logically put a sibling:
  131221. // * Function declaration
  131222. // * Class declaration or expression
  131223. // * Module/namespace or source file
  131224. if (isScope(current)) {
  131225. scopes.push(current);
  131226. if (current.kind === 290 /* SourceFile */) {
  131227. return scopes;
  131228. }
  131229. }
  131230. }
  131231. }
  131232. function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) {
  131233. var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
  131234. ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
  131235. context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217
  131236. return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
  131237. }
  131238. function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) {
  131239. var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
  131240. ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
  131241. ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
  131242. context.cancellationToken.throwIfCancellationRequested();
  131243. var expression = ts.isExpression(target)
  131244. ? target
  131245. : target.statements[0].expression;
  131246. return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
  131247. }
  131248. /**
  131249. * Given a piece of text to extract ('targetRange'), computes a list of possible extractions.
  131250. * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes
  131251. * or an error explaining why we can't extract into that scope.
  131252. */
  131253. function getPossibleExtractions(targetRange, context) {
  131254. var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope;
  131255. // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547
  131256. var extractions = scopes.map(function (scope, i) {
  131257. var functionDescriptionPart = getDescriptionForFunctionInScope(scope);
  131258. var constantDescriptionPart = getDescriptionForConstantInScope(scope);
  131259. var scopeDescription = ts.isFunctionLikeDeclaration(scope)
  131260. ? getDescriptionForFunctionLikeDeclaration(scope)
  131261. : ts.isClassLike(scope)
  131262. ? getDescriptionForClassLikeDeclaration(scope)
  131263. : getDescriptionForModuleLikeDeclaration(scope);
  131264. var functionDescription;
  131265. var constantDescription;
  131266. if (scopeDescription === 1 /* Global */) {
  131267. functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
  131268. constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
  131269. }
  131270. else if (scopeDescription === 0 /* Module */) {
  131271. functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
  131272. constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
  131273. }
  131274. else {
  131275. functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
  131276. constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
  131277. }
  131278. // Customize the phrasing for the innermost scope to increase clarity.
  131279. if (i === 0 && !ts.isClassLike(scope)) {
  131280. constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
  131281. }
  131282. return {
  131283. functionExtraction: {
  131284. description: functionDescription,
  131285. errors: functionErrorsPerScope[i],
  131286. },
  131287. constantExtraction: {
  131288. description: constantDescription,
  131289. errors: constantErrorsPerScope[i],
  131290. },
  131291. };
  131292. });
  131293. return extractions;
  131294. }
  131295. function getPossibleExtractionsWorker(targetRange, context) {
  131296. var sourceFile = context.file;
  131297. var scopes = collectEnclosingScopes(targetRange);
  131298. var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
  131299. var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken);
  131300. return { scopes: scopes, readsAndWrites: readsAndWrites };
  131301. }
  131302. function getDescriptionForFunctionInScope(scope) {
  131303. return ts.isFunctionLikeDeclaration(scope)
  131304. ? "inner function"
  131305. : ts.isClassLike(scope)
  131306. ? "method"
  131307. : "function";
  131308. }
  131309. function getDescriptionForConstantInScope(scope) {
  131310. return ts.isClassLike(scope)
  131311. ? "readonly field"
  131312. : "constant";
  131313. }
  131314. function getDescriptionForFunctionLikeDeclaration(scope) {
  131315. switch (scope.kind) {
  131316. case 162 /* Constructor */:
  131317. return "constructor";
  131318. case 201 /* FunctionExpression */:
  131319. case 244 /* FunctionDeclaration */:
  131320. return scope.name
  131321. ? "function '" + scope.name.text + "'"
  131322. : "anonymous function";
  131323. case 202 /* ArrowFunction */:
  131324. return "arrow function";
  131325. case 161 /* MethodDeclaration */:
  131326. return "method '" + scope.name.getText() + "'";
  131327. case 163 /* GetAccessor */:
  131328. return "'get " + scope.name.getText() + "'";
  131329. case 164 /* SetAccessor */:
  131330. return "'set " + scope.name.getText() + "'";
  131331. default:
  131332. throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind);
  131333. }
  131334. }
  131335. function getDescriptionForClassLikeDeclaration(scope) {
  131336. return scope.kind === 245 /* ClassDeclaration */
  131337. ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration"
  131338. : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression";
  131339. }
  131340. function getDescriptionForModuleLikeDeclaration(scope) {
  131341. return scope.kind === 250 /* ModuleBlock */
  131342. ? "namespace '" + scope.parent.name.getText() + "'"
  131343. : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
  131344. }
  131345. var SpecialScope;
  131346. (function (SpecialScope) {
  131347. SpecialScope[SpecialScope["Module"] = 0] = "Module";
  131348. SpecialScope[SpecialScope["Global"] = 1] = "Global";
  131349. })(SpecialScope || (SpecialScope = {}));
  131350. /**
  131351. * Result of 'extractRange' operation for a specific scope.
  131352. * Stores either a list of changes that should be applied to extract a range or a list of errors
  131353. */
  131354. function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) {
  131355. var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions;
  131356. var checker = context.program.getTypeChecker();
  131357. // Make a unique name for the extracted function
  131358. var file = scope.getSourceFile();
  131359. var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file);
  131360. var isJS = ts.isInJSFile(scope);
  131361. var functionName = ts.createIdentifier(functionNameText);
  131362. var returnType;
  131363. var parameters = [];
  131364. var callArguments = [];
  131365. var writes;
  131366. usagesInScope.forEach(function (usage, name) {
  131367. var typeNode;
  131368. if (!isJS) {
  131369. var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
  131370. // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
  131371. type = checker.getBaseTypeOfLiteralType(type);
  131372. typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */);
  131373. }
  131374. var paramDecl = ts.createParameter(
  131375. /*decorators*/ undefined,
  131376. /*modifiers*/ undefined,
  131377. /*dotDotDotToken*/ undefined,
  131378. /*name*/ name,
  131379. /*questionToken*/ undefined, typeNode);
  131380. parameters.push(paramDecl);
  131381. if (usage.usage === 2 /* Write */) {
  131382. (writes || (writes = [])).push(usage);
  131383. }
  131384. callArguments.push(ts.createIdentifier(name));
  131385. });
  131386. var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); });
  131387. var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
  131388. var typeParameters = sortedTypeParametersAndDeclarations.length === 0
  131389. ? undefined
  131390. : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; });
  131391. // Strictly speaking, we should check whether each name actually binds to the appropriate type
  131392. // parameter. In cases of shadowing, they may not.
  131393. var callTypeArguments = typeParameters !== undefined
  131394. ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); })
  131395. : undefined;
  131396. // Provide explicit return types for contextually-typed functions
  131397. // to avoid problems when there are literal types present
  131398. if (ts.isExpression(node) && !isJS) {
  131399. var contextualType = checker.getContextualType(node);
  131400. returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217
  131401. }
  131402. var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty;
  131403. ts.suppressLeadingAndTrailingTrivia(body);
  131404. var newFunction;
  131405. if (ts.isClassLike(scope)) {
  131406. // always create private method in TypeScript files
  131407. var modifiers = isJS ? [] : [ts.createToken(117 /* PrivateKeyword */)];
  131408. if (range.facts & RangeFacts.InStaticRegion) {
  131409. modifiers.push(ts.createToken(120 /* StaticKeyword */));
  131410. }
  131411. if (range.facts & RangeFacts.IsAsyncFunction) {
  131412. modifiers.push(ts.createToken(126 /* AsyncKeyword */));
  131413. }
  131414. newFunction = ts.createMethod(
  131415. /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(41 /* AsteriskToken */) : undefined, functionName,
  131416. /*questionToken*/ undefined, typeParameters, parameters, returnType, body);
  131417. }
  131418. else {
  131419. newFunction = ts.createFunctionDeclaration(
  131420. /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(126 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(41 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body);
  131421. }
  131422. var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
  131423. var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end;
  131424. var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
  131425. if (nodeToInsertBefore) {
  131426. changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true);
  131427. }
  131428. else {
  131429. changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
  131430. }
  131431. var newNodes = [];
  131432. // replace range with function call
  131433. var called = getCalledExpression(scope, range, functionNameText);
  131434. var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference
  131435. callArguments);
  131436. if (range.facts & RangeFacts.IsGenerator) {
  131437. call = ts.createYield(ts.createToken(41 /* AsteriskToken */), call);
  131438. }
  131439. if (range.facts & RangeFacts.IsAsyncFunction) {
  131440. call = ts.createAwait(call);
  131441. }
  131442. if (exposedVariableDeclarations.length && !writes) {
  131443. // No need to mix declarations and writes.
  131444. // How could any variables be exposed if there's a return statement?
  131445. ts.Debug.assert(!returnValueProperty, "Expected no returnValueProperty");
  131446. ts.Debug.assert(!(range.facts & RangeFacts.HasReturn), "Expected RangeFacts.HasReturn flag to be unset");
  131447. if (exposedVariableDeclarations.length === 1) {
  131448. // Declaring exactly one variable: let x = newFunction();
  131449. var variableDeclaration = exposedVariableDeclarations[0];
  131450. newNodes.push(ts.createVariableStatement(
  131451. /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns
  131452. variableDeclaration.parent.flags)));
  131453. }
  131454. else {
  131455. // Declaring multiple variables / return properties:
  131456. // let {x, y} = newFunction();
  131457. var bindingElements = [];
  131458. var typeElements = [];
  131459. var commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
  131460. var sawExplicitType = false;
  131461. for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) {
  131462. var variableDeclaration = exposedVariableDeclarations_1[_i];
  131463. bindingElements.push(ts.createBindingElement(
  131464. /*dotDotDotToken*/ undefined,
  131465. /*propertyName*/ undefined,
  131466. /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name)));
  131467. // Being returned through an object literal will have widened the type.
  131468. var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */);
  131469. typeElements.push(ts.createPropertySignature(
  131470. /*modifiers*/ undefined,
  131471. /*name*/ variableDeclaration.symbol.name,
  131472. /*questionToken*/ undefined,
  131473. /*type*/ variableType,
  131474. /*initializer*/ undefined));
  131475. sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined;
  131476. commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
  131477. }
  131478. var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined;
  131479. if (typeLiteral) {
  131480. ts.setEmitFlags(typeLiteral, 1 /* SingleLine */);
  131481. }
  131482. newNodes.push(ts.createVariableStatement(
  131483. /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements),
  131484. /*type*/ typeLiteral,
  131485. /*initializer*/ call)], commonNodeFlags)));
  131486. }
  131487. }
  131488. else if (exposedVariableDeclarations.length || writes) {
  131489. if (exposedVariableDeclarations.length) {
  131490. // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping.
  131491. for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) {
  131492. var variableDeclaration = exposedVariableDeclarations_2[_c];
  131493. var flags = variableDeclaration.parent.flags;
  131494. if (flags & 2 /* Const */) {
  131495. flags = (flags & ~2 /* Const */) | 1 /* Let */;
  131496. }
  131497. newNodes.push(ts.createVariableStatement(
  131498. /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags)));
  131499. }
  131500. }
  131501. if (returnValueProperty) {
  131502. // has both writes and return, need to create variable declaration to hold return value;
  131503. newNodes.push(ts.createVariableStatement(
  131504. /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */)));
  131505. }
  131506. var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
  131507. if (returnValueProperty) {
  131508. assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty));
  131509. }
  131510. // propagate writes back
  131511. if (assignments.length === 1) {
  131512. // We would only have introduced a return value property if there had been
  131513. // other assignments to make.
  131514. ts.Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here");
  131515. newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call)));
  131516. if (range.facts & RangeFacts.HasReturn) {
  131517. newNodes.push(ts.createReturn());
  131518. }
  131519. }
  131520. else {
  131521. // emit e.g.
  131522. // { a, b, __return } = newFunction(a, b);
  131523. // return __return;
  131524. newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call)));
  131525. if (returnValueProperty) {
  131526. newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty)));
  131527. }
  131528. }
  131529. }
  131530. else {
  131531. if (range.facts & RangeFacts.HasReturn) {
  131532. newNodes.push(ts.createReturn(call));
  131533. }
  131534. else if (isReadonlyArray(range.range)) {
  131535. newNodes.push(ts.createStatement(call));
  131536. }
  131537. else {
  131538. newNodes.push(call);
  131539. }
  131540. }
  131541. if (isReadonlyArray(range.range)) {
  131542. changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes);
  131543. }
  131544. else {
  131545. changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes);
  131546. }
  131547. var edits = changeTracker.getChanges();
  131548. var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
  131549. var renameFilename = renameRange.getSourceFile().fileName;
  131550. var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false);
  131551. return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
  131552. function getTypeDeepCloneUnionUndefined(typeNode) {
  131553. if (typeNode === undefined) {
  131554. return undefined;
  131555. }
  131556. var clone = ts.getSynthesizedDeepClone(typeNode);
  131557. var withoutParens = clone;
  131558. while (ts.isParenthesizedTypeNode(withoutParens)) {
  131559. withoutParens = withoutParens.type;
  131560. }
  131561. return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 146 /* UndefinedKeyword */; })
  131562. ? clone
  131563. : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
  131564. }
  131565. }
  131566. /**
  131567. * Result of 'extractRange' operation for a specific scope.
  131568. * Stores either a list of changes that should be applied to extract a range or a list of errors
  131569. */
  131570. function extractConstantInScope(node, scope, _a, rangeFacts, context) {
  131571. var _b;
  131572. var substitutions = _a.substitutions;
  131573. var checker = context.program.getTypeChecker();
  131574. // Make a unique name for the extracted variable
  131575. var file = scope.getSourceFile();
  131576. var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file);
  131577. var isJS = ts.isInJSFile(scope);
  131578. var variableType = isJS || !checker.isContextSensitive(node)
  131579. ? undefined
  131580. : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217
  131581. var initializer = transformConstantInitializer(node, substitutions);
  131582. (_b = transformFunctionInitializerAndType(variableType, initializer), variableType = _b.variableType, initializer = _b.initializer);
  131583. ts.suppressLeadingAndTrailingTrivia(initializer);
  131584. var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
  131585. if (ts.isClassLike(scope)) {
  131586. ts.Debug.assert(!isJS, "Cannot extract to a JS class"); // See CannotExtractToJSClass
  131587. var modifiers = [];
  131588. modifiers.push(ts.createToken(117 /* PrivateKeyword */));
  131589. if (rangeFacts & RangeFacts.InStaticRegion) {
  131590. modifiers.push(ts.createToken(120 /* StaticKeyword */));
  131591. }
  131592. modifiers.push(ts.createToken(138 /* ReadonlyKeyword */));
  131593. var newVariable = ts.createProperty(
  131594. /*decorators*/ undefined, modifiers, localNameText,
  131595. /*questionToken*/ undefined, variableType, initializer);
  131596. var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion
  131597. ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217
  131598. : ts.createThis(), ts.createIdentifier(localNameText));
  131599. // Declare
  131600. var maxInsertionPos = node.pos;
  131601. var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope);
  131602. changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true);
  131603. // Consume
  131604. changeTracker.replaceNode(context.file, node, localReference);
  131605. }
  131606. else {
  131607. var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer);
  131608. // If the node is part of an initializer in a list of variable declarations, insert a new
  131609. // variable declaration into the list (in case it depends on earlier ones).
  131610. // CONSIDER: If the declaration list isn't const, we might want to split it into multiple
  131611. // lists so that the newly extracted one can be const.
  131612. var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope);
  131613. if (oldVariableDeclaration) {
  131614. // Declare
  131615. // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`)
  131616. changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration);
  131617. // Consume
  131618. var localReference = ts.createIdentifier(localNameText);
  131619. changeTracker.replaceNode(context.file, node, localReference);
  131620. }
  131621. else if (node.parent.kind === 226 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) {
  131622. // If the parent is an expression statement and the target scope is the immediately enclosing one,
  131623. // replace the statement with the declaration.
  131624. var newVariableStatement = ts.createVariableStatement(
  131625. /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
  131626. changeTracker.replaceNode(context.file, node.parent, newVariableStatement);
  131627. }
  131628. else {
  131629. var newVariableStatement = ts.createVariableStatement(
  131630. /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
  131631. // Declare
  131632. var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope);
  131633. if (nodeToInsertBefore.pos === 0) {
  131634. changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false);
  131635. }
  131636. else {
  131637. changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false);
  131638. }
  131639. // Consume
  131640. if (node.parent.kind === 226 /* ExpressionStatement */) {
  131641. // If the parent is an expression statement, delete it.
  131642. changeTracker.delete(context.file, node.parent);
  131643. }
  131644. else {
  131645. var localReference = ts.createIdentifier(localNameText);
  131646. changeTracker.replaceNode(context.file, node, localReference);
  131647. }
  131648. }
  131649. }
  131650. var edits = changeTracker.getChanges();
  131651. var renameFilename = node.getSourceFile().fileName;
  131652. var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true);
  131653. return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
  131654. function transformFunctionInitializerAndType(variableType, initializer) {
  131655. // If no contextual type exists there is nothing to transfer to the function signature
  131656. if (variableType === undefined)
  131657. return { variableType: variableType, initializer: initializer };
  131658. // Only do this for function expressions and arrow functions that are not generic
  131659. if (!ts.isFunctionExpression(initializer) && !ts.isArrowFunction(initializer) || !!initializer.typeParameters)
  131660. return { variableType: variableType, initializer: initializer };
  131661. var functionType = checker.getTypeAtLocation(node);
  131662. var functionSignature = ts.singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */));
  131663. // If no function signature, maybe there was an error, do nothing
  131664. if (!functionSignature)
  131665. return { variableType: variableType, initializer: initializer };
  131666. // If the function signature has generic type parameters we don't attempt to move the parameters
  131667. if (!!functionSignature.getTypeParameters())
  131668. return { variableType: variableType, initializer: initializer };
  131669. // We add parameter types if needed
  131670. var parameters = [];
  131671. var hasAny = false;
  131672. for (var _i = 0, _a = initializer.parameters; _i < _a.length; _i++) {
  131673. var p = _a[_i];
  131674. if (p.type) {
  131675. parameters.push(p);
  131676. }
  131677. else {
  131678. var paramType = checker.getTypeAtLocation(p);
  131679. if (paramType === checker.getAnyType())
  131680. hasAny = true;
  131681. parameters.push(ts.updateParameter(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */), p.initializer));
  131682. }
  131683. }
  131684. // If a parameter was inferred as any we skip adding function parameters at all.
  131685. // Turning an implicit any (which under common settings is a error) to an explicit
  131686. // is probably actually a worse refactor outcome.
  131687. if (hasAny)
  131688. return { variableType: variableType, initializer: initializer };
  131689. variableType = undefined;
  131690. if (ts.isArrowFunction(initializer)) {
  131691. initializer = ts.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer.equalsGreaterThanToken, initializer.body);
  131692. }
  131693. else {
  131694. if (functionSignature && !!functionSignature.thisParameter) {
  131695. var firstParameter = ts.firstOrUndefined(parameters);
  131696. // If the function signature has a this parameter and if the first defined parameter is not the this parameter, we must add it
  131697. // Note: If this parameter was already there, it would have been previously updated with the type if not type was present
  131698. if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) {
  131699. var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node);
  131700. parameters.splice(0, 0, ts.createParameter(
  131701. /* decorators */ undefined,
  131702. /* modifiers */ undefined,
  131703. /* dotDotDotToken */ undefined, "this",
  131704. /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */)));
  131705. }
  131706. }
  131707. initializer = ts.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer.body);
  131708. }
  131709. return { variableType: variableType, initializer: initializer };
  131710. }
  131711. }
  131712. function getContainingVariableDeclarationIfInList(node, scope) {
  131713. var prevNode;
  131714. while (node !== undefined && node !== scope) {
  131715. if (ts.isVariableDeclaration(node) &&
  131716. node.initializer === prevNode &&
  131717. ts.isVariableDeclarationList(node.parent) &&
  131718. node.parent.declarations.length > 1) {
  131719. return node;
  131720. }
  131721. prevNode = node;
  131722. node = node.parent;
  131723. }
  131724. }
  131725. function getFirstDeclaration(type) {
  131726. var firstDeclaration;
  131727. var symbol = type.symbol;
  131728. if (symbol && symbol.declarations) {
  131729. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  131730. var declaration = _a[_i];
  131731. if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) {
  131732. firstDeclaration = declaration;
  131733. }
  131734. }
  131735. }
  131736. return firstDeclaration;
  131737. }
  131738. function compareTypesByDeclarationOrder(_a, _b) {
  131739. var type1 = _a.type, declaration1 = _a.declaration;
  131740. var type2 = _b.type, declaration2 = _b.declaration;
  131741. return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues)
  131742. || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "")
  131743. || ts.compareValues(type1.id, type2.id);
  131744. }
  131745. function getCalledExpression(scope, range, functionNameText) {
  131746. var functionReference = ts.createIdentifier(functionNameText);
  131747. if (ts.isClassLike(scope)) {
  131748. var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217
  131749. return ts.createPropertyAccess(lhs, functionReference);
  131750. }
  131751. else {
  131752. return functionReference;
  131753. }
  131754. }
  131755. function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) {
  131756. var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0;
  131757. if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
  131758. // already block, no declarations or writes to propagate back, no substitutions - can use node as is
  131759. return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined };
  131760. }
  131761. var returnValueProperty;
  131762. var ignoreReturns = false;
  131763. var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]);
  131764. // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions
  131765. if (hasWritesOrVariableDeclarations || substitutions.size) {
  131766. var rewrittenStatements = ts.visitNodes(statements, visitor).slice();
  131767. if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) {
  131768. // add return at the end to propagate writes back in case if control flow falls out of the function body
  131769. // it is ok to know that range has at least one return since it we only allow unconditional returns
  131770. var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
  131771. if (assignments.length === 1) {
  131772. rewrittenStatements.push(ts.createReturn(assignments[0].name));
  131773. }
  131774. else {
  131775. rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments)));
  131776. }
  131777. }
  131778. return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty };
  131779. }
  131780. else {
  131781. return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined };
  131782. }
  131783. function visitor(node) {
  131784. if (!ignoreReturns && node.kind === 235 /* ReturnStatement */ && hasWritesOrVariableDeclarations) {
  131785. var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
  131786. if (node.expression) {
  131787. if (!returnValueProperty) {
  131788. returnValueProperty = "__return";
  131789. }
  131790. assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor)));
  131791. }
  131792. if (assignments.length === 1) {
  131793. return ts.createReturn(assignments[0].name);
  131794. }
  131795. else {
  131796. return ts.createReturn(ts.createObjectLiteral(assignments));
  131797. }
  131798. }
  131799. else {
  131800. var oldIgnoreReturns = ignoreReturns;
  131801. ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node);
  131802. var substitution = substitutions.get(ts.getNodeId(node).toString());
  131803. var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
  131804. ignoreReturns = oldIgnoreReturns;
  131805. return result;
  131806. }
  131807. }
  131808. }
  131809. function transformConstantInitializer(initializer, substitutions) {
  131810. return substitutions.size
  131811. ? visitor(initializer)
  131812. : initializer;
  131813. function visitor(node) {
  131814. var substitution = substitutions.get(ts.getNodeId(node).toString());
  131815. return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
  131816. }
  131817. }
  131818. function getStatementsOrClassElements(scope) {
  131819. if (ts.isFunctionLikeDeclaration(scope)) {
  131820. var body = scope.body; // TODO: GH#18217
  131821. if (ts.isBlock(body)) {
  131822. return body.statements;
  131823. }
  131824. }
  131825. else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) {
  131826. return scope.statements;
  131827. }
  131828. else if (ts.isClassLike(scope)) {
  131829. return scope.members;
  131830. }
  131831. else {
  131832. ts.assertType(scope);
  131833. }
  131834. return ts.emptyArray;
  131835. }
  131836. /**
  131837. * If `scope` contains a function after `minPos`, then return the first such function.
  131838. * Otherwise, return `undefined`.
  131839. */
  131840. function getNodeToInsertFunctionBefore(minPos, scope) {
  131841. return ts.find(getStatementsOrClassElements(scope), function (child) {
  131842. return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child);
  131843. });
  131844. }
  131845. function getNodeToInsertPropertyBefore(maxPos, scope) {
  131846. var members = scope.members;
  131847. ts.Debug.assert(members.length > 0, "Found no members"); // There must be at least one child, since we extracted from one.
  131848. var prevMember;
  131849. var allProperties = true;
  131850. for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
  131851. var member = members_1[_i];
  131852. if (member.pos > maxPos) {
  131853. return prevMember || members[0];
  131854. }
  131855. if (allProperties && !ts.isPropertyDeclaration(member)) {
  131856. // If it is non-vacuously true that all preceding members are properties,
  131857. // insert before the current member (i.e. at the end of the list of properties).
  131858. if (prevMember !== undefined) {
  131859. return member;
  131860. }
  131861. allProperties = false;
  131862. }
  131863. prevMember = member;
  131864. }
  131865. if (prevMember === undefined)
  131866. return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember.
  131867. return prevMember;
  131868. }
  131869. function getNodeToInsertConstantBefore(node, scope) {
  131870. ts.Debug.assert(!ts.isClassLike(scope));
  131871. var prevScope;
  131872. for (var curr = node; curr !== scope; curr = curr.parent) {
  131873. if (isScope(curr)) {
  131874. prevScope = curr;
  131875. }
  131876. }
  131877. for (var curr = (prevScope || node).parent;; curr = curr.parent) {
  131878. if (isBlockLike(curr)) {
  131879. var prevStatement = void 0;
  131880. for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
  131881. var statement = _a[_i];
  131882. if (statement.pos > node.pos) {
  131883. break;
  131884. }
  131885. prevStatement = statement;
  131886. }
  131887. if (!prevStatement && ts.isCaseClause(curr)) {
  131888. // We must have been in the expression of the case clause.
  131889. ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement");
  131890. return curr.parent.parent;
  131891. }
  131892. // There must be at least one statement since we started in one.
  131893. return ts.Debug.assertDefined(prevStatement, "prevStatement failed to get set");
  131894. }
  131895. ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
  131896. }
  131897. }
  131898. function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
  131899. var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); });
  131900. var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); });
  131901. // TODO: GH#18217 `variableAssignments` not possibly undefined!
  131902. return variableAssignments === undefined
  131903. ? writeAssignments
  131904. : writeAssignments === undefined
  131905. ? variableAssignments
  131906. : variableAssignments.concat(writeAssignments);
  131907. }
  131908. function isReadonlyArray(v) {
  131909. return ts.isArray(v);
  131910. }
  131911. /**
  131912. * Produces a range that spans the entirety of nodes, given a selection
  131913. * that might start/end in the middle of nodes.
  131914. *
  131915. * For example, when the user makes a selection like this
  131916. * v---v
  131917. * var someThing = foo + bar;
  131918. * this returns ^-------^
  131919. */
  131920. function getEnclosingTextRange(targetRange, sourceFile) {
  131921. return isReadonlyArray(targetRange.range)
  131922. ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() }
  131923. : targetRange.range;
  131924. }
  131925. var Usage;
  131926. (function (Usage) {
  131927. // value should be passed to extracted method
  131928. Usage[Usage["Read"] = 1] = "Read";
  131929. // value should be passed to extracted method and propagated back
  131930. Usage[Usage["Write"] = 2] = "Write";
  131931. })(Usage || (Usage = {}));
  131932. function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) {
  131933. var allTypeParameterUsages = ts.createMap(); // Key is type ID
  131934. var usagesPerScope = [];
  131935. var substitutionsPerScope = [];
  131936. var functionErrorsPerScope = [];
  131937. var constantErrorsPerScope = [];
  131938. var visibleDeclarationsInExtractedRange = [];
  131939. var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
  131940. var exposedVariableDeclarations = [];
  131941. var firstExposedNonVariableDeclaration;
  131942. var expression = !isReadonlyArray(targetRange.range)
  131943. ? targetRange.range
  131944. : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
  131945. ? targetRange.range[0].expression
  131946. : undefined;
  131947. var expressionDiagnostic;
  131948. if (expression === undefined) {
  131949. var statements = targetRange.range;
  131950. var start = ts.first(statements).getStart();
  131951. var end = ts.last(statements).end;
  131952. expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected);
  131953. }
  131954. else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) {
  131955. expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType);
  131956. }
  131957. // initialize results
  131958. for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) {
  131959. var scope = scopes_1[_i];
  131960. usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() });
  131961. substitutionsPerScope.push(ts.createMap());
  131962. functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 244 /* FunctionDeclaration */
  131963. ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)]
  131964. : []);
  131965. var constantErrors = [];
  131966. if (expressionDiagnostic) {
  131967. constantErrors.push(expressionDiagnostic);
  131968. }
  131969. if (ts.isClassLike(scope) && ts.isInJSFile(scope)) {
  131970. constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
  131971. }
  131972. if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) {
  131973. // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this
  131974. constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
  131975. }
  131976. constantErrorsPerScope.push(constantErrors);
  131977. }
  131978. var seenUsages = ts.createMap();
  131979. var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range;
  131980. var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range;
  131981. var inGenericContext = isInGenericContext(unmodifiedNode);
  131982. collectUsages(target);
  131983. // Unfortunately, this code takes advantage of the knowledge that the generated method
  131984. // will use the contextual type of an expression as the return type of the extracted
  131985. // method (and will therefore "use" all the types involved).
  131986. if (inGenericContext && !isReadonlyArray(targetRange.range)) {
  131987. var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217
  131988. recordTypeParameterUsages(contextualType);
  131989. }
  131990. if (allTypeParameterUsages.size > 0) {
  131991. var seenTypeParameterUsages = ts.createMap(); // Key is type ID
  131992. var i_1 = 0;
  131993. for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) {
  131994. if (curr === scopes[i_1]) {
  131995. // Copy current contents of seenTypeParameterUsages into scope.
  131996. seenTypeParameterUsages.forEach(function (typeParameter, id) {
  131997. usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter);
  131998. });
  131999. i_1++;
  132000. }
  132001. // Note that we add the current node's type parameters *after* updating the corresponding scope.
  132002. if (ts.isDeclarationWithTypeParameters(curr)) {
  132003. for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
  132004. var typeParameterDecl = _b[_a];
  132005. var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
  132006. if (allTypeParameterUsages.has(typeParameter.id.toString())) {
  132007. seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter);
  132008. }
  132009. }
  132010. }
  132011. }
  132012. // If we didn't get through all the scopes, then there were some that weren't in our
  132013. // parent chain (impossible at time of writing). A conservative solution would be to
  132014. // copy allTypeParameterUsages into all remaining scopes.
  132015. ts.Debug.assert(i_1 === scopes.length, "Should have iterated all scopes");
  132016. }
  132017. // If there are any declarations in the extracted block that are used in the same enclosing
  132018. // lexical scope, we can't move the extraction "up" as those declarations will become unreachable
  132019. if (visibleDeclarationsInExtractedRange.length) {
  132020. var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent)
  132021. ? scopes[0]
  132022. : ts.getEnclosingBlockScopeContainer(scopes[0]);
  132023. ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
  132024. }
  132025. var _loop_16 = function (i) {
  132026. var scopeUsages = usagesPerScope[i];
  132027. // Special case: in the innermost scope, all usages are available.
  132028. // (The computed value reflects the value at the top-level of the scope, but the
  132029. // local will actually be declared at the same level as the extracted expression).
  132030. if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
  132031. var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
  132032. constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
  132033. }
  132034. var hasWrite = false;
  132035. var readonlyClassPropertyWrite;
  132036. usagesPerScope[i].usages.forEach(function (value) {
  132037. if (value.usage === 2 /* Write */) {
  132038. hasWrite = true;
  132039. if (value.symbol.flags & 106500 /* ClassMember */ &&
  132040. value.symbol.valueDeclaration &&
  132041. ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) {
  132042. readonlyClassPropertyWrite = value.symbol.valueDeclaration;
  132043. }
  132044. }
  132045. });
  132046. // If an expression was extracted, then there shouldn't have been any variable declarations.
  132047. ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted");
  132048. if (hasWrite && !isReadonlyArray(targetRange.range)) {
  132049. var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
  132050. functionErrorsPerScope[i].push(diag);
  132051. constantErrorsPerScope[i].push(diag);
  132052. }
  132053. else if (readonlyClassPropertyWrite && i > 0) {
  132054. var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
  132055. functionErrorsPerScope[i].push(diag);
  132056. constantErrorsPerScope[i].push(diag);
  132057. }
  132058. else if (firstExposedNonVariableDeclaration) {
  132059. var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
  132060. functionErrorsPerScope[i].push(diag);
  132061. constantErrorsPerScope[i].push(diag);
  132062. }
  132063. };
  132064. for (var i = 0; i < scopes.length; i++) {
  132065. _loop_16(i);
  132066. }
  132067. return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
  132068. function isInGenericContext(node) {
  132069. return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
  132070. }
  132071. function recordTypeParameterUsages(type) {
  132072. // PERF: This is potentially very expensive. `type` could be a library type with
  132073. // a lot of properties, each of which the walker will visit. Unfortunately, the
  132074. // solution isn't as trivial as filtering to user types because of (e.g.) Array.
  132075. var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); });
  132076. var visitedTypes = symbolWalker.walkType(type).visitedTypes;
  132077. for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) {
  132078. var visitedType = visitedTypes_1[_i];
  132079. if (visitedType.isTypeParameter()) {
  132080. allTypeParameterUsages.set(visitedType.id.toString(), visitedType);
  132081. }
  132082. }
  132083. }
  132084. function collectUsages(node, valueUsage) {
  132085. if (valueUsage === void 0) { valueUsage = 1 /* Read */; }
  132086. if (inGenericContext) {
  132087. var type = checker.getTypeAtLocation(node);
  132088. recordTypeParameterUsages(type);
  132089. }
  132090. if (ts.isDeclaration(node) && node.symbol) {
  132091. visibleDeclarationsInExtractedRange.push(node);
  132092. }
  132093. if (ts.isAssignmentExpression(node)) {
  132094. // use 'write' as default usage for values
  132095. collectUsages(node.left, 2 /* Write */);
  132096. collectUsages(node.right);
  132097. }
  132098. else if (ts.isUnaryExpressionWithWrite(node)) {
  132099. collectUsages(node.operand, 2 /* Write */);
  132100. }
  132101. else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
  132102. // use 'write' as default usage for values
  132103. ts.forEachChild(node, collectUsages);
  132104. }
  132105. else if (ts.isIdentifier(node)) {
  132106. if (!node.parent) {
  132107. return;
  132108. }
  132109. if (ts.isQualifiedName(node.parent) && node !== node.parent.left) {
  132110. return;
  132111. }
  132112. if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) {
  132113. return;
  132114. }
  132115. recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node));
  132116. }
  132117. else {
  132118. ts.forEachChild(node, collectUsages);
  132119. }
  132120. }
  132121. function recordUsage(n, usage, isTypeNode) {
  132122. var symbolId = recordUsagebySymbol(n, usage, isTypeNode);
  132123. if (symbolId) {
  132124. for (var i = 0; i < scopes.length; i++) {
  132125. // push substitution from map<symbolId, subst> to map<nodeId, subst> to simplify rewriting
  132126. var substitution = substitutionsPerScope[i].get(symbolId);
  132127. if (substitution) {
  132128. usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution);
  132129. }
  132130. }
  132131. }
  132132. }
  132133. function recordUsagebySymbol(identifier, usage, isTypeName) {
  132134. var symbol = getSymbolReferencedByIdentifier(identifier);
  132135. if (!symbol) {
  132136. // cannot find symbol - do nothing
  132137. return undefined;
  132138. }
  132139. var symbolId = ts.getSymbolId(symbol).toString();
  132140. var lastUsage = seenUsages.get(symbolId);
  132141. // there are two kinds of value usages
  132142. // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter
  132143. // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and
  132144. // returned as a return value
  132145. // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read'
  132146. // since all information is already recorded
  132147. if (lastUsage && lastUsage >= usage) {
  132148. return symbolId;
  132149. }
  132150. seenUsages.set(symbolId, usage);
  132151. if (lastUsage) {
  132152. // if we get here this means that we are trying to handle 'write' and 'read' was already processed
  132153. // walk scopes and update existing records.
  132154. for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) {
  132155. var perScope = usagesPerScope_1[_i];
  132156. var prevEntry = perScope.usages.get(identifier.text);
  132157. if (prevEntry) {
  132158. perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
  132159. }
  132160. }
  132161. return symbolId;
  132162. }
  132163. // find first declaration in this file
  132164. var decls = symbol.getDeclarations();
  132165. var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; });
  132166. if (!declInFile) {
  132167. return undefined;
  132168. }
  132169. if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) {
  132170. // declaration is located in range to be extracted - do nothing
  132171. return undefined;
  132172. }
  132173. if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) {
  132174. // this is write to a reference located outside of the target scope and range is extracted into generator
  132175. // currently this is unsupported scenario
  132176. var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
  132177. for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) {
  132178. var errors = functionErrorsPerScope_1[_a];
  132179. errors.push(diag);
  132180. }
  132181. for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) {
  132182. var errors = constantErrorsPerScope_1[_b];
  132183. errors.push(diag);
  132184. }
  132185. }
  132186. for (var i = 0; i < scopes.length; i++) {
  132187. var scope = scopes[i];
  132188. var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false);
  132189. if (resolvedSymbol === symbol) {
  132190. continue;
  132191. }
  132192. if (!substitutionsPerScope[i].has(symbolId)) {
  132193. var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName);
  132194. if (substitution) {
  132195. substitutionsPerScope[i].set(symbolId, substitution);
  132196. }
  132197. else if (isTypeName) {
  132198. // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument
  132199. // so there's no problem.
  132200. if (!(symbol.flags & 262144 /* TypeParameter */)) {
  132201. var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
  132202. functionErrorsPerScope[i].push(diag);
  132203. constantErrorsPerScope[i].push(diag);
  132204. }
  132205. }
  132206. else {
  132207. usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
  132208. }
  132209. }
  132210. }
  132211. return symbolId;
  132212. }
  132213. function checkForUsedDeclarations(node) {
  132214. // If this node is entirely within the original extraction range, we don't need to do anything.
  132215. if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) {
  132216. return;
  132217. }
  132218. // Otherwise check and recurse.
  132219. var sym = ts.isIdentifier(node)
  132220. ? getSymbolReferencedByIdentifier(node)
  132221. : checker.getSymbolAtLocation(node);
  132222. if (sym) {
  132223. var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; });
  132224. if (decl) {
  132225. if (ts.isVariableDeclaration(decl)) {
  132226. var idString = decl.symbol.id.toString();
  132227. if (!exposedVariableSymbolSet.has(idString)) {
  132228. exposedVariableDeclarations.push(decl);
  132229. exposedVariableSymbolSet.set(idString, true);
  132230. }
  132231. }
  132232. else {
  132233. // CONSIDER: this includes binding elements, which we could
  132234. // expose in the same way as variables.
  132235. firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
  132236. }
  132237. }
  132238. }
  132239. ts.forEachChild(node, checkForUsedDeclarations);
  132240. }
  132241. /**
  132242. * Return the symbol referenced by an identifier (even if it declares a different symbol).
  132243. */
  132244. function getSymbolReferencedByIdentifier(identifier) {
  132245. // If the identifier is both a property name and its value, we're only interested in its value
  132246. // (since the name is a declaration and will be included in the extracted range).
  132247. return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier
  132248. ? checker.getShorthandAssignmentValueSymbol(identifier.parent)
  132249. : checker.getSymbolAtLocation(identifier);
  132250. }
  132251. function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) {
  132252. if (!symbol) {
  132253. return undefined;
  132254. }
  132255. var decls = symbol.getDeclarations();
  132256. if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) {
  132257. return ts.createIdentifier(symbol.name);
  132258. }
  132259. var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode);
  132260. if (prefix === undefined) {
  132261. return undefined;
  132262. }
  132263. return isTypeNode
  132264. ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name))
  132265. : ts.createPropertyAccess(prefix, symbol.name);
  132266. }
  132267. }
  132268. /**
  132269. * Computes whether or not a node represents an expression in a position where it could
  132270. * be extracted.
  132271. * The isExpression() in utilities.ts returns some false positives we need to handle,
  132272. * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression
  132273. * in the sense of something that you could extract on
  132274. */
  132275. function isExtractableExpression(node) {
  132276. var parent = node.parent;
  132277. switch (parent.kind) {
  132278. case 284 /* EnumMember */:
  132279. return false;
  132280. }
  132281. switch (node.kind) {
  132282. case 10 /* StringLiteral */:
  132283. return parent.kind !== 254 /* ImportDeclaration */ &&
  132284. parent.kind !== 258 /* ImportSpecifier */;
  132285. case 213 /* SpreadElement */:
  132286. case 189 /* ObjectBindingPattern */:
  132287. case 191 /* BindingElement */:
  132288. return false;
  132289. case 75 /* Identifier */:
  132290. return parent.kind !== 191 /* BindingElement */ &&
  132291. parent.kind !== 258 /* ImportSpecifier */ &&
  132292. parent.kind !== 263 /* ExportSpecifier */;
  132293. }
  132294. return true;
  132295. }
  132296. function isBlockLike(node) {
  132297. switch (node.kind) {
  132298. case 223 /* Block */:
  132299. case 290 /* SourceFile */:
  132300. case 250 /* ModuleBlock */:
  132301. case 277 /* CaseClause */:
  132302. return true;
  132303. default:
  132304. return false;
  132305. }
  132306. }
  132307. })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
  132308. })(refactor = ts.refactor || (ts.refactor = {}));
  132309. })(ts || (ts = {}));
  132310. /* @internal */
  132311. var ts;
  132312. (function (ts) {
  132313. var refactor;
  132314. (function (refactor) {
  132315. var refactorName = "Extract type";
  132316. var extractToTypeAlias = "Extract to type alias";
  132317. var extractToInterface = "Extract to interface";
  132318. var extractToTypeDef = "Extract to typedef";
  132319. refactor.registerRefactor(refactorName, {
  132320. getAvailableActions: function (context) {
  132321. var info = getRangeToExtract(context);
  132322. if (!info)
  132323. return ts.emptyArray;
  132324. return [{
  132325. name: refactorName,
  132326. description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_type),
  132327. actions: info.isJS ? [{
  132328. name: extractToTypeDef, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_typedef)
  132329. }] : ts.append([{
  132330. name: extractToTypeAlias, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_type_alias)
  132331. }], info.typeElements && {
  132332. name: extractToInterface, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_interface)
  132333. })
  132334. }];
  132335. },
  132336. getEditsForAction: function (context, actionName) {
  132337. var file = context.file;
  132338. var info = ts.Debug.assertDefined(getRangeToExtract(context), "Expected to find a range to extract");
  132339. var name = ts.getUniqueName("NewType", file);
  132340. var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
  132341. switch (actionName) {
  132342. case extractToTypeAlias:
  132343. ts.Debug.assert(!info.isJS, "Invalid actionName/JS combo");
  132344. return doTypeAliasChange(changes, file, name, info);
  132345. case extractToTypeDef:
  132346. ts.Debug.assert(info.isJS, "Invalid actionName/JS combo");
  132347. return doTypedefChange(changes, file, name, info);
  132348. case extractToInterface:
  132349. ts.Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo");
  132350. return doInterfaceChange(changes, file, name, info);
  132351. default:
  132352. ts.Debug.fail("Unexpected action name");
  132353. }
  132354. });
  132355. var renameFilename = file.fileName;
  132356. var renameLocation = ts.getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ false);
  132357. return { edits: edits, renameFilename: renameFilename, renameLocation: renameLocation };
  132358. }
  132359. });
  132360. function getRangeToExtract(context) {
  132361. var file = context.file, startPosition = context.startPosition;
  132362. var isJS = ts.isSourceFileJS(file);
  132363. var current = ts.getTokenAtPosition(file, startPosition);
  132364. var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
  132365. var selection = ts.findAncestor(current, (function (node) { return node.parent && rangeContainsSkipTrivia(range, node, file) && !rangeContainsSkipTrivia(range, node.parent, file); }));
  132366. if (!selection || !ts.isTypeNode(selection))
  132367. return undefined;
  132368. var checker = context.program.getTypeChecker();
  132369. var firstStatement = ts.Debug.assertDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement");
  132370. var typeParameters = collectTypeParameters(checker, selection, firstStatement, file);
  132371. if (!typeParameters)
  132372. return undefined;
  132373. var typeElements = flattenTypeLiteralNodeReference(checker, selection);
  132374. return { isJS: isJS, selection: selection, firstStatement: firstStatement, typeParameters: typeParameters, typeElements: typeElements };
  132375. }
  132376. function flattenTypeLiteralNodeReference(checker, node) {
  132377. if (!node)
  132378. return undefined;
  132379. if (ts.isIntersectionTypeNode(node)) {
  132380. var result = [];
  132381. var seen_1 = ts.createMap();
  132382. for (var _i = 0, _a = node.types; _i < _a.length; _i++) {
  132383. var type = _a[_i];
  132384. var flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type);
  132385. if (!flattenedTypeMembers || !flattenedTypeMembers.every(function (type) { return type.name && ts.addToSeen(seen_1, ts.getNameFromPropertyName(type.name)); })) {
  132386. return undefined;
  132387. }
  132388. ts.addRange(result, flattenedTypeMembers);
  132389. }
  132390. return result;
  132391. }
  132392. else if (ts.isParenthesizedTypeNode(node)) {
  132393. return flattenTypeLiteralNodeReference(checker, node.type);
  132394. }
  132395. else if (ts.isTypeLiteralNode(node)) {
  132396. return node.members;
  132397. }
  132398. return undefined;
  132399. }
  132400. function rangeContainsSkipTrivia(r1, node, file) {
  132401. return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end);
  132402. }
  132403. function collectTypeParameters(checker, selection, statement, file) {
  132404. var result = [];
  132405. return visitor(selection) ? undefined : result;
  132406. function visitor(node) {
  132407. if (ts.isTypeReferenceNode(node)) {
  132408. if (ts.isIdentifier(node.typeName)) {
  132409. var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true);
  132410. if (symbol) {
  132411. var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration);
  132412. if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) {
  132413. result.push(declaration);
  132414. }
  132415. }
  132416. }
  132417. }
  132418. else if (ts.isInferTypeNode(node)) {
  132419. var conditionalTypeNode = ts.findAncestor(node, function (n) { return ts.isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file); });
  132420. if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) {
  132421. return true;
  132422. }
  132423. }
  132424. else if ((ts.isTypePredicateNode(node) || ts.isThisTypeNode(node))) {
  132425. var functionLikeNode = ts.findAncestor(node.parent, ts.isFunctionLike);
  132426. if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) {
  132427. return true;
  132428. }
  132429. }
  132430. else if (ts.isTypeQueryNode(node)) {
  132431. if (ts.isIdentifier(node.exprName)) {
  132432. var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false);
  132433. if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) {
  132434. return true;
  132435. }
  132436. }
  132437. else {
  132438. if (ts.isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) {
  132439. return true;
  132440. }
  132441. }
  132442. }
  132443. return ts.forEachChild(node, visitor);
  132444. }
  132445. }
  132446. function doTypeAliasChange(changes, file, name, info) {
  132447. var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters;
  132448. var newTypeNode = ts.createTypeAliasDeclaration(
  132449. /* decorators */ undefined,
  132450. /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.updateTypeParameterDeclaration(id, id.name, id.constraint, /* defaultType */ undefined); }), selection);
  132451. changes.insertNodeBefore(file, firstStatement, newTypeNode, /* blankLineBetween */ true);
  132452. changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
  132453. }
  132454. function doInterfaceChange(changes, file, name, info) {
  132455. var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements;
  132456. var newTypeNode = ts.createInterfaceDeclaration(
  132457. /* decorators */ undefined,
  132458. /* modifiers */ undefined, name, typeParameters,
  132459. /* heritageClauses */ undefined, typeElements);
  132460. changes.insertNodeBefore(file, firstStatement, newTypeNode, /* blankLineBetween */ true);
  132461. changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
  132462. }
  132463. function doTypedefChange(changes, file, name, info) {
  132464. var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters;
  132465. var node = ts.createNode(321 /* JSDocTypedefTag */);
  132466. node.tagName = ts.createIdentifier("typedef"); // TODO: jsdoc factory https://github.com/Microsoft/TypeScript/pull/29539
  132467. node.fullName = ts.createIdentifier(name);
  132468. node.name = node.fullName;
  132469. node.typeExpression = ts.createJSDocTypeExpression(selection);
  132470. var templates = [];
  132471. ts.forEach(typeParameters, function (typeParameter) {
  132472. var constraint = ts.getEffectiveConstraintOfTypeParameter(typeParameter);
  132473. var template = ts.createNode(320 /* JSDocTemplateTag */);
  132474. template.tagName = ts.createIdentifier("template");
  132475. template.constraint = constraint && ts.cast(constraint, ts.isJSDocTypeExpression);
  132476. var parameter = ts.createNode(155 /* TypeParameter */);
  132477. parameter.name = typeParameter.name;
  132478. template.typeParameters = ts.createNodeArray([parameter]);
  132479. templates.push(template);
  132480. });
  132481. changes.insertNodeBefore(file, firstStatement, ts.createJSDocComment(/* comment */ undefined, ts.createNodeArray(ts.concatenate(templates, [node]))), /* blankLineBetween */ true);
  132482. changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
  132483. }
  132484. })(refactor = ts.refactor || (ts.refactor = {}));
  132485. })(ts || (ts = {}));
  132486. /* @internal */
  132487. var ts;
  132488. (function (ts) {
  132489. var refactor;
  132490. (function (refactor) {
  132491. var generateGetAccessorAndSetAccessor;
  132492. (function (generateGetAccessorAndSetAccessor) {
  132493. var actionName = "Generate 'get' and 'set' accessors";
  132494. var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message;
  132495. refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
  132496. function getAvailableActions(context) {
  132497. if (!getConvertibleFieldAtPosition(context))
  132498. return ts.emptyArray;
  132499. return [{
  132500. name: actionName,
  132501. description: actionDescription,
  132502. actions: [
  132503. {
  132504. name: actionName,
  132505. description: actionDescription
  132506. }
  132507. ]
  132508. }];
  132509. }
  132510. function getEditsForAction(context, _actionName) {
  132511. var file = context.file;
  132512. var fieldInfo = getConvertibleFieldAtPosition(context);
  132513. if (!fieldInfo)
  132514. return undefined;
  132515. var isJS = ts.isSourceFileJS(file);
  132516. var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
  132517. var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor;
  132518. ts.suppressLeadingAndTrailingTrivia(fieldName);
  132519. ts.suppressLeadingAndTrailingTrivia(declaration);
  132520. ts.suppressLeadingAndTrailingTrivia(container);
  132521. var isInClassLike = ts.isClassLike(container);
  132522. // avoid Readonly modifier because it will convert to get accessor
  132523. var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
  132524. var accessorModifiers = isInClassLike
  132525. ? !modifierFlags || modifierFlags & 8 /* Private */
  132526. ? getModifiers(isJS, isStatic, 119 /* PublicKeyword */)
  132527. : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
  132528. : undefined;
  132529. var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 117 /* PrivateKeyword */) : undefined;
  132530. updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
  132531. var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
  132532. ts.suppressLeadingAndTrailingTrivia(getAccessor);
  132533. insertAccessor(changeTracker, file, getAccessor, declaration, container);
  132534. if (isReadonly) {
  132535. // readonly modifier only existed in classLikeDeclaration
  132536. var constructor = ts.getFirstConstructorWithBody(container);
  132537. if (constructor) {
  132538. updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
  132539. }
  132540. }
  132541. else {
  132542. var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
  132543. ts.suppressLeadingAndTrailingTrivia(setAccessor);
  132544. insertAccessor(changeTracker, file, setAccessor, declaration, container);
  132545. }
  132546. var edits = changeTracker.getChanges();
  132547. var renameFilename = file.fileName;
  132548. var nameNeedRename = renameAccessor ? accessorName : fieldName;
  132549. var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
  132550. var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
  132551. return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
  132552. }
  132553. function isConvertibleName(name) {
  132554. return ts.isIdentifier(name) || ts.isStringLiteral(name);
  132555. }
  132556. function isAcceptedDeclaration(node) {
  132557. return ts.isParameterPropertyDeclaration(node, node.parent) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node);
  132558. }
  132559. function createPropertyName(name, originalName) {
  132560. return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name);
  132561. }
  132562. function createAccessorAccessExpression(fieldName, isStatic, container) {
  132563. var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217
  132564. return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName));
  132565. }
  132566. function getModifiers(isJS, isStatic, accessModifier) {
  132567. var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(120 /* StaticKeyword */) : undefined);
  132568. return modifiers && ts.createNodeArray(modifiers);
  132569. }
  132570. function startsWithUnderscore(name) {
  132571. return name.charCodeAt(0) === 95 /* _ */;
  132572. }
  132573. function getConvertibleFieldAtPosition(context) {
  132574. var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition;
  132575. var node = ts.getTokenAtPosition(file, startPosition);
  132576. var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
  132577. // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
  132578. var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
  132579. if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217
  132580. || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
  132581. return undefined;
  132582. var name = declaration.name.text;
  132583. var startWithUnderscore = startsWithUnderscore(name);
  132584. var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name);
  132585. var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name);
  132586. return {
  132587. isStatic: ts.hasStaticModifier(declaration),
  132588. isReadonly: ts.hasReadonlyModifier(declaration),
  132589. type: ts.getTypeAnnotationNode(declaration),
  132590. container: declaration.kind === 156 /* Parameter */ ? declaration.parent.parent : declaration.parent,
  132591. originalName: declaration.name.text,
  132592. declaration: declaration,
  132593. fieldName: fieldName,
  132594. accessorName: accessorName,
  132595. renameAccessor: startWithUnderscore
  132596. };
  132597. }
  132598. function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
  132599. return ts.createGetAccessor(
  132600. /*decorators*/ undefined, modifiers, accessorName,
  132601. /*parameters*/ undefined, // TODO: GH#18217
  132602. type, ts.createBlock([
  132603. ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container))
  132604. ], /*multiLine*/ true));
  132605. }
  132606. function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
  132607. return ts.createSetAccessor(
  132608. /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter(
  132609. /*decorators*/ undefined,
  132610. /*modifiers*/ undefined,
  132611. /*dotDotDotToken*/ undefined, ts.createIdentifier("value"),
  132612. /*questionToken*/ undefined, type)], ts.createBlock([
  132613. ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value")))
  132614. ], /*multiLine*/ true));
  132615. }
  132616. function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
  132617. var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
  132618. changeTracker.replaceNode(file, declaration, property);
  132619. }
  132620. function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
  132621. var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
  132622. changeTracker.replacePropertyAssignment(file, declaration, assignment);
  132623. }
  132624. function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
  132625. if (ts.isPropertyDeclaration(declaration)) {
  132626. updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
  132627. }
  132628. else if (ts.isPropertyAssignment(declaration)) {
  132629. updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
  132630. }
  132631. else {
  132632. changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
  132633. }
  132634. }
  132635. function insertAccessor(changeTracker, file, accessor, declaration, container) {
  132636. ts.isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertNodeAtClassStart(file, container, accessor) :
  132637. ts.isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) :
  132638. changeTracker.insertNodeAfter(file, declaration, accessor);
  132639. }
  132640. function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
  132641. if (!constructor.body)
  132642. return;
  132643. constructor.body.forEachChild(function recur(node) {
  132644. if (ts.isElementAccessExpression(node) &&
  132645. node.expression.kind === 104 /* ThisKeyword */ &&
  132646. ts.isStringLiteral(node.argumentExpression) &&
  132647. node.argumentExpression.text === originalName &&
  132648. ts.isWriteAccess(node)) {
  132649. changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
  132650. }
  132651. if (ts.isPropertyAccessExpression(node) && node.expression.kind === 104 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
  132652. changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
  132653. }
  132654. if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
  132655. node.forEachChild(recur);
  132656. }
  132657. });
  132658. }
  132659. })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
  132660. })(refactor = ts.refactor || (ts.refactor = {}));
  132661. })(ts || (ts = {}));
  132662. /* @internal */
  132663. var ts;
  132664. (function (ts) {
  132665. var refactor;
  132666. (function (refactor) {
  132667. var refactorName = "Move to a new file";
  132668. refactor.registerRefactor(refactorName, {
  132669. getAvailableActions: function (context) {
  132670. if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
  132671. return ts.emptyArray;
  132672. var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
  132673. return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
  132674. },
  132675. getEditsForAction: function (context, actionName) {
  132676. ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked");
  132677. var statements = ts.Debug.assertDefined(getStatementsToMove(context));
  132678. var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); });
  132679. return { edits: edits, renameFilename: undefined, renameLocation: undefined };
  132680. }
  132681. });
  132682. function getRangeToMove(context) {
  132683. var file = context.file;
  132684. var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
  132685. var statements = file.statements;
  132686. var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
  132687. if (startNodeIndex === -1)
  132688. return undefined;
  132689. var startStatement = statements[startNodeIndex];
  132690. if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) {
  132691. return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] };
  132692. }
  132693. // Can't only partially include the start node or be partially into the next node
  132694. if (range.pos > startStatement.getStart(file))
  132695. return undefined;
  132696. var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
  132697. // Can't be partially into the next node
  132698. if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
  132699. return undefined;
  132700. return {
  132701. toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex),
  132702. afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex],
  132703. };
  132704. }
  132705. function doChange(oldFile, program, toMove, changes, host, preferences) {
  132706. var checker = program.getTypeChecker();
  132707. var usage = getUsageInfo(oldFile, toMove.all, checker);
  132708. var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
  132709. var extension = ts.extensionFromPath(oldFile.fileName);
  132710. var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
  132711. var newFileNameWithExtension = newModuleName + extension;
  132712. // If previous file was global, this is easy.
  132713. changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences));
  132714. addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
  132715. }
  132716. // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file.
  132717. function getStatementsToMove(context) {
  132718. var rangeToMove = getRangeToMove(context);
  132719. if (rangeToMove === undefined)
  132720. return undefined;
  132721. var all = [];
  132722. var ranges = [];
  132723. var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast;
  132724. ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) {
  132725. for (var i = start; i < afterEndIndex; i++)
  132726. all.push(toMove[i]);
  132727. ranges.push({ first: toMove[start], afterLast: afterLast });
  132728. });
  132729. return all.length === 0 ? undefined : { all: all, ranges: ranges };
  132730. }
  132731. function isPureImport(node) {
  132732. switch (node.kind) {
  132733. case 254 /* ImportDeclaration */:
  132734. return true;
  132735. case 253 /* ImportEqualsDeclaration */:
  132736. return !ts.hasModifier(node, 1 /* Export */);
  132737. case 225 /* VariableStatement */:
  132738. return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
  132739. default:
  132740. return false;
  132741. }
  132742. }
  132743. function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
  132744. var cfg = program.getCompilerOptions().configFile;
  132745. if (!cfg)
  132746. return;
  132747. var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
  132748. var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
  132749. var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
  132750. var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
  132751. return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
  132752. });
  132753. if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
  132754. changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
  132755. }
  132756. }
  132757. function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) {
  132758. var checker = program.getTypeChecker();
  132759. if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
  132760. deleteMovedStatements(oldFile, toMove.ranges, changes);
  132761. return toMove.all;
  132762. }
  132763. var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
  132764. var quotePreference = ts.getQuotePreference(oldFile, preferences);
  132765. var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference);
  132766. if (importsFromNewFile) {
  132767. ts.insertImport(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true);
  132768. }
  132769. deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
  132770. deleteMovedStatements(oldFile, toMove.ranges, changes);
  132771. updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
  132772. return __spreadArrays(getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference), addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
  132773. }
  132774. function deleteMovedStatements(sourceFile, moved, changes) {
  132775. for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
  132776. var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast;
  132777. changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast);
  132778. }
  132779. }
  132780. function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
  132781. for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
  132782. var statement = _a[_i];
  132783. if (ts.contains(toMove, statement))
  132784. continue;
  132785. forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
  132786. }
  132787. }
  132788. function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
  132789. var checker = program.getTypeChecker();
  132790. var _loop_17 = function (sourceFile) {
  132791. if (sourceFile === oldFile)
  132792. return "continue";
  132793. var _loop_18 = function (statement) {
  132794. forEachImportInStatement(statement, function (importNode) {
  132795. if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
  132796. return;
  132797. var shouldMove = function (name) {
  132798. var symbol = ts.isBindingElement(name.parent)
  132799. ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
  132800. : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217
  132801. return !!symbol && movedSymbols.has(symbol);
  132802. };
  132803. deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
  132804. var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
  132805. var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
  132806. if (newImportDeclaration)
  132807. changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
  132808. var ns = getNamespaceLikeImport(importNode);
  132809. if (ns)
  132810. updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode);
  132811. });
  132812. };
  132813. for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
  132814. var statement = _a[_i];
  132815. _loop_18(statement);
  132816. }
  132817. };
  132818. for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
  132819. var sourceFile = _a[_i];
  132820. _loop_17(sourceFile);
  132821. }
  132822. }
  132823. function getNamespaceLikeImport(node) {
  132824. switch (node.kind) {
  132825. case 254 /* ImportDeclaration */:
  132826. return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 256 /* NamespaceImport */ ?
  132827. node.importClause.namedBindings.name : undefined;
  132828. case 253 /* ImportEqualsDeclaration */:
  132829. return node.name;
  132830. case 242 /* VariableDeclaration */:
  132831. return ts.tryCast(node.name, ts.isIdentifier);
  132832. default:
  132833. return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind);
  132834. }
  132835. }
  132836. function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
  132837. var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 99 /* ESNext */);
  132838. var needUniqueName = false;
  132839. var toChange = [];
  132840. ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
  132841. if (!ts.isPropertyAccessExpression(ref.parent))
  132842. return;
  132843. needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true);
  132844. if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) {
  132845. toChange.push(ref);
  132846. }
  132847. });
  132848. if (toChange.length) {
  132849. var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName;
  132850. for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) {
  132851. var ref = toChange_1[_i];
  132852. changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName));
  132853. }
  132854. changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier));
  132855. }
  132856. }
  132857. function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) {
  132858. var newNamespaceId = ts.createIdentifier(newNamespaceName);
  132859. var newModuleString = ts.createLiteral(newModuleSpecifier);
  132860. switch (node.kind) {
  132861. case 254 /* ImportDeclaration */:
  132862. return ts.createImportDeclaration(
  132863. /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString);
  132864. case 253 /* ImportEqualsDeclaration */:
  132865. return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString));
  132866. case 242 /* VariableDeclaration */:
  132867. return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString));
  132868. default:
  132869. return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind);
  132870. }
  132871. }
  132872. function moduleSpecifierFromImport(i) {
  132873. return (i.kind === 254 /* ImportDeclaration */ ? i.moduleSpecifier
  132874. : i.kind === 253 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
  132875. : i.initializer.arguments[0]);
  132876. }
  132877. function forEachImportInStatement(statement, cb) {
  132878. if (ts.isImportDeclaration(statement)) {
  132879. if (ts.isStringLiteral(statement.moduleSpecifier))
  132880. cb(statement);
  132881. }
  132882. else if (ts.isImportEqualsDeclaration(statement)) {
  132883. if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
  132884. cb(statement);
  132885. }
  132886. }
  132887. else if (ts.isVariableStatement(statement)) {
  132888. for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
  132889. var decl = _a[_i];
  132890. if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
  132891. cb(decl);
  132892. }
  132893. }
  132894. }
  132895. }
  132896. function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) {
  132897. var defaultImport;
  132898. var imports = [];
  132899. newFileNeedExport.forEach(function (symbol) {
  132900. if (symbol.escapedName === "default" /* Default */) {
  132901. defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217
  132902. }
  132903. else {
  132904. imports.push(symbol.name);
  132905. }
  132906. });
  132907. return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference);
  132908. }
  132909. function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) {
  132910. path = ts.ensurePathIsNonModuleName(path);
  132911. if (useEs6Imports) {
  132912. var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
  132913. return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference);
  132914. }
  132915. else {
  132916. ts.Debug.assert(!defaultImport, "No default import should exist"); // If there's a default export, it should have been an es6 module.
  132917. var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
  132918. return bindingElements.length
  132919. ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
  132920. : undefined;
  132921. }
  132922. }
  132923. function makeVariableStatement(name, type, initializer, flags) {
  132924. if (flags === void 0) { flags = 2 /* Const */; }
  132925. return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
  132926. }
  132927. function createRequireCall(moduleSpecifier) {
  132928. return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
  132929. }
  132930. function addExports(sourceFile, toMove, needExport, useEs6Exports) {
  132931. return ts.flatMap(toMove, function (statement) {
  132932. if (isTopLevelDeclarationStatement(statement) &&
  132933. !isExported(sourceFile, statement, useEs6Exports) &&
  132934. forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
  132935. var exports = addExport(statement, useEs6Exports);
  132936. if (exports)
  132937. return exports;
  132938. }
  132939. return statement;
  132940. });
  132941. }
  132942. function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
  132943. switch (importDecl.kind) {
  132944. case 254 /* ImportDeclaration */:
  132945. deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
  132946. break;
  132947. case 253 /* ImportEqualsDeclaration */:
  132948. if (isUnused(importDecl.name)) {
  132949. changes.delete(sourceFile, importDecl);
  132950. }
  132951. break;
  132952. case 242 /* VariableDeclaration */:
  132953. deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
  132954. break;
  132955. default:
  132956. ts.Debug.assertNever(importDecl, "Unexpected import decl kind " + importDecl.kind);
  132957. }
  132958. }
  132959. function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
  132960. if (!importDecl.importClause)
  132961. return;
  132962. var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
  132963. var defaultUnused = !name || isUnused(name);
  132964. var namedBindingsUnused = !namedBindings ||
  132965. (namedBindings.kind === 256 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); }));
  132966. if (defaultUnused && namedBindingsUnused) {
  132967. changes.delete(sourceFile, importDecl);
  132968. }
  132969. else {
  132970. if (name && defaultUnused) {
  132971. changes.delete(sourceFile, name);
  132972. }
  132973. if (namedBindings) {
  132974. if (namedBindingsUnused) {
  132975. changes.replaceNode(sourceFile, importDecl.importClause, ts.updateImportClause(importDecl.importClause, name, /*namedBindings*/ undefined, importDecl.importClause.isTypeOnly));
  132976. }
  132977. else if (namedBindings.kind === 257 /* NamedImports */) {
  132978. for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
  132979. var element = _b[_i];
  132980. if (isUnused(element.name))
  132981. changes.delete(sourceFile, element);
  132982. }
  132983. }
  132984. }
  132985. }
  132986. }
  132987. function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
  132988. var name = varDecl.name;
  132989. switch (name.kind) {
  132990. case 75 /* Identifier */:
  132991. if (isUnused(name)) {
  132992. changes.delete(sourceFile, name);
  132993. }
  132994. break;
  132995. case 190 /* ArrayBindingPattern */:
  132996. break;
  132997. case 189 /* ObjectBindingPattern */:
  132998. if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
  132999. changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
  133000. }
  133001. else {
  133002. for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
  133003. var element = _a[_i];
  133004. if (ts.isIdentifier(element.name) && isUnused(element.name)) {
  133005. changes.delete(sourceFile, element.name);
  133006. }
  133007. }
  133008. }
  133009. break;
  133010. }
  133011. }
  133012. function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) {
  133013. var copiedOldImports = [];
  133014. for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
  133015. var oldStatement = _a[_i];
  133016. forEachImportInStatement(oldStatement, function (i) {
  133017. ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
  133018. });
  133019. }
  133020. // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
  133021. var oldFileDefault;
  133022. var oldFileNamedImports = [];
  133023. var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
  133024. newFileImportsFromOldFile.forEach(function (symbol) {
  133025. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  133026. var decl = _a[_i];
  133027. if (!isTopLevelDeclaration(decl))
  133028. continue;
  133029. var name = nameOfTopLevelDeclaration(decl);
  133030. if (!name)
  133031. continue;
  133032. var top = getTopLevelDeclarationStatement(decl);
  133033. if (markSeenTop(top)) {
  133034. addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
  133035. }
  133036. if (ts.hasModifier(decl, 512 /* Default */)) {
  133037. oldFileDefault = name;
  133038. }
  133039. else {
  133040. oldFileNamedImports.push(name.text);
  133041. }
  133042. }
  133043. });
  133044. ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference));
  133045. return copiedOldImports;
  133046. }
  133047. function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
  133048. var newModuleName = moduleName;
  133049. for (var i = 1;; i++) {
  133050. var name = ts.combinePaths(inDirectory, newModuleName + extension);
  133051. if (!host.fileExists(name))
  133052. return newModuleName; // TODO: GH#18217
  133053. newModuleName = moduleName + "." + i;
  133054. }
  133055. }
  133056. function getNewModuleName(movedSymbols) {
  133057. return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
  133058. }
  133059. function getUsageInfo(oldFile, toMove, checker) {
  133060. var movedSymbols = new SymbolSet();
  133061. var oldImportsNeededByNewFile = new SymbolSet();
  133062. var newFileImportsFromOldFile = new SymbolSet();
  133063. var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
  133064. var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
  133065. if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
  133066. oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
  133067. }
  133068. for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
  133069. var statement = toMove_1[_i];
  133070. forEachTopLevelDeclaration(statement, function (decl) {
  133071. movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
  133072. });
  133073. }
  133074. for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
  133075. var statement = toMove_2[_a];
  133076. forEachReference(statement, checker, function (symbol) {
  133077. if (!symbol.declarations)
  133078. return;
  133079. for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
  133080. var decl = _a[_i];
  133081. if (isInImport(decl)) {
  133082. oldImportsNeededByNewFile.add(symbol);
  133083. }
  133084. else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) {
  133085. newFileImportsFromOldFile.add(symbol);
  133086. }
  133087. }
  133088. });
  133089. }
  133090. var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
  133091. var oldFileImportsFromNewFile = new SymbolSet();
  133092. for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
  133093. var statement = _c[_b];
  133094. if (ts.contains(toMove, statement))
  133095. continue;
  133096. // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
  133097. if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
  133098. unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
  133099. }
  133100. forEachReference(statement, checker, function (symbol) {
  133101. if (movedSymbols.has(symbol))
  133102. oldFileImportsFromNewFile.add(symbol);
  133103. unusedImportsFromOldFile.delete(symbol);
  133104. });
  133105. }
  133106. return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
  133107. function getJsxNamespaceSymbol(containsJsx) {
  133108. if (containsJsx === undefined) {
  133109. return undefined;
  133110. }
  133111. var jsxNamespace = checker.getJsxNamespace(containsJsx);
  133112. // Strictly speaking, this could resolve to a symbol other than the JSX namespace.
  133113. // This will produce erroneous output (probably, an incorrectly copied import) but
  133114. // is expected to be very rare and easily reversible.
  133115. var jsxNamespaceSymbol = checker.resolveName(jsxNamespace, containsJsx, 1920 /* Namespace */, /*excludeGlobals*/ true);
  133116. return !!jsxNamespaceSymbol && ts.some(jsxNamespaceSymbol.declarations, isInImport)
  133117. ? jsxNamespaceSymbol
  133118. : undefined;
  133119. }
  133120. }
  133121. // Below should all be utilities
  133122. function isInImport(decl) {
  133123. switch (decl.kind) {
  133124. case 253 /* ImportEqualsDeclaration */:
  133125. case 258 /* ImportSpecifier */:
  133126. case 255 /* ImportClause */:
  133127. return true;
  133128. case 242 /* VariableDeclaration */:
  133129. return isVariableDeclarationInImport(decl);
  133130. case 191 /* BindingElement */:
  133131. return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
  133132. default:
  133133. return false;
  133134. }
  133135. }
  133136. function isVariableDeclarationInImport(decl) {
  133137. return ts.isSourceFile(decl.parent.parent.parent) &&
  133138. !!decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
  133139. }
  133140. function filterImport(i, moduleSpecifier, keep) {
  133141. switch (i.kind) {
  133142. case 254 /* ImportDeclaration */: {
  133143. var clause = i.importClause;
  133144. if (!clause)
  133145. return undefined;
  133146. var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
  133147. var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
  133148. return defaultImport || namedBindings
  133149. ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
  133150. : undefined;
  133151. }
  133152. case 253 /* ImportEqualsDeclaration */:
  133153. return keep(i.name) ? i : undefined;
  133154. case 242 /* VariableDeclaration */: {
  133155. var name = filterBindingName(i.name, keep);
  133156. return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
  133157. }
  133158. default:
  133159. return ts.Debug.assertNever(i, "Unexpected import kind " + i.kind);
  133160. }
  133161. }
  133162. function filterNamedBindings(namedBindings, keep) {
  133163. if (namedBindings.kind === 256 /* NamespaceImport */) {
  133164. return keep(namedBindings.name) ? namedBindings : undefined;
  133165. }
  133166. else {
  133167. var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
  133168. return newElements.length ? ts.createNamedImports(newElements) : undefined;
  133169. }
  133170. }
  133171. function filterBindingName(name, keep) {
  133172. switch (name.kind) {
  133173. case 75 /* Identifier */:
  133174. return keep(name) ? name : undefined;
  133175. case 190 /* ArrayBindingPattern */:
  133176. return name;
  133177. case 189 /* ObjectBindingPattern */: {
  133178. // We can't handle nested destructurings or property names well here, so just copy them all.
  133179. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
  133180. return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
  133181. }
  133182. }
  133183. }
  133184. function forEachReference(node, checker, onReference) {
  133185. node.forEachChild(function cb(node) {
  133186. if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
  133187. var sym = checker.getSymbolAtLocation(node);
  133188. if (sym)
  133189. onReference(sym);
  133190. }
  133191. else {
  133192. node.forEachChild(cb);
  133193. }
  133194. });
  133195. }
  133196. var SymbolSet = /** @class */ (function () {
  133197. function SymbolSet() {
  133198. this.map = ts.createMap();
  133199. }
  133200. SymbolSet.prototype.add = function (symbol) {
  133201. this.map.set(String(ts.getSymbolId(symbol)), symbol);
  133202. };
  133203. SymbolSet.prototype.has = function (symbol) {
  133204. return this.map.has(String(ts.getSymbolId(symbol)));
  133205. };
  133206. SymbolSet.prototype.delete = function (symbol) {
  133207. this.map.delete(String(ts.getSymbolId(symbol)));
  133208. };
  133209. SymbolSet.prototype.forEach = function (cb) {
  133210. this.map.forEach(cb);
  133211. };
  133212. SymbolSet.prototype.forEachEntry = function (cb) {
  133213. return ts.forEachEntry(this.map, cb);
  133214. };
  133215. SymbolSet.prototype.clone = function () {
  133216. var clone = new SymbolSet();
  133217. ts.copyEntries(this.map, clone.map);
  133218. return clone;
  133219. };
  133220. return SymbolSet;
  133221. }());
  133222. function isTopLevelDeclaration(node) {
  133223. return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
  133224. }
  133225. function sourceFileOfTopLevelDeclaration(node) {
  133226. return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent;
  133227. }
  133228. function isTopLevelDeclarationStatement(node) {
  133229. ts.Debug.assert(ts.isSourceFile(node.parent), "Node parent should be a SourceFile");
  133230. return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
  133231. }
  133232. function isNonVariableTopLevelDeclaration(node) {
  133233. switch (node.kind) {
  133234. case 244 /* FunctionDeclaration */:
  133235. case 245 /* ClassDeclaration */:
  133236. case 249 /* ModuleDeclaration */:
  133237. case 248 /* EnumDeclaration */:
  133238. case 247 /* TypeAliasDeclaration */:
  133239. case 246 /* InterfaceDeclaration */:
  133240. case 253 /* ImportEqualsDeclaration */:
  133241. return true;
  133242. default:
  133243. return false;
  133244. }
  133245. }
  133246. function forEachTopLevelDeclaration(statement, cb) {
  133247. switch (statement.kind) {
  133248. case 244 /* FunctionDeclaration */:
  133249. case 245 /* ClassDeclaration */:
  133250. case 249 /* ModuleDeclaration */:
  133251. case 248 /* EnumDeclaration */:
  133252. case 247 /* TypeAliasDeclaration */:
  133253. case 246 /* InterfaceDeclaration */:
  133254. case 253 /* ImportEqualsDeclaration */:
  133255. return cb(statement);
  133256. case 225 /* VariableStatement */:
  133257. return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); });
  133258. case 226 /* ExpressionStatement */: {
  133259. var expression = statement.expression;
  133260. return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */
  133261. ? cb(statement)
  133262. : undefined;
  133263. }
  133264. }
  133265. }
  133266. function forEachTopLevelDeclarationInBindingName(name, cb) {
  133267. switch (name.kind) {
  133268. case 75 /* Identifier */:
  133269. return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); }));
  133270. case 190 /* ArrayBindingPattern */:
  133271. case 189 /* ObjectBindingPattern */:
  133272. return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); });
  133273. default:
  133274. return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind);
  133275. }
  133276. }
  133277. function nameOfTopLevelDeclaration(d) {
  133278. return ts.isExpressionStatement(d) ? ts.tryCast(d.expression.left.name, ts.isIdentifier) : ts.tryCast(d.name, ts.isIdentifier);
  133279. }
  133280. function getTopLevelDeclarationStatement(d) {
  133281. switch (d.kind) {
  133282. case 242 /* VariableDeclaration */:
  133283. return d.parent.parent;
  133284. case 191 /* BindingElement */:
  133285. return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); }));
  133286. default:
  133287. return d;
  133288. }
  133289. }
  133290. function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
  133291. if (isExported(sourceFile, decl, useEs6Exports))
  133292. return;
  133293. if (useEs6Exports) {
  133294. if (!ts.isExpressionStatement(decl))
  133295. changes.insertExportModifier(sourceFile, decl);
  133296. }
  133297. else {
  133298. var names = getNamesToExportInCommonJS(decl);
  133299. if (names.length !== 0)
  133300. changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
  133301. }
  133302. }
  133303. function isExported(sourceFile, decl, useEs6Exports) {
  133304. if (useEs6Exports) {
  133305. return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
  133306. }
  133307. else {
  133308. return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
  133309. }
  133310. }
  133311. function addExport(decl, useEs6Exports) {
  133312. return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
  133313. }
  133314. function addEs6Export(d) {
  133315. var modifiers = ts.concatenate([ts.createModifier(89 /* ExportKeyword */)], d.modifiers);
  133316. switch (d.kind) {
  133317. case 244 /* FunctionDeclaration */:
  133318. return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
  133319. case 245 /* ClassDeclaration */:
  133320. return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
  133321. case 225 /* VariableStatement */:
  133322. return ts.updateVariableStatement(d, modifiers, d.declarationList);
  133323. case 249 /* ModuleDeclaration */:
  133324. return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
  133325. case 248 /* EnumDeclaration */:
  133326. return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
  133327. case 247 /* TypeAliasDeclaration */:
  133328. return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
  133329. case 246 /* InterfaceDeclaration */:
  133330. return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
  133331. case 253 /* ImportEqualsDeclaration */:
  133332. return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
  133333. case 226 /* ExpressionStatement */:
  133334. return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
  133335. default:
  133336. return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind);
  133337. }
  133338. }
  133339. function addCommonjsExport(decl) {
  133340. return __spreadArrays([decl], getNamesToExportInCommonJS(decl).map(createExportAssignment));
  133341. }
  133342. function getNamesToExportInCommonJS(decl) {
  133343. switch (decl.kind) {
  133344. case 244 /* FunctionDeclaration */:
  133345. case 245 /* ClassDeclaration */:
  133346. return [decl.name.text]; // TODO: GH#18217
  133347. case 225 /* VariableStatement */:
  133348. return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
  133349. case 249 /* ModuleDeclaration */:
  133350. case 248 /* EnumDeclaration */:
  133351. case 247 /* TypeAliasDeclaration */:
  133352. case 246 /* InterfaceDeclaration */:
  133353. case 253 /* ImportEqualsDeclaration */:
  133354. return ts.emptyArray;
  133355. case 226 /* ExpressionStatement */:
  133356. return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...`
  133357. default:
  133358. return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind);
  133359. }
  133360. }
  133361. /** Creates `exports.x = x;` */
  133362. function createExportAssignment(name) {
  133363. return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 62 /* EqualsToken */, ts.createIdentifier(name)));
  133364. }
  133365. })(refactor = ts.refactor || (ts.refactor = {}));
  133366. })(ts || (ts = {}));
  133367. /* @internal */
  133368. var ts;
  133369. (function (ts) {
  133370. var refactor;
  133371. (function (refactor) {
  133372. var addOrRemoveBracesToArrowFunction;
  133373. (function (addOrRemoveBracesToArrowFunction) {
  133374. var refactorName = "Add or remove braces in an arrow function";
  133375. var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
  133376. var addBracesActionName = "Add braces to arrow function";
  133377. var removeBracesActionName = "Remove braces from arrow function";
  133378. var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message;
  133379. var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message;
  133380. refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
  133381. function getAvailableActions(context) {
  133382. var file = context.file, startPosition = context.startPosition;
  133383. var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
  133384. if (!info)
  133385. return ts.emptyArray;
  133386. return [{
  133387. name: refactorName,
  133388. description: refactorDescription,
  133389. actions: [
  133390. info.addBraces ?
  133391. {
  133392. name: addBracesActionName,
  133393. description: addBracesActionDescription
  133394. } : {
  133395. name: removeBracesActionName,
  133396. description: removeBracesActionDescription
  133397. }
  133398. ]
  133399. }];
  133400. }
  133401. function getEditsForAction(context, actionName) {
  133402. var file = context.file, startPosition = context.startPosition;
  133403. var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
  133404. if (!info)
  133405. return undefined;
  133406. var expression = info.expression, returnStatement = info.returnStatement, func = info.func;
  133407. var body;
  133408. if (actionName === addBracesActionName) {
  133409. var returnStatement_1 = ts.createReturn(expression);
  133410. body = ts.createBlock([returnStatement_1], /* multiLine */ true);
  133411. ts.suppressLeadingAndTrailingTrivia(body);
  133412. ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
  133413. }
  133414. else if (actionName === removeBracesActionName && returnStatement) {
  133415. var actualExpression = expression || ts.createVoidZero();
  133416. body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
  133417. ts.suppressLeadingAndTrailingTrivia(body);
  133418. ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
  133419. }
  133420. else {
  133421. ts.Debug.fail("invalid action");
  133422. }
  133423. var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); });
  133424. return { renameFilename: undefined, renameLocation: undefined, edits: edits };
  133425. }
  133426. function needsParentheses(expression) {
  133427. return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression);
  133428. }
  133429. function getConvertibleArrowFunctionAtPosition(file, startPosition) {
  133430. var node = ts.getTokenAtPosition(file, startPosition);
  133431. var func = ts.getContainingFunction(node);
  133432. if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node)))
  133433. return undefined;
  133434. if (ts.isExpression(func.body)) {
  133435. return {
  133436. func: func,
  133437. addBraces: true,
  133438. expression: func.body
  133439. };
  133440. }
  133441. else if (func.body.statements.length === 1) {
  133442. var firstStatement = ts.first(func.body.statements);
  133443. if (ts.isReturnStatement(firstStatement)) {
  133444. return {
  133445. func: func,
  133446. addBraces: false,
  133447. expression: firstStatement.expression,
  133448. returnStatement: firstStatement
  133449. };
  133450. }
  133451. }
  133452. return undefined;
  133453. }
  133454. })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
  133455. })(refactor = ts.refactor || (ts.refactor = {}));
  133456. })(ts || (ts = {}));
  133457. /* @internal */
  133458. var ts;
  133459. (function (ts) {
  133460. var refactor;
  133461. (function (refactor) {
  133462. var convertParamsToDestructuredObject;
  133463. (function (convertParamsToDestructuredObject) {
  133464. var refactorName = "Convert parameters to destructured object";
  133465. var minimumParameterLength = 2;
  133466. refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
  133467. function getAvailableActions(context) {
  133468. var file = context.file, startPosition = context.startPosition;
  133469. var isJSFile = ts.isSourceFileJS(file);
  133470. if (isJSFile)
  133471. return ts.emptyArray; // TODO: GH#30113
  133472. var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
  133473. if (!functionDeclaration)
  133474. return ts.emptyArray;
  133475. var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
  133476. return [{
  133477. name: refactorName,
  133478. description: description,
  133479. actions: [{
  133480. name: refactorName,
  133481. description: description
  133482. }]
  133483. }];
  133484. }
  133485. function getEditsForAction(context, actionName) {
  133486. ts.Debug.assert(actionName === refactorName, "Unexpected action name");
  133487. var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
  133488. var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
  133489. if (!functionDeclaration || !cancellationToken)
  133490. return undefined;
  133491. var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
  133492. if (groupedReferences.valid) {
  133493. var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
  133494. return { renameFilename: undefined, renameLocation: undefined, edits: edits };
  133495. }
  133496. return { edits: [] }; // TODO: GH#30113
  133497. }
  133498. function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
  133499. var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
  133500. changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
  133501. // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
  133502. indentation: 0,
  133503. leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
  133504. trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
  133505. });
  133506. var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
  133507. for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
  133508. var call = functionCalls_1[_i];
  133509. if (call.arguments && call.arguments.length) {
  133510. var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
  133511. changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
  133512. }
  133513. }
  133514. }
  133515. function getGroupedReferences(functionDeclaration, program, cancellationToken) {
  133516. var functionNames = getFunctionNames(functionDeclaration);
  133517. var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
  133518. var names = ts.deduplicate(__spreadArrays(functionNames, classNames), ts.equateValues);
  133519. var checker = program.getTypeChecker();
  133520. var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
  133521. var groupedReferences = groupReferences(references);
  133522. if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
  133523. groupedReferences.valid = false;
  133524. }
  133525. return groupedReferences;
  133526. function groupReferences(referenceEntries) {
  133527. var classReferences = { accessExpressions: [], typeUsages: [] };
  133528. var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
  133529. var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation);
  133530. var classSymbols = ts.map(classNames, getSymbolTargetAtLocation);
  133531. var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
  133532. for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
  133533. var entry = referenceEntries_1[_i];
  133534. if (entry.kind !== 1 /* Node */) {
  133535. groupedReferences.valid = false;
  133536. continue;
  133537. }
  133538. /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
  133539. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
  133540. class A { foo(a: number, b: number) { return a + b; } }
  133541. class B { foo(c: number, d: number) { return c + d; } }
  133542. declare const ab: A | B;
  133543. ab.foo(1, 2);
  133544. Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
  133545. When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
  133546. So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
  133547. the symbols are going to be different.
  133548. */
  133549. if (ts.contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || ts.isNewExpressionTarget(entry.node)) {
  133550. var importOrExportReference = entryToImportOrExport(entry);
  133551. if (importOrExportReference) {
  133552. continue;
  133553. }
  133554. var decl = entryToDeclaration(entry);
  133555. if (decl) {
  133556. groupedReferences.declarations.push(decl);
  133557. continue;
  133558. }
  133559. var call = entryToFunctionCall(entry);
  133560. if (call) {
  133561. groupedReferences.functionCalls.push(call);
  133562. continue;
  133563. }
  133564. }
  133565. // if the refactored function is a constructor, we must also check if the references to its class are valid
  133566. if (isConstructor && ts.contains(classSymbols, getSymbolTargetAtLocation(entry.node))) {
  133567. var importOrExportReference = entryToImportOrExport(entry);
  133568. if (importOrExportReference) {
  133569. continue;
  133570. }
  133571. var decl = entryToDeclaration(entry);
  133572. if (decl) {
  133573. groupedReferences.declarations.push(decl);
  133574. continue;
  133575. }
  133576. var accessExpression = entryToAccessExpression(entry);
  133577. if (accessExpression) {
  133578. classReferences.accessExpressions.push(accessExpression);
  133579. continue;
  133580. }
  133581. // Only class declarations are allowed to be used as a type (in a heritage clause),
  133582. // otherwise `findAllReferences` might not be able to track constructor calls.
  133583. if (ts.isClassDeclaration(functionDeclaration.parent)) {
  133584. var type = entryToType(entry);
  133585. if (type) {
  133586. classReferences.typeUsages.push(type);
  133587. continue;
  133588. }
  133589. }
  133590. }
  133591. groupedReferences.valid = false;
  133592. }
  133593. return groupedReferences;
  133594. }
  133595. function getSymbolTargetAtLocation(node) {
  133596. var symbol = checker.getSymbolAtLocation(node);
  133597. return symbol && ts.getSymbolTarget(symbol, checker);
  133598. }
  133599. }
  133600. function entryToImportOrExport(entry) {
  133601. var node = entry.node;
  133602. if (ts.isImportSpecifier(node.parent)
  133603. || ts.isImportClause(node.parent)
  133604. || ts.isImportEqualsDeclaration(node.parent)
  133605. || ts.isNamespaceImport(node.parent)) {
  133606. return node;
  133607. }
  133608. if (ts.isExportSpecifier(node.parent) || ts.isExportAssignment(node.parent)) {
  133609. return node;
  133610. }
  133611. return undefined;
  133612. }
  133613. function entryToDeclaration(entry) {
  133614. if (ts.isDeclaration(entry.node.parent)) {
  133615. return entry.node;
  133616. }
  133617. return undefined;
  133618. }
  133619. function entryToFunctionCall(entry) {
  133620. if (entry.node.parent) {
  133621. var functionReference = entry.node;
  133622. var parent = functionReference.parent;
  133623. switch (parent.kind) {
  133624. // foo(...) or super(...) or new Foo(...)
  133625. case 196 /* CallExpression */:
  133626. case 197 /* NewExpression */:
  133627. var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression);
  133628. if (callOrNewExpression && callOrNewExpression.expression === functionReference) {
  133629. return callOrNewExpression;
  133630. }
  133631. break;
  133632. // x.foo(...)
  133633. case 194 /* PropertyAccessExpression */:
  133634. var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
  133635. if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
  133636. var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression);
  133637. if (callOrNewExpression_1 && callOrNewExpression_1.expression === propertyAccessExpression) {
  133638. return callOrNewExpression_1;
  133639. }
  133640. }
  133641. break;
  133642. // x["foo"](...)
  133643. case 195 /* ElementAccessExpression */:
  133644. var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
  133645. if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
  133646. var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression);
  133647. if (callOrNewExpression_2 && callOrNewExpression_2.expression === elementAccessExpression) {
  133648. return callOrNewExpression_2;
  133649. }
  133650. }
  133651. break;
  133652. }
  133653. }
  133654. return undefined;
  133655. }
  133656. function entryToAccessExpression(entry) {
  133657. if (entry.node.parent) {
  133658. var reference = entry.node;
  133659. var parent = reference.parent;
  133660. switch (parent.kind) {
  133661. // `C.foo`
  133662. case 194 /* PropertyAccessExpression */:
  133663. var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
  133664. if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
  133665. return propertyAccessExpression;
  133666. }
  133667. break;
  133668. // `C["foo"]`
  133669. case 195 /* ElementAccessExpression */:
  133670. var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
  133671. if (elementAccessExpression && elementAccessExpression.expression === reference) {
  133672. return elementAccessExpression;
  133673. }
  133674. break;
  133675. }
  133676. }
  133677. return undefined;
  133678. }
  133679. function entryToType(entry) {
  133680. var reference = entry.node;
  133681. if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
  133682. return reference;
  133683. }
  133684. return undefined;
  133685. }
  133686. function getFunctionDeclarationAtPosition(file, startPosition, checker) {
  133687. var node = ts.getTouchingToken(file, startPosition);
  133688. var functionDeclaration = ts.getContainingFunctionDeclaration(node);
  133689. // don't offer refactor on top-level JSDoc
  133690. if (isTopLevelJSDoc(node))
  133691. return undefined;
  133692. if (functionDeclaration
  133693. && isValidFunctionDeclaration(functionDeclaration, checker)
  133694. && ts.rangeContainsRange(functionDeclaration, node)
  133695. && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
  133696. return functionDeclaration;
  133697. return undefined;
  133698. }
  133699. function isTopLevelJSDoc(node) {
  133700. var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
  133701. if (containingJSDoc) {
  133702. var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
  133703. return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
  133704. }
  133705. return false;
  133706. }
  133707. function isValidFunctionDeclaration(functionDeclaration, checker) {
  133708. if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
  133709. return false;
  133710. switch (functionDeclaration.kind) {
  133711. case 244 /* FunctionDeclaration */:
  133712. return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker);
  133713. case 161 /* MethodDeclaration */:
  133714. return isSingleImplementation(functionDeclaration, checker);
  133715. case 162 /* Constructor */:
  133716. if (ts.isClassDeclaration(functionDeclaration.parent)) {
  133717. return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker);
  133718. }
  133719. else {
  133720. return isValidVariableDeclaration(functionDeclaration.parent.parent)
  133721. && isSingleImplementation(functionDeclaration, checker);
  133722. }
  133723. case 201 /* FunctionExpression */:
  133724. case 202 /* ArrowFunction */:
  133725. return isValidVariableDeclaration(functionDeclaration.parent);
  133726. }
  133727. return false;
  133728. }
  133729. function isSingleImplementation(functionDeclaration, checker) {
  133730. return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
  133731. }
  133732. function hasNameOrDefault(functionOrClassDeclaration) {
  133733. if (!functionOrClassDeclaration.name) {
  133734. var defaultKeyword = ts.findModifier(functionOrClassDeclaration, 84 /* DefaultKeyword */);
  133735. return !!defaultKeyword;
  133736. }
  133737. return true;
  133738. }
  133739. function isValidParameterNodeArray(parameters, checker) {
  133740. return getRefactorableParametersLength(parameters) >= minimumParameterLength
  133741. && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
  133742. }
  133743. function isValidParameterDeclaration(parameterDeclaration, checker) {
  133744. if (ts.isRestParameter(parameterDeclaration)) {
  133745. var type = checker.getTypeAtLocation(parameterDeclaration);
  133746. if (!checker.isArrayType(type) && !checker.isTupleType(type))
  133747. return false;
  133748. }
  133749. return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
  133750. }
  133751. function isValidVariableDeclaration(node) {
  133752. return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
  133753. }
  133754. function hasThisParameter(parameters) {
  133755. return parameters.length > 0 && ts.isThis(parameters[0].name);
  133756. }
  133757. function getRefactorableParametersLength(parameters) {
  133758. if (hasThisParameter(parameters)) {
  133759. return parameters.length - 1;
  133760. }
  133761. return parameters.length;
  133762. }
  133763. function getRefactorableParameters(parameters) {
  133764. if (hasThisParameter(parameters)) {
  133765. parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
  133766. }
  133767. return parameters;
  133768. }
  133769. function createPropertyOrShorthandAssignment(name, initializer) {
  133770. if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
  133771. return ts.createShorthandPropertyAssignment(name);
  133772. }
  133773. return ts.createPropertyAssignment(name, initializer);
  133774. }
  133775. function createNewArgument(functionDeclaration, functionArguments) {
  133776. var parameters = getRefactorableParameters(functionDeclaration.parameters);
  133777. var hasRestParameter = ts.isRestParameter(ts.last(parameters));
  133778. var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
  133779. var properties = ts.map(nonRestArguments, function (arg, i) {
  133780. var parameterName = getParameterName(parameters[i]);
  133781. var property = createPropertyOrShorthandAssignment(parameterName, arg);
  133782. ts.suppressLeadingAndTrailingTrivia(property.name);
  133783. if (ts.isPropertyAssignment(property))
  133784. ts.suppressLeadingAndTrailingTrivia(property.initializer);
  133785. copyComments(arg, property);
  133786. return property;
  133787. });
  133788. if (hasRestParameter && functionArguments.length >= parameters.length) {
  133789. var restArguments = functionArguments.slice(parameters.length - 1);
  133790. var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
  133791. properties.push(restProperty);
  133792. }
  133793. var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
  133794. return objectLiteral;
  133795. }
  133796. function createNewParameters(functionDeclaration, program, host) {
  133797. var checker = program.getTypeChecker();
  133798. var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
  133799. var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
  133800. var objectParameterName = ts.createObjectBindingPattern(bindingElements);
  133801. var objectParameterType = createParameterTypeNode(refactorableParameters);
  133802. var objectInitializer;
  133803. // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
  133804. if (ts.every(refactorableParameters, isOptionalParameter)) {
  133805. objectInitializer = ts.createObjectLiteral();
  133806. }
  133807. var objectParameter = ts.createParameter(
  133808. /*decorators*/ undefined,
  133809. /*modifiers*/ undefined,
  133810. /*dotDotDotToken*/ undefined, objectParameterName,
  133811. /*questionToken*/ undefined, objectParameterType, objectInitializer);
  133812. if (hasThisParameter(functionDeclaration.parameters)) {
  133813. var thisParameter = functionDeclaration.parameters[0];
  133814. var newThisParameter = ts.createParameter(
  133815. /*decorators*/ undefined,
  133816. /*modifiers*/ undefined,
  133817. /*dotDotDotToken*/ undefined, thisParameter.name,
  133818. /*questionToken*/ undefined, thisParameter.type);
  133819. ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
  133820. copyComments(thisParameter.name, newThisParameter.name);
  133821. if (thisParameter.type) {
  133822. ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
  133823. copyComments(thisParameter.type, newThisParameter.type);
  133824. }
  133825. return ts.createNodeArray([newThisParameter, objectParameter]);
  133826. }
  133827. return ts.createNodeArray([objectParameter]);
  133828. function createBindingElementFromParameterDeclaration(parameterDeclaration) {
  133829. var element = ts.createBindingElement(
  133830. /*dotDotDotToken*/ undefined,
  133831. /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
  133832. ts.suppressLeadingAndTrailingTrivia(element);
  133833. if (parameterDeclaration.initializer && element.initializer) {
  133834. copyComments(parameterDeclaration.initializer, element.initializer);
  133835. }
  133836. return element;
  133837. }
  133838. function createParameterTypeNode(parameters) {
  133839. var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
  133840. var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
  133841. return typeNode;
  133842. }
  133843. function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
  133844. var parameterType = parameterDeclaration.type;
  133845. if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
  133846. parameterType = getTypeNode(parameterDeclaration);
  133847. }
  133848. var propertySignature = ts.createPropertySignature(
  133849. /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
  133850. /*initializer*/ undefined);
  133851. ts.suppressLeadingAndTrailingTrivia(propertySignature);
  133852. copyComments(parameterDeclaration.name, propertySignature.name);
  133853. if (parameterDeclaration.type && propertySignature.type) {
  133854. copyComments(parameterDeclaration.type, propertySignature.type);
  133855. }
  133856. return propertySignature;
  133857. }
  133858. function getTypeNode(node) {
  133859. var type = checker.getTypeAtLocation(node);
  133860. return ts.getTypeNodeIfAccessible(type, node, program, host);
  133861. }
  133862. function isOptionalParameter(parameterDeclaration) {
  133863. if (ts.isRestParameter(parameterDeclaration)) {
  133864. var type = checker.getTypeAtLocation(parameterDeclaration);
  133865. return !checker.isTupleType(type);
  133866. }
  133867. return checker.isOptionalParameter(parameterDeclaration);
  133868. }
  133869. }
  133870. function copyComments(sourceNode, targetNode) {
  133871. var sourceFile = sourceNode.getSourceFile();
  133872. var text = sourceFile.text;
  133873. if (hasLeadingLineBreak(sourceNode, text)) {
  133874. ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
  133875. }
  133876. else {
  133877. ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
  133878. }
  133879. ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
  133880. }
  133881. function hasLeadingLineBreak(node, text) {
  133882. var start = node.getFullStart();
  133883. var end = node.getStart();
  133884. for (var i = start; i < end; i++) {
  133885. if (text.charCodeAt(i) === 10 /* lineFeed */)
  133886. return true;
  133887. }
  133888. return false;
  133889. }
  133890. function getParameterName(paramDeclaration) {
  133891. return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
  133892. }
  133893. function getClassNames(constructorDeclaration) {
  133894. switch (constructorDeclaration.parent.kind) {
  133895. case 245 /* ClassDeclaration */:
  133896. var classDeclaration = constructorDeclaration.parent;
  133897. if (classDeclaration.name)
  133898. return [classDeclaration.name];
  133899. // If the class declaration doesn't have a name, it should have a default modifier.
  133900. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
  133901. var defaultModifier = ts.Debug.assertDefined(ts.findModifier(classDeclaration, 84 /* DefaultKeyword */), "Nameless class declaration should be a default export");
  133902. return [defaultModifier];
  133903. case 214 /* ClassExpression */:
  133904. var classExpression = constructorDeclaration.parent;
  133905. var variableDeclaration = constructorDeclaration.parent.parent;
  133906. var className = classExpression.name;
  133907. if (className)
  133908. return [className, variableDeclaration.name];
  133909. return [variableDeclaration.name];
  133910. }
  133911. }
  133912. function getFunctionNames(functionDeclaration) {
  133913. switch (functionDeclaration.kind) {
  133914. case 244 /* FunctionDeclaration */:
  133915. if (functionDeclaration.name)
  133916. return [functionDeclaration.name];
  133917. // If the function declaration doesn't have a name, it should have a default modifier.
  133918. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
  133919. var defaultModifier = ts.Debug.assertDefined(ts.findModifier(functionDeclaration, 84 /* DefaultKeyword */), "Nameless function declaration should be a default export");
  133920. return [defaultModifier];
  133921. case 161 /* MethodDeclaration */:
  133922. return [functionDeclaration.name];
  133923. case 162 /* Constructor */:
  133924. var ctrKeyword = ts.Debug.assertDefined(ts.findChildOfKind(functionDeclaration, 129 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword");
  133925. if (functionDeclaration.parent.kind === 214 /* ClassExpression */) {
  133926. var variableDeclaration = functionDeclaration.parent.parent;
  133927. return [variableDeclaration.name, ctrKeyword];
  133928. }
  133929. return [ctrKeyword];
  133930. case 202 /* ArrowFunction */:
  133931. return [functionDeclaration.parent.name];
  133932. case 201 /* FunctionExpression */:
  133933. if (functionDeclaration.name)
  133934. return [functionDeclaration.name, functionDeclaration.parent.name];
  133935. return [functionDeclaration.parent.name];
  133936. default:
  133937. return ts.Debug.assertNever(functionDeclaration, "Unexpected function declaration kind " + functionDeclaration.kind);
  133938. }
  133939. }
  133940. })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
  133941. })(refactor = ts.refactor || (ts.refactor = {}));
  133942. })(ts || (ts = {}));
  133943. /* @internal */
  133944. var ts;
  133945. (function (ts) {
  133946. var refactor;
  133947. (function (refactor) {
  133948. var convertStringOrTemplateLiteral;
  133949. (function (convertStringOrTemplateLiteral) {
  133950. var refactorName = "Convert to template string";
  133951. var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_template_string);
  133952. refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
  133953. function getAvailableActions(context) {
  133954. var file = context.file, startPosition = context.startPosition;
  133955. var node = getNodeOrParentOfParentheses(file, startPosition);
  133956. var maybeBinary = getParentBinaryExpression(node);
  133957. var refactorInfo = { name: refactorName, description: refactorDescription, actions: [] };
  133958. if (ts.isBinaryExpression(maybeBinary) && isStringConcatenationValid(maybeBinary)) {
  133959. refactorInfo.actions.push({ name: refactorName, description: refactorDescription });
  133960. return [refactorInfo];
  133961. }
  133962. return ts.emptyArray;
  133963. }
  133964. function getNodeOrParentOfParentheses(file, startPosition) {
  133965. var node = ts.getTokenAtPosition(file, startPosition);
  133966. var nestedBinary = getParentBinaryExpression(node);
  133967. var isNonStringBinary = !isStringConcatenationValid(nestedBinary);
  133968. if (isNonStringBinary &&
  133969. ts.isParenthesizedExpression(nestedBinary.parent) &&
  133970. ts.isBinaryExpression(nestedBinary.parent.parent)) {
  133971. return nestedBinary.parent.parent;
  133972. }
  133973. return node;
  133974. }
  133975. function getEditsForAction(context, actionName) {
  133976. var file = context.file, startPosition = context.startPosition;
  133977. var node = getNodeOrParentOfParentheses(file, startPosition);
  133978. switch (actionName) {
  133979. case refactorDescription:
  133980. return { edits: getEditsForToTemplateLiteral(context, node) };
  133981. default:
  133982. return ts.Debug.fail("invalid action");
  133983. }
  133984. }
  133985. function getEditsForToTemplateLiteral(context, node) {
  133986. var maybeBinary = getParentBinaryExpression(node);
  133987. var file = context.file;
  133988. var templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file);
  133989. var trailingCommentRanges = ts.getTrailingCommentRanges(file.text, maybeBinary.end);
  133990. if (trailingCommentRanges) {
  133991. var lastComment = trailingCommentRanges[trailingCommentRanges.length - 1];
  133992. var trailingRange_1 = { pos: trailingCommentRanges[0].pos, end: lastComment.end };
  133993. // since suppressTrailingTrivia(maybeBinary) does not work, the trailing comment is removed manually
  133994. // otherwise it would have the trailing comment twice
  133995. return ts.textChanges.ChangeTracker.with(context, function (t) {
  133996. t.deleteRange(file, trailingRange_1);
  133997. t.replaceNode(file, maybeBinary, templateLiteral);
  133998. });
  133999. }
  134000. else {
  134001. return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, maybeBinary, templateLiteral); });
  134002. }
  134003. }
  134004. function isNotEqualsOperator(node) {
  134005. return node.operatorToken.kind !== 62 /* EqualsToken */;
  134006. }
  134007. function getParentBinaryExpression(expr) {
  134008. while (ts.isBinaryExpression(expr.parent) && isNotEqualsOperator(expr.parent)) {
  134009. expr = expr.parent;
  134010. }
  134011. return expr;
  134012. }
  134013. function isStringConcatenationValid(node) {
  134014. var _a = treeToArray(node), containsString = _a.containsString, areOperatorsValid = _a.areOperatorsValid;
  134015. return containsString && areOperatorsValid;
  134016. }
  134017. function treeToArray(current) {
  134018. if (ts.isBinaryExpression(current)) {
  134019. var _a = treeToArray(current.left), nodes = _a.nodes, operators = _a.operators, leftHasString = _a.containsString, leftOperatorValid = _a.areOperatorsValid;
  134020. if (!leftHasString && !ts.isStringLiteral(current.right)) {
  134021. return { nodes: [current], operators: [], containsString: false, areOperatorsValid: true };
  134022. }
  134023. var currentOperatorValid = current.operatorToken.kind === 39 /* PlusToken */;
  134024. var areOperatorsValid = leftOperatorValid && currentOperatorValid;
  134025. nodes.push(current.right);
  134026. operators.push(current.operatorToken);
  134027. return { nodes: nodes, operators: operators, containsString: true, areOperatorsValid: areOperatorsValid };
  134028. }
  134029. return { nodes: [current], operators: [], containsString: ts.isStringLiteral(current), areOperatorsValid: true };
  134030. }
  134031. // to copy comments following the operator
  134032. // "foo" + /* comment */ "bar"
  134033. var copyTrailingOperatorComments = function (operators, file) { return function (index, targetNode) {
  134034. if (index < operators.length) {
  134035. ts.copyTrailingComments(operators[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
  134036. }
  134037. }; };
  134038. // to copy comments following the string
  134039. // "foo" /* comment */ + "bar" /* comment */ + "bar2"
  134040. var copyCommentFromMultiNode = function (nodes, file, copyOperatorComments) {
  134041. return function (indexes, targetNode) {
  134042. while (indexes.length > 0) {
  134043. var index = indexes.shift();
  134044. ts.copyTrailingComments(nodes[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
  134045. copyOperatorComments(index, targetNode);
  134046. }
  134047. };
  134048. };
  134049. function concatConsecutiveString(index, nodes) {
  134050. var text = "";
  134051. var indexes = [];
  134052. while (index < nodes.length && ts.isStringLiteral(nodes[index])) {
  134053. var stringNode = nodes[index];
  134054. text = text + stringNode.text;
  134055. indexes.push(index);
  134056. index++;
  134057. }
  134058. text = ts.escapeString(text);
  134059. return [index, text, indexes];
  134060. }
  134061. function nodesToTemplate(_a, file) {
  134062. var nodes = _a.nodes, operators = _a.operators;
  134063. var copyOperatorComments = copyTrailingOperatorComments(operators, file);
  134064. var copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments);
  134065. var _b = concatConsecutiveString(0, nodes), begin = _b[0], headText = _b[1], headIndexes = _b[2];
  134066. if (begin === nodes.length) {
  134067. var noSubstitutionTemplateLiteral = ts.createNoSubstitutionTemplateLiteral(headText);
  134068. copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral);
  134069. return noSubstitutionTemplateLiteral;
  134070. }
  134071. var templateSpans = [];
  134072. var templateHead = ts.createTemplateHead(headText);
  134073. copyCommentFromStringLiterals(headIndexes, templateHead);
  134074. for (var i = begin; i < nodes.length; i++) {
  134075. var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]);
  134076. copyOperatorComments(i, currentNode);
  134077. var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2];
  134078. i = newIndex - 1;
  134079. var templatePart = i === nodes.length - 1 ? ts.createTemplateTail(subsequentText) : ts.createTemplateMiddle(subsequentText);
  134080. copyCommentFromStringLiterals(stringIndexes, templatePart);
  134081. templateSpans.push(ts.createTemplateSpan(currentNode, templatePart));
  134082. }
  134083. return ts.createTemplateExpression(templateHead, templateSpans);
  134084. }
  134085. // to copy comments following the opening & closing parentheses
  134086. // "foo" + ( /* comment */ 5 + 5 ) /* comment */ + "bar"
  134087. function copyCommentsWhenParenthesized(node) {
  134088. var file = node.getSourceFile();
  134089. ts.copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
  134090. ts.copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
  134091. }
  134092. function getExpressionFromParenthesesOrExpression(node) {
  134093. if (ts.isParenthesizedExpression(node)) {
  134094. copyCommentsWhenParenthesized(node);
  134095. node = node.expression;
  134096. }
  134097. return node;
  134098. }
  134099. })(convertStringOrTemplateLiteral = refactor.convertStringOrTemplateLiteral || (refactor.convertStringOrTemplateLiteral = {}));
  134100. })(refactor = ts.refactor || (ts.refactor = {}));
  134101. })(ts || (ts = {}));
  134102. var ts;
  134103. (function (ts) {
  134104. /** The version of the language service API */
  134105. ts.servicesVersion = "0.8";
  134106. function createNode(kind, pos, end, parent) {
  134107. var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) :
  134108. kind === 75 /* Identifier */ ? new IdentifierObject(75 /* Identifier */, pos, end) :
  134109. kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierObject(76 /* PrivateIdentifier */, pos, end) :
  134110. new TokenObject(kind, pos, end);
  134111. node.parent = parent;
  134112. node.flags = parent.flags & 25358336 /* ContextFlags */;
  134113. return node;
  134114. }
  134115. var NodeObject = /** @class */ (function () {
  134116. function NodeObject(kind, pos, end) {
  134117. this.pos = pos;
  134118. this.end = end;
  134119. this.flags = 0 /* None */;
  134120. this.modifierFlagsCache = 0 /* None */;
  134121. this.transformFlags = 0 /* None */;
  134122. this.parent = undefined;
  134123. this.kind = kind;
  134124. }
  134125. NodeObject.prototype.assertHasRealPosition = function (message) {
  134126. // eslint-disable-next-line debug-assert
  134127. ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation");
  134128. };
  134129. NodeObject.prototype.getSourceFile = function () {
  134130. return ts.getSourceFileOfNode(this);
  134131. };
  134132. NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
  134133. this.assertHasRealPosition();
  134134. return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
  134135. };
  134136. NodeObject.prototype.getFullStart = function () {
  134137. this.assertHasRealPosition();
  134138. return this.pos;
  134139. };
  134140. NodeObject.prototype.getEnd = function () {
  134141. this.assertHasRealPosition();
  134142. return this.end;
  134143. };
  134144. NodeObject.prototype.getWidth = function (sourceFile) {
  134145. this.assertHasRealPosition();
  134146. return this.getEnd() - this.getStart(sourceFile);
  134147. };
  134148. NodeObject.prototype.getFullWidth = function () {
  134149. this.assertHasRealPosition();
  134150. return this.end - this.pos;
  134151. };
  134152. NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
  134153. this.assertHasRealPosition();
  134154. return this.getStart(sourceFile) - this.pos;
  134155. };
  134156. NodeObject.prototype.getFullText = function (sourceFile) {
  134157. this.assertHasRealPosition();
  134158. return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
  134159. };
  134160. NodeObject.prototype.getText = function (sourceFile) {
  134161. this.assertHasRealPosition();
  134162. if (!sourceFile) {
  134163. sourceFile = this.getSourceFile();
  134164. }
  134165. return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
  134166. };
  134167. NodeObject.prototype.getChildCount = function (sourceFile) {
  134168. return this.getChildren(sourceFile).length;
  134169. };
  134170. NodeObject.prototype.getChildAt = function (index, sourceFile) {
  134171. return this.getChildren(sourceFile)[index];
  134172. };
  134173. NodeObject.prototype.getChildren = function (sourceFile) {
  134174. this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine");
  134175. return this._children || (this._children = createChildren(this, sourceFile));
  134176. };
  134177. NodeObject.prototype.getFirstToken = function (sourceFile) {
  134178. this.assertHasRealPosition();
  134179. var children = this.getChildren(sourceFile);
  134180. if (!children.length) {
  134181. return undefined;
  134182. }
  134183. var child = ts.find(children, function (kid) { return kid.kind < 294 /* FirstJSDocNode */ || kid.kind > 322 /* LastJSDocNode */; });
  134184. return child.kind < 153 /* FirstNode */ ?
  134185. child :
  134186. child.getFirstToken(sourceFile);
  134187. };
  134188. NodeObject.prototype.getLastToken = function (sourceFile) {
  134189. this.assertHasRealPosition();
  134190. var children = this.getChildren(sourceFile);
  134191. var child = ts.lastOrUndefined(children);
  134192. if (!child) {
  134193. return undefined;
  134194. }
  134195. return child.kind < 153 /* FirstNode */ ? child : child.getLastToken(sourceFile);
  134196. };
  134197. NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) {
  134198. return ts.forEachChild(this, cbNode, cbNodeArray);
  134199. };
  134200. return NodeObject;
  134201. }());
  134202. function createChildren(node, sourceFile) {
  134203. if (!ts.isNodeKind(node.kind)) {
  134204. return ts.emptyArray;
  134205. }
  134206. var children = [];
  134207. if (ts.isJSDocCommentContainingNode(node)) {
  134208. /** Don't add trivia for "tokens" since this is in a comment. */
  134209. node.forEachChild(function (child) { children.push(child); });
  134210. return children;
  134211. }
  134212. ts.scanner.setText((sourceFile || node.getSourceFile()).text);
  134213. var pos = node.pos;
  134214. var processNode = function (child) {
  134215. addSyntheticNodes(children, pos, child.pos, node);
  134216. children.push(child);
  134217. pos = child.end;
  134218. };
  134219. var processNodes = function (nodes) {
  134220. addSyntheticNodes(children, pos, nodes.pos, node);
  134221. children.push(createSyntaxList(nodes, node));
  134222. pos = nodes.end;
  134223. };
  134224. // jsDocComments need to be the first children
  134225. ts.forEach(node.jsDoc, processNode);
  134226. // For syntactic classifications, all trivia are classified together, including jsdoc comments.
  134227. // For that to work, the jsdoc comments should still be the leading trivia of the first child.
  134228. // Restoring the scanner position ensures that.
  134229. pos = node.pos;
  134230. node.forEachChild(processNode, processNodes);
  134231. addSyntheticNodes(children, pos, node.end, node);
  134232. ts.scanner.setText(undefined);
  134233. return children;
  134234. }
  134235. function addSyntheticNodes(nodes, pos, end, parent) {
  134236. ts.scanner.setTextPos(pos);
  134237. while (pos < end) {
  134238. var token = ts.scanner.scan();
  134239. var textPos = ts.scanner.getTextPos();
  134240. if (textPos <= end) {
  134241. if (token === 75 /* Identifier */) {
  134242. ts.Debug.fail("Did not expect " + ts.Debug.formatSyntaxKind(parent.kind) + " to have an Identifier in its trivia");
  134243. }
  134244. nodes.push(createNode(token, pos, textPos, parent));
  134245. }
  134246. pos = textPos;
  134247. if (token === 1 /* EndOfFileToken */) {
  134248. break;
  134249. }
  134250. }
  134251. }
  134252. function createSyntaxList(nodes, parent) {
  134253. var list = createNode(323 /* SyntaxList */, nodes.pos, nodes.end, parent);
  134254. list._children = [];
  134255. var pos = nodes.pos;
  134256. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  134257. var node = nodes_1[_i];
  134258. addSyntheticNodes(list._children, pos, node.pos, parent);
  134259. list._children.push(node);
  134260. pos = node.end;
  134261. }
  134262. addSyntheticNodes(list._children, pos, nodes.end, parent);
  134263. return list;
  134264. }
  134265. var TokenOrIdentifierObject = /** @class */ (function () {
  134266. function TokenOrIdentifierObject(pos, end) {
  134267. // Set properties in same order as NodeObject
  134268. this.pos = pos;
  134269. this.end = end;
  134270. this.flags = 0 /* None */;
  134271. this.modifierFlagsCache = 0 /* None */;
  134272. this.transformFlags = 0 /* None */;
  134273. this.parent = undefined;
  134274. }
  134275. TokenOrIdentifierObject.prototype.getSourceFile = function () {
  134276. return ts.getSourceFileOfNode(this);
  134277. };
  134278. TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
  134279. return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
  134280. };
  134281. TokenOrIdentifierObject.prototype.getFullStart = function () {
  134282. return this.pos;
  134283. };
  134284. TokenOrIdentifierObject.prototype.getEnd = function () {
  134285. return this.end;
  134286. };
  134287. TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
  134288. return this.getEnd() - this.getStart(sourceFile);
  134289. };
  134290. TokenOrIdentifierObject.prototype.getFullWidth = function () {
  134291. return this.end - this.pos;
  134292. };
  134293. TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
  134294. return this.getStart(sourceFile) - this.pos;
  134295. };
  134296. TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
  134297. return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
  134298. };
  134299. TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
  134300. if (!sourceFile) {
  134301. sourceFile = this.getSourceFile();
  134302. }
  134303. return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
  134304. };
  134305. TokenOrIdentifierObject.prototype.getChildCount = function () {
  134306. return 0;
  134307. };
  134308. TokenOrIdentifierObject.prototype.getChildAt = function () {
  134309. return undefined; // TODO: GH#18217
  134310. };
  134311. TokenOrIdentifierObject.prototype.getChildren = function () {
  134312. return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray;
  134313. };
  134314. TokenOrIdentifierObject.prototype.getFirstToken = function () {
  134315. return undefined;
  134316. };
  134317. TokenOrIdentifierObject.prototype.getLastToken = function () {
  134318. return undefined;
  134319. };
  134320. TokenOrIdentifierObject.prototype.forEachChild = function () {
  134321. return undefined;
  134322. };
  134323. return TokenOrIdentifierObject;
  134324. }());
  134325. var SymbolObject = /** @class */ (function () {
  134326. function SymbolObject(flags, name) {
  134327. this.flags = flags;
  134328. this.escapedName = name;
  134329. }
  134330. SymbolObject.prototype.getFlags = function () {
  134331. return this.flags;
  134332. };
  134333. Object.defineProperty(SymbolObject.prototype, "name", {
  134334. get: function () {
  134335. return ts.symbolName(this);
  134336. },
  134337. enumerable: true,
  134338. configurable: true
  134339. });
  134340. SymbolObject.prototype.getEscapedName = function () {
  134341. return this.escapedName;
  134342. };
  134343. SymbolObject.prototype.getName = function () {
  134344. return this.name;
  134345. };
  134346. SymbolObject.prototype.getDeclarations = function () {
  134347. return this.declarations;
  134348. };
  134349. SymbolObject.prototype.getDocumentationComment = function (checker) {
  134350. if (!this.documentationComment) {
  134351. this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs
  134352. this.documentationComment = getDocumentationComment(this.declarations, checker);
  134353. }
  134354. return this.documentationComment;
  134355. };
  134356. SymbolObject.prototype.getJsDocTags = function () {
  134357. if (this.tags === undefined) {
  134358. this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations);
  134359. }
  134360. return this.tags;
  134361. };
  134362. return SymbolObject;
  134363. }());
  134364. var TokenObject = /** @class */ (function (_super) {
  134365. __extends(TokenObject, _super);
  134366. function TokenObject(kind, pos, end) {
  134367. var _this = _super.call(this, pos, end) || this;
  134368. _this.kind = kind;
  134369. return _this;
  134370. }
  134371. return TokenObject;
  134372. }(TokenOrIdentifierObject));
  134373. var IdentifierObject = /** @class */ (function (_super) {
  134374. __extends(IdentifierObject, _super);
  134375. function IdentifierObject(_kind, pos, end) {
  134376. var _this = _super.call(this, pos, end) || this;
  134377. _this.kind = 75 /* Identifier */;
  134378. return _this;
  134379. }
  134380. Object.defineProperty(IdentifierObject.prototype, "text", {
  134381. get: function () {
  134382. return ts.idText(this);
  134383. },
  134384. enumerable: true,
  134385. configurable: true
  134386. });
  134387. return IdentifierObject;
  134388. }(TokenOrIdentifierObject));
  134389. IdentifierObject.prototype.kind = 75 /* Identifier */;
  134390. var PrivateIdentifierObject = /** @class */ (function (_super) {
  134391. __extends(PrivateIdentifierObject, _super);
  134392. function PrivateIdentifierObject(_kind, pos, end) {
  134393. return _super.call(this, pos, end) || this;
  134394. }
  134395. Object.defineProperty(PrivateIdentifierObject.prototype, "text", {
  134396. get: function () {
  134397. return ts.idText(this);
  134398. },
  134399. enumerable: true,
  134400. configurable: true
  134401. });
  134402. return PrivateIdentifierObject;
  134403. }(TokenOrIdentifierObject));
  134404. PrivateIdentifierObject.prototype.kind = 76 /* PrivateIdentifier */;
  134405. var TypeObject = /** @class */ (function () {
  134406. function TypeObject(checker, flags) {
  134407. this.checker = checker;
  134408. this.flags = flags;
  134409. }
  134410. TypeObject.prototype.getFlags = function () {
  134411. return this.flags;
  134412. };
  134413. TypeObject.prototype.getSymbol = function () {
  134414. return this.symbol;
  134415. };
  134416. TypeObject.prototype.getProperties = function () {
  134417. return this.checker.getPropertiesOfType(this);
  134418. };
  134419. TypeObject.prototype.getProperty = function (propertyName) {
  134420. return this.checker.getPropertyOfType(this, propertyName);
  134421. };
  134422. TypeObject.prototype.getApparentProperties = function () {
  134423. return this.checker.getAugmentedPropertiesOfType(this);
  134424. };
  134425. TypeObject.prototype.getCallSignatures = function () {
  134426. return this.checker.getSignaturesOfType(this, 0 /* Call */);
  134427. };
  134428. TypeObject.prototype.getConstructSignatures = function () {
  134429. return this.checker.getSignaturesOfType(this, 1 /* Construct */);
  134430. };
  134431. TypeObject.prototype.getStringIndexType = function () {
  134432. return this.checker.getIndexTypeOfType(this, 0 /* String */);
  134433. };
  134434. TypeObject.prototype.getNumberIndexType = function () {
  134435. return this.checker.getIndexTypeOfType(this, 1 /* Number */);
  134436. };
  134437. TypeObject.prototype.getBaseTypes = function () {
  134438. return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined;
  134439. };
  134440. TypeObject.prototype.isNullableType = function () {
  134441. return this.checker.isNullableType(this);
  134442. };
  134443. TypeObject.prototype.getNonNullableType = function () {
  134444. return this.checker.getNonNullableType(this);
  134445. };
  134446. TypeObject.prototype.getNonOptionalType = function () {
  134447. return this.checker.getNonOptionalType(this);
  134448. };
  134449. TypeObject.prototype.getConstraint = function () {
  134450. return this.checker.getBaseConstraintOfType(this);
  134451. };
  134452. TypeObject.prototype.getDefault = function () {
  134453. return this.checker.getDefaultFromTypeParameter(this);
  134454. };
  134455. TypeObject.prototype.isUnion = function () {
  134456. return !!(this.flags & 1048576 /* Union */);
  134457. };
  134458. TypeObject.prototype.isIntersection = function () {
  134459. return !!(this.flags & 2097152 /* Intersection */);
  134460. };
  134461. TypeObject.prototype.isUnionOrIntersection = function () {
  134462. return !!(this.flags & 3145728 /* UnionOrIntersection */);
  134463. };
  134464. TypeObject.prototype.isLiteral = function () {
  134465. return !!(this.flags & 384 /* StringOrNumberLiteral */);
  134466. };
  134467. TypeObject.prototype.isStringLiteral = function () {
  134468. return !!(this.flags & 128 /* StringLiteral */);
  134469. };
  134470. TypeObject.prototype.isNumberLiteral = function () {
  134471. return !!(this.flags & 256 /* NumberLiteral */);
  134472. };
  134473. TypeObject.prototype.isTypeParameter = function () {
  134474. return !!(this.flags & 262144 /* TypeParameter */);
  134475. };
  134476. TypeObject.prototype.isClassOrInterface = function () {
  134477. return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */);
  134478. };
  134479. TypeObject.prototype.isClass = function () {
  134480. return !!(ts.getObjectFlags(this) & 1 /* Class */);
  134481. };
  134482. Object.defineProperty(TypeObject.prototype, "typeArguments", {
  134483. /**
  134484. * This polyfills `referenceType.typeArguments` for API consumers
  134485. */
  134486. get: function () {
  134487. if (ts.getObjectFlags(this) & 4 /* Reference */) {
  134488. return this.checker.getTypeArguments(this);
  134489. }
  134490. return undefined;
  134491. },
  134492. enumerable: true,
  134493. configurable: true
  134494. });
  134495. return TypeObject;
  134496. }());
  134497. var SignatureObject = /** @class */ (function () {
  134498. function SignatureObject(checker, flags) {
  134499. this.checker = checker;
  134500. this.flags = flags;
  134501. }
  134502. SignatureObject.prototype.getDeclaration = function () {
  134503. return this.declaration;
  134504. };
  134505. SignatureObject.prototype.getTypeParameters = function () {
  134506. return this.typeParameters;
  134507. };
  134508. SignatureObject.prototype.getParameters = function () {
  134509. return this.parameters;
  134510. };
  134511. SignatureObject.prototype.getReturnType = function () {
  134512. return this.checker.getReturnTypeOfSignature(this);
  134513. };
  134514. SignatureObject.prototype.getDocumentationComment = function () {
  134515. return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker));
  134516. };
  134517. SignatureObject.prototype.getJsDocTags = function () {
  134518. if (this.jsDocTags === undefined) {
  134519. this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : [];
  134520. }
  134521. return this.jsDocTags;
  134522. };
  134523. return SignatureObject;
  134524. }());
  134525. /**
  134526. * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it.
  134527. * @param node the Node in question.
  134528. * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`.
  134529. */
  134530. function hasJSDocInheritDocTag(node) {
  134531. return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; });
  134532. }
  134533. function getDocumentationComment(declarations, checker) {
  134534. if (!declarations)
  134535. return ts.emptyArray;
  134536. var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
  134537. if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
  134538. ts.forEachUnique(declarations, function (declaration) {
  134539. var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
  134540. // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
  134541. if (inheritedDocs)
  134542. doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc);
  134543. });
  134544. }
  134545. return doc;
  134546. }
  134547. /**
  134548. * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses
  134549. * implemented interfaces until a symbol is found with the same name and with documentation.
  134550. * @param declaration The possibly-inherited declaration to find comments for.
  134551. * @param propertyName The name of the possibly-inherited property.
  134552. * @param typeChecker A TypeChecker, used to find inherited properties.
  134553. * @returns A filled array of documentation comments if any were found, otherwise an empty array.
  134554. */
  134555. function findInheritedJSDocComments(declaration, propertyName, typeChecker) {
  134556. return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) {
  134557. var superType = typeChecker.getTypeAtLocation(superTypeNode);
  134558. var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName);
  134559. var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker);
  134560. return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined;
  134561. });
  134562. }
  134563. var SourceFileObject = /** @class */ (function (_super) {
  134564. __extends(SourceFileObject, _super);
  134565. function SourceFileObject(kind, pos, end) {
  134566. var _this = _super.call(this, kind, pos, end) || this;
  134567. _this.kind = 290 /* SourceFile */;
  134568. return _this;
  134569. }
  134570. SourceFileObject.prototype.update = function (newText, textChangeRange) {
  134571. return ts.updateSourceFile(this, newText, textChangeRange);
  134572. };
  134573. SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) {
  134574. return ts.getLineAndCharacterOfPosition(this, position);
  134575. };
  134576. SourceFileObject.prototype.getLineStarts = function () {
  134577. return ts.getLineStarts(this);
  134578. };
  134579. SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) {
  134580. return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits);
  134581. };
  134582. SourceFileObject.prototype.getLineEndOfPosition = function (pos) {
  134583. var line = this.getLineAndCharacterOfPosition(pos).line;
  134584. var lineStarts = this.getLineStarts();
  134585. var lastCharPos;
  134586. if (line + 1 >= lineStarts.length) {
  134587. lastCharPos = this.getEnd();
  134588. }
  134589. if (!lastCharPos) {
  134590. lastCharPos = lineStarts[line + 1] - 1;
  134591. }
  134592. var fullText = this.getFullText();
  134593. // if the new line is "\r\n", we should return the last non-new-line-character position
  134594. return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos;
  134595. };
  134596. SourceFileObject.prototype.getNamedDeclarations = function () {
  134597. if (!this.namedDeclarations) {
  134598. this.namedDeclarations = this.computeNamedDeclarations();
  134599. }
  134600. return this.namedDeclarations;
  134601. };
  134602. SourceFileObject.prototype.computeNamedDeclarations = function () {
  134603. var result = ts.createMultiMap();
  134604. this.forEachChild(visit);
  134605. return result;
  134606. function addDeclaration(declaration) {
  134607. var name = getDeclarationName(declaration);
  134608. if (name) {
  134609. result.add(name, declaration);
  134610. }
  134611. }
  134612. function getDeclarations(name) {
  134613. var declarations = result.get(name);
  134614. if (!declarations) {
  134615. result.set(name, declarations = []);
  134616. }
  134617. return declarations;
  134618. }
  134619. function getDeclarationName(declaration) {
  134620. var name = ts.getNonAssignedNameOfDeclaration(declaration);
  134621. return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text
  134622. : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined);
  134623. }
  134624. function visit(node) {
  134625. switch (node.kind) {
  134626. case 244 /* FunctionDeclaration */:
  134627. case 201 /* FunctionExpression */:
  134628. case 161 /* MethodDeclaration */:
  134629. case 160 /* MethodSignature */:
  134630. var functionDeclaration = node;
  134631. var declarationName = getDeclarationName(functionDeclaration);
  134632. if (declarationName) {
  134633. var declarations = getDeclarations(declarationName);
  134634. var lastDeclaration = ts.lastOrUndefined(declarations);
  134635. // Check whether this declaration belongs to an "overload group".
  134636. if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
  134637. // Overwrite the last declaration if it was an overload
  134638. // and this one is an implementation.
  134639. if (functionDeclaration.body && !lastDeclaration.body) {
  134640. declarations[declarations.length - 1] = functionDeclaration;
  134641. }
  134642. }
  134643. else {
  134644. declarations.push(functionDeclaration);
  134645. }
  134646. }
  134647. ts.forEachChild(node, visit);
  134648. break;
  134649. case 245 /* ClassDeclaration */:
  134650. case 214 /* ClassExpression */:
  134651. case 246 /* InterfaceDeclaration */:
  134652. case 247 /* TypeAliasDeclaration */:
  134653. case 248 /* EnumDeclaration */:
  134654. case 249 /* ModuleDeclaration */:
  134655. case 253 /* ImportEqualsDeclaration */:
  134656. case 263 /* ExportSpecifier */:
  134657. case 258 /* ImportSpecifier */:
  134658. case 255 /* ImportClause */:
  134659. case 256 /* NamespaceImport */:
  134660. case 163 /* GetAccessor */:
  134661. case 164 /* SetAccessor */:
  134662. case 173 /* TypeLiteral */:
  134663. addDeclaration(node);
  134664. ts.forEachChild(node, visit);
  134665. break;
  134666. case 156 /* Parameter */:
  134667. // Only consider parameter properties
  134668. if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
  134669. break;
  134670. }
  134671. // falls through
  134672. case 242 /* VariableDeclaration */:
  134673. case 191 /* BindingElement */: {
  134674. var decl = node;
  134675. if (ts.isBindingPattern(decl.name)) {
  134676. ts.forEachChild(decl.name, visit);
  134677. break;
  134678. }
  134679. if (decl.initializer) {
  134680. visit(decl.initializer);
  134681. }
  134682. }
  134683. // falls through
  134684. case 284 /* EnumMember */:
  134685. case 159 /* PropertyDeclaration */:
  134686. case 158 /* PropertySignature */:
  134687. addDeclaration(node);
  134688. break;
  134689. case 260 /* ExportDeclaration */:
  134690. // Handle named exports case e.g.:
  134691. // export {a, b as B} from "mod";
  134692. var exportDeclaration = node;
  134693. if (exportDeclaration.exportClause) {
  134694. if (ts.isNamedExports(exportDeclaration.exportClause)) {
  134695. ts.forEach(exportDeclaration.exportClause.elements, visit);
  134696. }
  134697. else {
  134698. visit(exportDeclaration.exportClause.name);
  134699. }
  134700. }
  134701. break;
  134702. case 254 /* ImportDeclaration */:
  134703. var importClause = node.importClause;
  134704. if (importClause) {
  134705. // Handle default import case e.g.:
  134706. // import d from "mod";
  134707. if (importClause.name) {
  134708. addDeclaration(importClause.name);
  134709. }
  134710. // Handle named bindings in imports e.g.:
  134711. // import * as NS from "mod";
  134712. // import {a, b as B} from "mod";
  134713. if (importClause.namedBindings) {
  134714. if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
  134715. addDeclaration(importClause.namedBindings);
  134716. }
  134717. else {
  134718. ts.forEach(importClause.namedBindings.elements, visit);
  134719. }
  134720. }
  134721. }
  134722. break;
  134723. case 209 /* BinaryExpression */:
  134724. if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) {
  134725. addDeclaration(node);
  134726. }
  134727. // falls through
  134728. default:
  134729. ts.forEachChild(node, visit);
  134730. }
  134731. }
  134732. };
  134733. return SourceFileObject;
  134734. }(NodeObject));
  134735. var SourceMapSourceObject = /** @class */ (function () {
  134736. function SourceMapSourceObject(fileName, text, skipTrivia) {
  134737. this.fileName = fileName;
  134738. this.text = text;
  134739. this.skipTrivia = skipTrivia;
  134740. }
  134741. SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) {
  134742. return ts.getLineAndCharacterOfPosition(this, pos);
  134743. };
  134744. return SourceMapSourceObject;
  134745. }());
  134746. function getServicesObjectAllocator() {
  134747. return {
  134748. getNodeConstructor: function () { return NodeObject; },
  134749. getTokenConstructor: function () { return TokenObject; },
  134750. getIdentifierConstructor: function () { return IdentifierObject; },
  134751. getPrivateIdentifierConstructor: function () { return PrivateIdentifierObject; },
  134752. getSourceFileConstructor: function () { return SourceFileObject; },
  134753. getSymbolConstructor: function () { return SymbolObject; },
  134754. getTypeConstructor: function () { return TypeObject; },
  134755. getSignatureConstructor: function () { return SignatureObject; },
  134756. getSourceMapSourceConstructor: function () { return SourceMapSourceObject; },
  134757. };
  134758. }
  134759. function toEditorSettings(optionsAsMap) {
  134760. var allPropertiesAreCamelCased = true;
  134761. for (var key in optionsAsMap) {
  134762. if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
  134763. allPropertiesAreCamelCased = false;
  134764. break;
  134765. }
  134766. }
  134767. if (allPropertiesAreCamelCased) {
  134768. return optionsAsMap;
  134769. }
  134770. var settings = {};
  134771. for (var key in optionsAsMap) {
  134772. if (ts.hasProperty(optionsAsMap, key)) {
  134773. var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
  134774. settings[newKey] = optionsAsMap[key];
  134775. }
  134776. }
  134777. return settings;
  134778. }
  134779. ts.toEditorSettings = toEditorSettings;
  134780. function isCamelCase(s) {
  134781. return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
  134782. }
  134783. function displayPartsToString(displayParts) {
  134784. if (displayParts) {
  134785. return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
  134786. }
  134787. return "";
  134788. }
  134789. ts.displayPartsToString = displayPartsToString;
  134790. function getDefaultCompilerOptions() {
  134791. // Always default to "ScriptTarget.ES5" for the language service
  134792. return {
  134793. target: 1 /* ES5 */,
  134794. jsx: 1 /* Preserve */
  134795. };
  134796. }
  134797. ts.getDefaultCompilerOptions = getDefaultCompilerOptions;
  134798. function getSupportedCodeFixes() {
  134799. return ts.codefix.getSupportedErrorCodes();
  134800. }
  134801. ts.getSupportedCodeFixes = getSupportedCodeFixes;
  134802. // Cache host information about script Should be refreshed
  134803. // at each language service public entry point, since we don't know when
  134804. // the set of scripts handled by the host changes.
  134805. var HostCache = /** @class */ (function () {
  134806. function HostCache(host, getCanonicalFileName) {
  134807. this.host = host;
  134808. // script id => script index
  134809. this.currentDirectory = host.getCurrentDirectory();
  134810. this.fileNameToEntry = ts.createMap();
  134811. // Initialize the list with the root file names
  134812. var rootFileNames = host.getScriptFileNames();
  134813. for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
  134814. var fileName = rootFileNames_1[_i];
  134815. this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName));
  134816. }
  134817. // store the compilation settings
  134818. this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions();
  134819. }
  134820. HostCache.prototype.compilationSettings = function () {
  134821. return this._compilationSettings;
  134822. };
  134823. HostCache.prototype.getProjectReferences = function () {
  134824. return this.host.getProjectReferences && this.host.getProjectReferences();
  134825. };
  134826. HostCache.prototype.createEntry = function (fileName, path) {
  134827. var entry;
  134828. var scriptSnapshot = this.host.getScriptSnapshot(fileName);
  134829. if (scriptSnapshot) {
  134830. entry = {
  134831. hostFileName: fileName,
  134832. version: this.host.getScriptVersion(fileName),
  134833. scriptSnapshot: scriptSnapshot,
  134834. scriptKind: ts.getScriptKind(fileName, this.host)
  134835. };
  134836. }
  134837. else {
  134838. entry = fileName;
  134839. }
  134840. this.fileNameToEntry.set(path, entry);
  134841. return entry;
  134842. };
  134843. HostCache.prototype.getEntryByPath = function (path) {
  134844. return this.fileNameToEntry.get(path);
  134845. };
  134846. HostCache.prototype.getHostFileInformation = function (path) {
  134847. var entry = this.fileNameToEntry.get(path);
  134848. return !ts.isString(entry) ? entry : undefined;
  134849. };
  134850. HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) {
  134851. var info = this.getEntryByPath(path) || this.createEntry(fileName, path);
  134852. return ts.isString(info) ? undefined : info; // TODO: GH#18217
  134853. };
  134854. HostCache.prototype.getRootFileNames = function () {
  134855. var names = [];
  134856. this.fileNameToEntry.forEach(function (entry) {
  134857. if (ts.isString(entry)) {
  134858. names.push(entry);
  134859. }
  134860. else {
  134861. names.push(entry.hostFileName);
  134862. }
  134863. });
  134864. return names;
  134865. };
  134866. HostCache.prototype.getVersion = function (path) {
  134867. var file = this.getHostFileInformation(path);
  134868. return (file && file.version); // TODO: GH#18217
  134869. };
  134870. HostCache.prototype.getScriptSnapshot = function (path) {
  134871. var file = this.getHostFileInformation(path);
  134872. return (file && file.scriptSnapshot); // TODO: GH#18217
  134873. };
  134874. return HostCache;
  134875. }());
  134876. var SyntaxTreeCache = /** @class */ (function () {
  134877. function SyntaxTreeCache(host) {
  134878. this.host = host;
  134879. }
  134880. SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) {
  134881. var scriptSnapshot = this.host.getScriptSnapshot(fileName);
  134882. if (!scriptSnapshot) {
  134883. // The host does not know about this file.
  134884. throw new Error("Could not find file: '" + fileName + "'.");
  134885. }
  134886. var scriptKind = ts.getScriptKind(fileName, this.host);
  134887. var version = this.host.getScriptVersion(fileName);
  134888. var sourceFile;
  134889. if (this.currentFileName !== fileName) {
  134890. // This is a new file, just parse it
  134891. sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 99 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
  134892. }
  134893. else if (this.currentFileVersion !== version) {
  134894. // This is the same file, just a newer version. Incrementally parse the file.
  134895. var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot);
  134896. sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange);
  134897. }
  134898. if (sourceFile) {
  134899. // All done, ensure state is up to date
  134900. this.currentFileVersion = version;
  134901. this.currentFileName = fileName;
  134902. this.currentFileScriptSnapshot = scriptSnapshot;
  134903. this.currentSourceFile = sourceFile;
  134904. }
  134905. return this.currentSourceFile;
  134906. };
  134907. return SyntaxTreeCache;
  134908. }());
  134909. function setSourceFileFields(sourceFile, scriptSnapshot, version) {
  134910. sourceFile.version = version;
  134911. sourceFile.scriptSnapshot = scriptSnapshot;
  134912. }
  134913. function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) {
  134914. var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind);
  134915. setSourceFileFields(sourceFile, scriptSnapshot, version);
  134916. return sourceFile;
  134917. }
  134918. ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile;
  134919. function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) {
  134920. // If we were given a text change range, and our version or open-ness changed, then
  134921. // incrementally parse this file.
  134922. if (textChangeRange) {
  134923. if (version !== sourceFile.version) {
  134924. var newText = void 0;
  134925. // grab the fragment from the beginning of the original text to the beginning of the span
  134926. var prefix = textChangeRange.span.start !== 0
  134927. ? sourceFile.text.substr(0, textChangeRange.span.start)
  134928. : "";
  134929. // grab the fragment from the end of the span till the end of the original text
  134930. var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length
  134931. ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span))
  134932. : "";
  134933. if (textChangeRange.newLength === 0) {
  134934. // edit was a deletion - just combine prefix and suffix
  134935. newText = prefix && suffix ? prefix + suffix : prefix || suffix;
  134936. }
  134937. else {
  134938. // it was actual edit, fetch the fragment of new text that correspond to new span
  134939. var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength);
  134940. // combine prefix, changed text and suffix
  134941. newText = prefix && suffix
  134942. ? prefix + changedText + suffix
  134943. : prefix
  134944. ? (prefix + changedText)
  134945. : (changedText + suffix);
  134946. }
  134947. var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
  134948. setSourceFileFields(newSourceFile, scriptSnapshot, version);
  134949. // after incremental parsing nameTable might not be up-to-date
  134950. // drop it so it can be lazily recreated later
  134951. newSourceFile.nameTable = undefined;
  134952. // dispose all resources held by old script snapshot
  134953. if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
  134954. if (sourceFile.scriptSnapshot.dispose) {
  134955. sourceFile.scriptSnapshot.dispose();
  134956. }
  134957. sourceFile.scriptSnapshot = undefined;
  134958. }
  134959. return newSourceFile;
  134960. }
  134961. }
  134962. // Otherwise, just create a new source file.
  134963. return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind);
  134964. }
  134965. ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile;
  134966. var CancellationTokenObject = /** @class */ (function () {
  134967. function CancellationTokenObject(cancellationToken) {
  134968. this.cancellationToken = cancellationToken;
  134969. }
  134970. CancellationTokenObject.prototype.isCancellationRequested = function () {
  134971. return !!this.cancellationToken && this.cancellationToken.isCancellationRequested();
  134972. };
  134973. CancellationTokenObject.prototype.throwIfCancellationRequested = function () {
  134974. if (this.isCancellationRequested()) {
  134975. throw new ts.OperationCanceledException();
  134976. }
  134977. };
  134978. return CancellationTokenObject;
  134979. }());
  134980. /* @internal */
  134981. /** A cancellation that throttles calls to the host */
  134982. var ThrottledCancellationToken = /** @class */ (function () {
  134983. function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) {
  134984. if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; }
  134985. this.hostCancellationToken = hostCancellationToken;
  134986. this.throttleWaitMilliseconds = throttleWaitMilliseconds;
  134987. // Store when we last tried to cancel. Checking cancellation can be expensive (as we have
  134988. // to marshall over to the host layer). So we only bother actually checking once enough
  134989. // time has passed.
  134990. this.lastCancellationCheckTime = 0;
  134991. }
  134992. ThrottledCancellationToken.prototype.isCancellationRequested = function () {
  134993. var time = ts.timestamp();
  134994. var duration = Math.abs(time - this.lastCancellationCheckTime);
  134995. if (duration >= this.throttleWaitMilliseconds) {
  134996. // Check no more than once every throttle wait milliseconds
  134997. this.lastCancellationCheckTime = time;
  134998. return this.hostCancellationToken.isCancellationRequested();
  134999. }
  135000. return false;
  135001. };
  135002. ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () {
  135003. if (this.isCancellationRequested()) {
  135004. throw new ts.OperationCanceledException();
  135005. }
  135006. };
  135007. return ThrottledCancellationToken;
  135008. }());
  135009. ts.ThrottledCancellationToken = ThrottledCancellationToken;
  135010. function createLanguageService(host, documentRegistry, syntaxOnly) {
  135011. var _a;
  135012. if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
  135013. if (syntaxOnly === void 0) { syntaxOnly = false; }
  135014. var syntaxTreeCache = new SyntaxTreeCache(host);
  135015. var program;
  135016. var lastProjectVersion;
  135017. var lastTypesRootVersion = 0;
  135018. var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken());
  135019. var currentDirectory = host.getCurrentDirectory();
  135020. // Check if the localized messages json is set, otherwise query the host for it
  135021. if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) {
  135022. ts.setLocalizedDiagnosticMessages(host.getLocalizedDiagnosticMessages());
  135023. }
  135024. function log(message) {
  135025. if (host.log) {
  135026. host.log(message);
  135027. }
  135028. }
  135029. var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
  135030. var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
  135031. var sourceMapper = ts.getSourceMapper({
  135032. useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
  135033. getCurrentDirectory: function () { return currentDirectory; },
  135034. getProgram: getProgram,
  135035. fileExists: ts.maybeBind(host, host.fileExists),
  135036. readFile: ts.maybeBind(host, host.readFile),
  135037. getDocumentPositionMapper: ts.maybeBind(host, host.getDocumentPositionMapper),
  135038. getSourceFileLike: ts.maybeBind(host, host.getSourceFileLike),
  135039. log: log
  135040. });
  135041. function getValidSourceFile(fileName) {
  135042. var sourceFile = program.getSourceFile(fileName);
  135043. if (!sourceFile) {
  135044. var error = new Error("Could not find source file: '" + fileName + "'.");
  135045. // We've been having trouble debugging this, so attach sidecar data for the tsserver log.
  135046. // See https://github.com/microsoft/TypeScript/issues/30180.
  135047. error.ProgramFiles = program.getSourceFiles().map(function (f) { return f.fileName; });
  135048. throw error;
  135049. }
  135050. return sourceFile;
  135051. }
  135052. function synchronizeHostData() {
  135053. ts.Debug.assert(!syntaxOnly);
  135054. // perform fast check if host supports it
  135055. if (host.getProjectVersion) {
  135056. var hostProjectVersion = host.getProjectVersion();
  135057. if (hostProjectVersion) {
  135058. if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) {
  135059. return;
  135060. }
  135061. lastProjectVersion = hostProjectVersion;
  135062. }
  135063. }
  135064. var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
  135065. if (lastTypesRootVersion !== typeRootsVersion) {
  135066. log("TypeRoots version has changed; provide new program");
  135067. program = undefined; // TODO: GH#18217
  135068. lastTypesRootVersion = typeRootsVersion;
  135069. }
  135070. // Get a fresh cache of the host information
  135071. var hostCache = new HostCache(host, getCanonicalFileName);
  135072. var rootFileNames = hostCache.getRootFileNames();
  135073. var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
  135074. var projectReferences = hostCache.getProjectReferences();
  135075. // If the program is already up-to-date, we can reuse it
  135076. if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
  135077. return;
  135078. }
  135079. // IMPORTANT - It is critical from this moment onward that we do not check
  135080. // cancellation tokens. We are about to mutate source files from a previous program
  135081. // instance. If we cancel midway through, we may end up in an inconsistent state where
  135082. // the program points to old source files that have been invalidated because of
  135083. // incremental parsing.
  135084. var newSettings = hostCache.compilationSettings();
  135085. // Now create a new compiler
  135086. var compilerHost = {
  135087. getSourceFile: getOrCreateSourceFile,
  135088. getSourceFileByPath: getOrCreateSourceFileByPath,
  135089. getCancellationToken: function () { return cancellationToken; },
  135090. getCanonicalFileName: getCanonicalFileName,
  135091. useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
  135092. getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); },
  135093. getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
  135094. writeFile: ts.noop,
  135095. getCurrentDirectory: function () { return currentDirectory; },
  135096. fileExists: fileExists,
  135097. readFile: readFile,
  135098. realpath: host.realpath && (function (path) { return host.realpath(path); }),
  135099. directoryExists: function (directoryName) {
  135100. return ts.directoryProbablyExists(directoryName, host);
  135101. },
  135102. getDirectories: function (path) {
  135103. return host.getDirectories ? host.getDirectories(path) : [];
  135104. },
  135105. readDirectory: function (path, extensions, exclude, include, depth) {
  135106. ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
  135107. return host.readDirectory(path, extensions, exclude, include, depth);
  135108. },
  135109. onReleaseOldSourceFile: onReleaseOldSourceFile,
  135110. hasInvalidatedResolution: hasInvalidatedResolution,
  135111. hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames
  135112. };
  135113. if (host.trace) {
  135114. compilerHost.trace = function (message) { return host.trace(message); };
  135115. }
  135116. if (host.resolveModuleNames) {
  135117. compilerHost.resolveModuleNames = function () {
  135118. var args = [];
  135119. for (var _i = 0; _i < arguments.length; _i++) {
  135120. args[_i] = arguments[_i];
  135121. }
  135122. return host.resolveModuleNames.apply(host, args);
  135123. };
  135124. }
  135125. if (host.resolveTypeReferenceDirectives) {
  135126. compilerHost.resolveTypeReferenceDirectives = function () {
  135127. var args = [];
  135128. for (var _i = 0; _i < arguments.length; _i++) {
  135129. args[_i] = arguments[_i];
  135130. }
  135131. return host.resolveTypeReferenceDirectives.apply(host, args);
  135132. };
  135133. }
  135134. if (host.setResolvedProjectReferenceCallbacks) {
  135135. compilerHost.setResolvedProjectReferenceCallbacks = function (callbacks) { return host.setResolvedProjectReferenceCallbacks(callbacks); };
  135136. }
  135137. if (host.useSourceOfProjectReferenceRedirect) {
  135138. compilerHost.useSourceOfProjectReferenceRedirect = function () { return host.useSourceOfProjectReferenceRedirect(); };
  135139. }
  135140. var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
  135141. var options = {
  135142. rootNames: rootFileNames,
  135143. options: newSettings,
  135144. host: compilerHost,
  135145. oldProgram: program,
  135146. projectReferences: projectReferences
  135147. };
  135148. program = ts.createProgram(options);
  135149. // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
  135150. // It needs to be cleared to allow all collected snapshots to be released
  135151. hostCache = undefined;
  135152. // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above,
  135153. // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during
  135154. // the course of whatever called `synchronizeHostData`
  135155. sourceMapper.clearCache();
  135156. // Make sure all the nodes in the program are both bound, and have their parent
  135157. // pointers set property.
  135158. program.getTypeChecker();
  135159. return;
  135160. function fileExists(fileName) {
  135161. var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  135162. var entry = hostCache && hostCache.getEntryByPath(path);
  135163. return entry ?
  135164. !ts.isString(entry) :
  135165. (!!host.fileExists && host.fileExists(fileName));
  135166. }
  135167. function readFile(fileName) {
  135168. // stub missing host functionality
  135169. var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
  135170. var entry = hostCache && hostCache.getEntryByPath(path);
  135171. if (entry) {
  135172. return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot);
  135173. }
  135174. return host.readFile && host.readFile(fileName);
  135175. }
  135176. // Release any files we have acquired in the old program but are
  135177. // not part of the new program.
  135178. function onReleaseOldSourceFile(oldSourceFile, oldOptions) {
  135179. var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions);
  135180. documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey);
  135181. }
  135182. function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
  135183. return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile);
  135184. }
  135185. function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) {
  135186. ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
  135187. // The program is asking for this file, check first if the host can locate it.
  135188. // If the host can not locate the file, then it does not exist. return undefined
  135189. // to the program to allow reporting of errors for missing files.
  135190. var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path);
  135191. if (!hostFileInformation) {
  135192. return undefined;
  135193. }
  135194. // Check if the language version has changed since we last created a program; if they are the same,
  135195. // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile
  135196. // can not be reused. we have to dump all syntax trees and create new ones.
  135197. if (!shouldCreateNewSourceFile) {
  135198. // Check if the old program had this file already
  135199. var oldSourceFile = program && program.getSourceFileByPath(path);
  135200. if (oldSourceFile) {
  135201. // We already had a source file for this file name. Go to the registry to
  135202. // ensure that we get the right up to date version of it. We need this to
  135203. // address the following race-condition. Specifically, say we have the following:
  135204. //
  135205. // LS1
  135206. // \
  135207. // DocumentRegistry
  135208. // /
  135209. // LS2
  135210. //
  135211. // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates
  135212. // it's version of 'foo.ts' to version 2. This will cause LS2 and the
  135213. // DocumentRegistry to have version 2 of the document. HOwever, LS1 will
  135214. // have version 1. And *importantly* this source file will be *corrupt*.
  135215. // The act of creating version 2 of the file irrevocably damages the version
  135216. // 1 file.
  135217. //
  135218. // So, later when we call into LS1, we need to make sure that it doesn't use
  135219. // it's source file any more, and instead defers to DocumentRegistry to get
  135220. // either version 1, version 2 (or some other version) depending on what the
  135221. // host says should be used.
  135222. // We do not support the scenario where a host can modify a registered
  135223. // file's script kind, i.e. in one project some file is treated as ".ts"
  135224. // and in another as ".js"
  135225. ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path);
  135226. return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
  135227. }
  135228. // We didn't already have the file. Fall through and acquire it from the registry.
  135229. }
  135230. // Could not find this file in the old program, create a new SourceFile for it.
  135231. return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
  135232. }
  135233. }
  135234. // TODO: GH#18217 frequently asserted as defined
  135235. function getProgram() {
  135236. if (syntaxOnly) {
  135237. ts.Debug.assert(program === undefined);
  135238. return undefined;
  135239. }
  135240. synchronizeHostData();
  135241. return program;
  135242. }
  135243. function cleanupSemanticCache() {
  135244. program = undefined; // TODO: GH#18217
  135245. }
  135246. function dispose() {
  135247. if (program) {
  135248. ts.forEach(program.getSourceFiles(), function (f) {
  135249. return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions());
  135250. });
  135251. program = undefined; // TODO: GH#18217
  135252. }
  135253. host = undefined;
  135254. }
  135255. /// Diagnostics
  135256. function getSyntacticDiagnostics(fileName) {
  135257. synchronizeHostData();
  135258. return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice();
  135259. }
  135260. /**
  135261. * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors
  135262. * If '-d' enabled, report both semantic and emitter errors
  135263. */
  135264. function getSemanticDiagnostics(fileName) {
  135265. synchronizeHostData();
  135266. var targetSourceFile = getValidSourceFile(fileName);
  135267. // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
  135268. // Therefore only get diagnostics for given file.
  135269. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
  135270. if (!ts.getEmitDeclarations(program.getCompilerOptions())) {
  135271. return semanticDiagnostics.slice();
  135272. }
  135273. // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
  135274. var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
  135275. return __spreadArrays(semanticDiagnostics, declarationDiagnostics);
  135276. }
  135277. function getSuggestionDiagnostics(fileName) {
  135278. synchronizeHostData();
  135279. return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken);
  135280. }
  135281. function getCompilerOptionsDiagnostics() {
  135282. synchronizeHostData();
  135283. return __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken));
  135284. }
  135285. function getCompletionsAtPosition(fileName, position, options) {
  135286. if (options === void 0) { options = ts.emptyOptions; }
  135287. // Convert from deprecated options names to new names
  135288. var fullPreferences = __assign(__assign({}, ts.identity(options)), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions });
  135289. synchronizeHostData();
  135290. return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter);
  135291. }
  135292. function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) {
  135293. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135294. synchronizeHostData();
  135295. return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217
  135296. preferences, cancellationToken);
  135297. }
  135298. function getCompletionEntrySymbol(fileName, position, name, source) {
  135299. synchronizeHostData();
  135300. return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host);
  135301. }
  135302. function getQuickInfoAtPosition(fileName, position) {
  135303. synchronizeHostData();
  135304. var sourceFile = getValidSourceFile(fileName);
  135305. var node = ts.getTouchingPropertyName(sourceFile, position);
  135306. if (node === sourceFile) {
  135307. // Avoid giving quickInfo for the sourceFile as a whole.
  135308. return undefined;
  135309. }
  135310. var typeChecker = program.getTypeChecker();
  135311. var nodeForQuickInfo = getNodeForQuickInfo(node);
  135312. var symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker);
  135313. if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
  135314. var type_2 = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : undefined;
  135315. return type_2 && {
  135316. kind: "" /* unknown */,
  135317. kindModifiers: "" /* none */,
  135318. textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
  135319. displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }),
  135320. documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined,
  135321. tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined
  135322. };
  135323. }
  135324. var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
  135325. return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(nodeForQuickInfo), nodeForQuickInfo);
  135326. }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
  135327. return {
  135328. kind: symbolKind,
  135329. kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
  135330. textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
  135331. displayParts: displayParts,
  135332. documentation: documentation,
  135333. tags: tags,
  135334. };
  135335. }
  135336. function getNodeForQuickInfo(node) {
  135337. if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) {
  135338. return node.parent.expression;
  135339. }
  135340. return node;
  135341. }
  135342. function shouldGetType(sourceFile, node, position) {
  135343. switch (node.kind) {
  135344. case 75 /* Identifier */:
  135345. return !ts.isLabelName(node) && !ts.isTagName(node);
  135346. case 194 /* PropertyAccessExpression */:
  135347. case 153 /* QualifiedName */:
  135348. // Don't return quickInfo if inside the comment in `a/**/.b`
  135349. return !ts.isInComment(sourceFile, position);
  135350. case 104 /* ThisKeyword */:
  135351. case 183 /* ThisType */:
  135352. case 102 /* SuperKeyword */:
  135353. return true;
  135354. default:
  135355. return false;
  135356. }
  135357. }
  135358. /// Goto definition
  135359. function getDefinitionAtPosition(fileName, position) {
  135360. synchronizeHostData();
  135361. return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position);
  135362. }
  135363. function getDefinitionAndBoundSpan(fileName, position) {
  135364. synchronizeHostData();
  135365. return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position);
  135366. }
  135367. function getTypeDefinitionAtPosition(fileName, position) {
  135368. synchronizeHostData();
  135369. return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
  135370. }
  135371. /// Goto implementation
  135372. function getImplementationAtPosition(fileName, position) {
  135373. synchronizeHostData();
  135374. return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
  135375. }
  135376. /// References and Occurrences
  135377. function getOccurrencesAtPosition(fileName, position) {
  135378. return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return (__assign(__assign({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, isDefinition: false }, highlightSpan.isInString && { isInString: true }), highlightSpan.contextSpan && { contextSpan: highlightSpan.contextSpan })); }); });
  135379. }
  135380. function getDocumentHighlights(fileName, position, filesToSearch) {
  135381. var normalizedFileName = ts.normalizePath(fileName);
  135382. ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; }));
  135383. synchronizeHostData();
  135384. var sourceFilesToSearch = ts.mapDefined(filesToSearch, function (fileName) { return program.getSourceFile(fileName); });
  135385. var sourceFile = getValidSourceFile(fileName);
  135386. return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
  135387. }
  135388. function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) {
  135389. synchronizeHostData();
  135390. var sourceFile = getValidSourceFile(fileName);
  135391. var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position));
  135392. if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) {
  135393. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
  135394. return [openingElement, closingElement].map(function (node) {
  135395. var textSpan = ts.createTextSpanFromNode(node.tagName, sourceFile);
  135396. return __assign({ fileName: sourceFile.fileName, textSpan: textSpan }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, node.parent));
  135397. });
  135398. }
  135399. else {
  135400. return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, use: 2 /* Rename */ }, function (entry, originalNode, checker) { return ts.FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false); });
  135401. }
  135402. }
  135403. function getReferencesAtPosition(fileName, position) {
  135404. synchronizeHostData();
  135405. return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: 1 /* References */ }, ts.FindAllReferences.toReferenceEntry);
  135406. }
  135407. function getReferencesWorker(node, position, options, cb) {
  135408. synchronizeHostData();
  135409. // Exclude default library when renaming as commonly user don't want to change that file.
  135410. var sourceFiles = options && options.use === 2 /* Rename */
  135411. ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); })
  135412. : program.getSourceFiles();
  135413. return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb);
  135414. }
  135415. function findReferences(fileName, position) {
  135416. synchronizeHostData();
  135417. return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
  135418. }
  135419. function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
  135420. if (excludeDtsFiles === void 0) { excludeDtsFiles = false; }
  135421. synchronizeHostData();
  135422. var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
  135423. return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
  135424. }
  135425. function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) {
  135426. synchronizeHostData();
  135427. var sourceFile = getValidSourceFile(fileName);
  135428. var customTransformers = host.getCustomTransformers && host.getCustomTransformers();
  135429. return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit);
  135430. }
  135431. // Signature help
  135432. /**
  135433. * This is a semantic operation.
  135434. */
  135435. function getSignatureHelpItems(fileName, position, _a) {
  135436. var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason;
  135437. synchronizeHostData();
  135438. var sourceFile = getValidSourceFile(fileName);
  135439. return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
  135440. }
  135441. /// Syntactic features
  135442. function getNonBoundSourceFile(fileName) {
  135443. return syntaxTreeCache.getCurrentSourceFile(fileName);
  135444. }
  135445. function getNameOrDottedNameSpan(fileName, startPos, _endPos) {
  135446. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135447. // Get node at the location
  135448. var node = ts.getTouchingPropertyName(sourceFile, startPos);
  135449. if (node === sourceFile) {
  135450. return undefined;
  135451. }
  135452. switch (node.kind) {
  135453. case 194 /* PropertyAccessExpression */:
  135454. case 153 /* QualifiedName */:
  135455. case 10 /* StringLiteral */:
  135456. case 91 /* FalseKeyword */:
  135457. case 106 /* TrueKeyword */:
  135458. case 100 /* NullKeyword */:
  135459. case 102 /* SuperKeyword */:
  135460. case 104 /* ThisKeyword */:
  135461. case 183 /* ThisType */:
  135462. case 75 /* Identifier */:
  135463. break;
  135464. // Cant create the text span
  135465. default:
  135466. return undefined;
  135467. }
  135468. var nodeForStartPos = node;
  135469. while (true) {
  135470. if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) {
  135471. // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node
  135472. nodeForStartPos = nodeForStartPos.parent;
  135473. }
  135474. else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) {
  135475. // If this is name of a module declarations, check if this is right side of dotted module name
  135476. // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of
  135477. // Then this name is name from dotted module
  135478. if (nodeForStartPos.parent.parent.kind === 249 /* ModuleDeclaration */ &&
  135479. nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
  135480. // Use parent module declarations name for start pos
  135481. nodeForStartPos = nodeForStartPos.parent.parent.name;
  135482. }
  135483. else {
  135484. // We have to use this name for start pos
  135485. break;
  135486. }
  135487. }
  135488. else {
  135489. // Is not a member expression so we have found the node for start pos
  135490. break;
  135491. }
  135492. }
  135493. return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd());
  135494. }
  135495. function getBreakpointStatementAtPosition(fileName, position) {
  135496. // doesn't use compiler - no need to synchronize with host
  135497. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135498. return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position);
  135499. }
  135500. function getNavigationBarItems(fileName) {
  135501. return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
  135502. }
  135503. function getNavigationTree(fileName) {
  135504. return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
  135505. }
  135506. function isTsOrTsxFile(fileName) {
  135507. var kind = ts.getScriptKind(fileName, host);
  135508. return kind === 3 /* TS */ || kind === 4 /* TSX */;
  135509. }
  135510. function getSemanticClassifications(fileName, span) {
  135511. if (!isTsOrTsxFile(fileName)) {
  135512. // do not run semantic classification on non-ts-or-tsx files
  135513. return [];
  135514. }
  135515. synchronizeHostData();
  135516. return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
  135517. }
  135518. function getEncodedSemanticClassifications(fileName, span) {
  135519. if (!isTsOrTsxFile(fileName)) {
  135520. // do not run semantic classification on non-ts-or-tsx files
  135521. return { spans: [], endOfLineState: 0 /* None */ };
  135522. }
  135523. synchronizeHostData();
  135524. return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
  135525. }
  135526. function getSyntacticClassifications(fileName, span) {
  135527. // doesn't use compiler - no need to synchronize with host
  135528. return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
  135529. }
  135530. function getEncodedSyntacticClassifications(fileName, span) {
  135531. // doesn't use compiler - no need to synchronize with host
  135532. return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
  135533. }
  135534. function getOutliningSpans(fileName) {
  135535. // doesn't use compiler - no need to synchronize with host
  135536. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135537. return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken);
  135538. }
  135539. var braceMatching = ts.createMapFromTemplate((_a = {},
  135540. _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */,
  135541. _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */,
  135542. _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */,
  135543. _a[31 /* GreaterThanToken */] = 29 /* LessThanToken */,
  135544. _a));
  135545. braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); });
  135546. function getBraceMatchingAtPosition(fileName, position) {
  135547. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135548. var token = ts.getTouchingToken(sourceFile, position);
  135549. var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined;
  135550. var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile);
  135551. // We want to order the braces when we return the result.
  135552. return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray;
  135553. }
  135554. function getIndentationAtPosition(fileName, position, editorOptions) {
  135555. var start = ts.timestamp();
  135556. var settings = toEditorSettings(editorOptions);
  135557. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135558. log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
  135559. start = ts.timestamp();
  135560. var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
  135561. log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start));
  135562. return result;
  135563. }
  135564. function getFormattingEditsForRange(fileName, start, end, options) {
  135565. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135566. return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options)));
  135567. }
  135568. function getFormattingEditsForDocument(fileName, options) {
  135569. return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options)));
  135570. }
  135571. function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
  135572. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135573. var formatContext = ts.formatting.getFormatContext(toEditorSettings(options));
  135574. if (!ts.isInComment(sourceFile, position)) {
  135575. switch (key) {
  135576. case "{":
  135577. return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext);
  135578. case "}":
  135579. return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext);
  135580. case ";":
  135581. return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext);
  135582. case "\n":
  135583. return ts.formatting.formatOnEnter(position, sourceFile, formatContext);
  135584. }
  135585. }
  135586. return [];
  135587. }
  135588. function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) {
  135589. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135590. synchronizeHostData();
  135591. var sourceFile = getValidSourceFile(fileName);
  135592. var span = ts.createTextSpanFromBounds(start, end);
  135593. var formatContext = ts.formatting.getFormatContext(formatOptions);
  135594. return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) {
  135595. cancellationToken.throwIfCancellationRequested();
  135596. return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
  135597. });
  135598. }
  135599. function getCombinedCodeFix(scope, fixId, formatOptions, preferences) {
  135600. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135601. synchronizeHostData();
  135602. ts.Debug.assert(scope.type === "file");
  135603. var sourceFile = getValidSourceFile(scope.fileName);
  135604. var formatContext = ts.formatting.getFormatContext(formatOptions);
  135605. return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
  135606. }
  135607. function organizeImports(scope, formatOptions, preferences) {
  135608. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135609. synchronizeHostData();
  135610. ts.Debug.assert(scope.type === "file");
  135611. var sourceFile = getValidSourceFile(scope.fileName);
  135612. var formatContext = ts.formatting.getFormatContext(formatOptions);
  135613. return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences);
  135614. }
  135615. function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) {
  135616. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135617. return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper);
  135618. }
  135619. function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) {
  135620. var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName;
  135621. return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a); })) : applySingleCodeActionCommand(action);
  135622. }
  135623. function applySingleCodeActionCommand(action) {
  135624. var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); };
  135625. ts.Debug.assertEqual(action.type, "install package");
  135626. return host.installPackage
  135627. ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName })
  135628. : Promise.reject("Host does not implement `installPackage`");
  135629. }
  135630. function getDocCommentTemplateAtPosition(fileName, position) {
  135631. return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position);
  135632. }
  135633. function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
  135634. // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too
  135635. // expensive to do during typing scenarios
  135636. // i.e. whether we're dealing with:
  135637. // var x = new foo<| ( with class foo<T>{} )
  135638. // or
  135639. // var y = 3 <|
  135640. if (openingBrace === 60 /* lessThan */) {
  135641. return false;
  135642. }
  135643. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135644. // Check if in a context where we don't want to perform any insertion
  135645. if (ts.isInString(sourceFile, position)) {
  135646. return false;
  135647. }
  135648. if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) {
  135649. return openingBrace === 123 /* openBrace */;
  135650. }
  135651. if (ts.isInTemplateString(sourceFile, position)) {
  135652. return false;
  135653. }
  135654. switch (openingBrace) {
  135655. case 39 /* singleQuote */:
  135656. case 34 /* doubleQuote */:
  135657. case 96 /* backtick */:
  135658. return !ts.isInComment(sourceFile, position);
  135659. }
  135660. return true;
  135661. }
  135662. function getJsxClosingTagAtPosition(fileName, position) {
  135663. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135664. var token = ts.findPrecedingToken(position, sourceFile);
  135665. if (!token)
  135666. return undefined;
  135667. var element = token.kind === 31 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent
  135668. : ts.isJsxText(token) ? token.parent : undefined;
  135669. if (element && isUnclosedTag(element)) {
  135670. return { newText: "</" + element.openingElement.tagName.getText(sourceFile) + ">" };
  135671. }
  135672. }
  135673. function isUnclosedTag(_a) {
  135674. var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent;
  135675. return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) ||
  135676. ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent);
  135677. }
  135678. function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
  135679. var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
  135680. var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position);
  135681. return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined;
  135682. }
  135683. function getTodoComments(fileName, descriptors) {
  135684. // Note: while getting todo comments seems like a syntactic operation, we actually
  135685. // treat it as a semantic operation here. This is because we expect our host to call
  135686. // this on every single file. If we treat this syntactically, then that will cause
  135687. // us to populate and throw away the tree in our syntax tree cache for each file. By
  135688. // treating this as a semantic operation, we can access any tree without throwing
  135689. // anything away.
  135690. synchronizeHostData();
  135691. var sourceFile = getValidSourceFile(fileName);
  135692. cancellationToken.throwIfCancellationRequested();
  135693. var fileContents = sourceFile.text;
  135694. var result = [];
  135695. // Exclude node_modules files as we don't want to show the todos of external libraries.
  135696. if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) {
  135697. var regExp = getTodoCommentsRegExp();
  135698. var matchArray = void 0;
  135699. while (matchArray = regExp.exec(fileContents)) {
  135700. cancellationToken.throwIfCancellationRequested();
  135701. // If we got a match, here is what the match array will look like. Say the source text is:
  135702. //
  135703. // " // hack 1"
  135704. //
  135705. // The result array with the regexp: will be:
  135706. //
  135707. // ["// hack 1", "// ", "hack 1", undefined, "hack"]
  135708. //
  135709. // Here are the relevant capture groups:
  135710. // 0) The full match for the entire regexp.
  135711. // 1) The preamble to the message portion.
  135712. // 2) The message portion.
  135713. // 3...N) The descriptor that was matched - by index. 'undefined' for each
  135714. // descriptor that didn't match. an actual value if it did match.
  135715. //
  135716. // i.e. 'undefined' in position 3 above means TODO(jason) didn't match.
  135717. // "hack" in position 4 means HACK did match.
  135718. var firstDescriptorCaptureIndex = 3;
  135719. ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
  135720. var preamble = matchArray[1];
  135721. var matchPosition = matchArray.index + preamble.length;
  135722. // OK, we have found a match in the file. This is only an acceptable match if
  135723. // it is contained within a comment.
  135724. if (!ts.isInComment(sourceFile, matchPosition)) {
  135725. continue;
  135726. }
  135727. var descriptor = void 0;
  135728. for (var i = 0; i < descriptors.length; i++) {
  135729. if (matchArray[i + firstDescriptorCaptureIndex]) {
  135730. descriptor = descriptors[i];
  135731. }
  135732. }
  135733. if (descriptor === undefined)
  135734. return ts.Debug.fail();
  135735. // We don't want to match something like 'TODOBY', so we make sure a non
  135736. // letter/digit follows the match.
  135737. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
  135738. continue;
  135739. }
  135740. var message = matchArray[2];
  135741. result.push({ descriptor: descriptor, message: message, position: matchPosition });
  135742. }
  135743. }
  135744. return result;
  135745. function escapeRegExp(str) {
  135746. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  135747. }
  135748. function getTodoCommentsRegExp() {
  135749. // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to
  135750. // filter them out later in the final result array.
  135751. // TODO comments can appear in one of the following forms:
  135752. //
  135753. // 1) // TODO or /////////// TODO
  135754. //
  135755. // 2) /* TODO or /********** TODO
  135756. //
  135757. // 3) /*
  135758. // * TODO
  135759. // */
  135760. //
  135761. // The following three regexps are used to match the start of the text up to the TODO
  135762. // comment portion.
  135763. var singleLineCommentStart = /(?:\/\/+\s*)/.source;
  135764. var multiLineCommentStart = /(?:\/\*+\s*)/.source;
  135765. var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
  135766. // Match any of the above three TODO comment start regexps.
  135767. // Note that the outermost group *is* a capture group. We want to capture the preamble
  135768. // so that we can determine the starting position of the TODO comment match.
  135769. var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
  135770. // Takes the descriptors and forms a regexp that matches them as if they were literals.
  135771. // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be:
  135772. //
  135773. // (?:(TODO\(jason\))|(HACK))
  135774. //
  135775. // Note that the outermost group is *not* a capture group, but the innermost groups
  135776. // *are* capture groups. By capturing the inner literals we can determine after
  135777. // matching which descriptor we are dealing with.
  135778. var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")";
  135779. // After matching a descriptor literal, the following regexp matches the rest of the
  135780. // text up to the end of the line (or */).
  135781. var endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
  135782. var messageRemainder = /(?:.*?)/.source;
  135783. // This is the portion of the match we'll return as part of the TODO comment result. We
  135784. // match the literal portion up to the end of the line or end of comment.
  135785. var messagePortion = "(" + literals + messageRemainder + ")";
  135786. var regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
  135787. // The final regexp will look like this:
  135788. // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim
  135789. // The flags of the regexp are important here.
  135790. // 'g' is so that we are doing a global search and can find matches several times
  135791. // in the input.
  135792. //
  135793. // 'i' is for case insensitivity (We do this to match C# TODO comment code).
  135794. //
  135795. // 'm' is so we can find matches in a multi-line input.
  135796. return new RegExp(regExpString, "gim");
  135797. }
  135798. function isLetterOrDigit(char) {
  135799. return (char >= 97 /* a */ && char <= 122 /* z */) ||
  135800. (char >= 65 /* A */ && char <= 90 /* Z */) ||
  135801. (char >= 48 /* _0 */ && char <= 57 /* _9 */);
  135802. }
  135803. function isNodeModulesFile(path) {
  135804. return ts.stringContains(path, "/node_modules/");
  135805. }
  135806. }
  135807. function getRenameInfo(fileName, position, options) {
  135808. synchronizeHostData();
  135809. return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options);
  135810. }
  135811. function getRefactorContext(file, positionOrRange, preferences, formatOptions) {
  135812. var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1];
  135813. return {
  135814. file: file,
  135815. startPosition: startPosition,
  135816. endPosition: endPosition,
  135817. program: getProgram(),
  135818. host: host,
  135819. formatContext: ts.formatting.getFormatContext(formatOptions),
  135820. cancellationToken: cancellationToken,
  135821. preferences: preferences,
  135822. };
  135823. }
  135824. function getSmartSelectionRange(fileName, position) {
  135825. return ts.SmartSelectionRange.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName));
  135826. }
  135827. function getApplicableRefactors(fileName, positionOrRange, preferences) {
  135828. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135829. synchronizeHostData();
  135830. var file = getValidSourceFile(fileName);
  135831. return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences));
  135832. }
  135833. function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) {
  135834. if (preferences === void 0) { preferences = ts.emptyOptions; }
  135835. synchronizeHostData();
  135836. var file = getValidSourceFile(fileName);
  135837. return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName);
  135838. }
  135839. function prepareCallHierarchy(fileName, position) {
  135840. synchronizeHostData();
  135841. var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position));
  135842. return declarations && ts.mapOneOrMany(declarations, function (declaration) { return ts.CallHierarchy.createCallHierarchyItem(program, declaration); });
  135843. }
  135844. function provideCallHierarchyIncomingCalls(fileName, position) {
  135845. synchronizeHostData();
  135846. var sourceFile = getValidSourceFile(fileName);
  135847. var declaration = ts.firstOrOnly(ts.CallHierarchy.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : ts.getTouchingPropertyName(sourceFile, position)));
  135848. return declaration ? ts.CallHierarchy.getIncomingCalls(program, declaration, cancellationToken) : [];
  135849. }
  135850. function provideCallHierarchyOutgoingCalls(fileName, position) {
  135851. synchronizeHostData();
  135852. var sourceFile = getValidSourceFile(fileName);
  135853. var declaration = ts.firstOrOnly(ts.CallHierarchy.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : ts.getTouchingPropertyName(sourceFile, position)));
  135854. return declaration ? ts.CallHierarchy.getOutgoingCalls(program, declaration) : [];
  135855. }
  135856. return {
  135857. dispose: dispose,
  135858. cleanupSemanticCache: cleanupSemanticCache,
  135859. getSyntacticDiagnostics: getSyntacticDiagnostics,
  135860. getSemanticDiagnostics: getSemanticDiagnostics,
  135861. getSuggestionDiagnostics: getSuggestionDiagnostics,
  135862. getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
  135863. getSyntacticClassifications: getSyntacticClassifications,
  135864. getSemanticClassifications: getSemanticClassifications,
  135865. getEncodedSyntacticClassifications: getEncodedSyntacticClassifications,
  135866. getEncodedSemanticClassifications: getEncodedSemanticClassifications,
  135867. getCompletionsAtPosition: getCompletionsAtPosition,
  135868. getCompletionEntryDetails: getCompletionEntryDetails,
  135869. getCompletionEntrySymbol: getCompletionEntrySymbol,
  135870. getSignatureHelpItems: getSignatureHelpItems,
  135871. getQuickInfoAtPosition: getQuickInfoAtPosition,
  135872. getDefinitionAtPosition: getDefinitionAtPosition,
  135873. getDefinitionAndBoundSpan: getDefinitionAndBoundSpan,
  135874. getImplementationAtPosition: getImplementationAtPosition,
  135875. getTypeDefinitionAtPosition: getTypeDefinitionAtPosition,
  135876. getReferencesAtPosition: getReferencesAtPosition,
  135877. findReferences: findReferences,
  135878. getOccurrencesAtPosition: getOccurrencesAtPosition,
  135879. getDocumentHighlights: getDocumentHighlights,
  135880. getNameOrDottedNameSpan: getNameOrDottedNameSpan,
  135881. getBreakpointStatementAtPosition: getBreakpointStatementAtPosition,
  135882. getNavigateToItems: getNavigateToItems,
  135883. getRenameInfo: getRenameInfo,
  135884. getSmartSelectionRange: getSmartSelectionRange,
  135885. findRenameLocations: findRenameLocations,
  135886. getNavigationBarItems: getNavigationBarItems,
  135887. getNavigationTree: getNavigationTree,
  135888. getOutliningSpans: getOutliningSpans,
  135889. getTodoComments: getTodoComments,
  135890. getBraceMatchingAtPosition: getBraceMatchingAtPosition,
  135891. getIndentationAtPosition: getIndentationAtPosition,
  135892. getFormattingEditsForRange: getFormattingEditsForRange,
  135893. getFormattingEditsForDocument: getFormattingEditsForDocument,
  135894. getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke,
  135895. getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition,
  135896. isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition,
  135897. getJsxClosingTagAtPosition: getJsxClosingTagAtPosition,
  135898. getSpanOfEnclosingComment: getSpanOfEnclosingComment,
  135899. getCodeFixesAtPosition: getCodeFixesAtPosition,
  135900. getCombinedCodeFix: getCombinedCodeFix,
  135901. applyCodeActionCommand: applyCodeActionCommand,
  135902. organizeImports: organizeImports,
  135903. getEditsForFileRename: getEditsForFileRename,
  135904. getEmitOutput: getEmitOutput,
  135905. getNonBoundSourceFile: getNonBoundSourceFile,
  135906. getProgram: getProgram,
  135907. getApplicableRefactors: getApplicableRefactors,
  135908. getEditsForRefactor: getEditsForRefactor,
  135909. toLineColumnOffset: sourceMapper.toLineColumnOffset,
  135910. getSourceMapper: function () { return sourceMapper; },
  135911. prepareCallHierarchy: prepareCallHierarchy,
  135912. provideCallHierarchyIncomingCalls: provideCallHierarchyIncomingCalls,
  135913. provideCallHierarchyOutgoingCalls: provideCallHierarchyOutgoingCalls
  135914. };
  135915. }
  135916. ts.createLanguageService = createLanguageService;
  135917. /* @internal */
  135918. /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */
  135919. function getNameTable(sourceFile) {
  135920. if (!sourceFile.nameTable) {
  135921. initializeNameTable(sourceFile);
  135922. }
  135923. return sourceFile.nameTable; // TODO: GH#18217
  135924. }
  135925. ts.getNameTable = getNameTable;
  135926. function initializeNameTable(sourceFile) {
  135927. var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
  135928. sourceFile.forEachChild(function walk(node) {
  135929. if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
  135930. var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
  135931. nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
  135932. }
  135933. else if (ts.isPrivateIdentifier(node)) {
  135934. var text = node.escapedText;
  135935. nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
  135936. }
  135937. ts.forEachChild(node, walk);
  135938. if (ts.hasJSDocNodes(node)) {
  135939. for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
  135940. var jsDoc = _a[_i];
  135941. ts.forEachChild(jsDoc, walk);
  135942. }
  135943. }
  135944. });
  135945. }
  135946. /**
  135947. * We want to store any numbers/strings if they were a name that could be
  135948. * related to a declaration. So, if we have 'import x = require("something")'
  135949. * then we want 'something' to be in the name table. Similarly, if we have
  135950. * "a['propname']" then we want to store "propname" in the name table.
  135951. */
  135952. function literalIsName(node) {
  135953. return ts.isDeclarationName(node) ||
  135954. node.parent.kind === 265 /* ExternalModuleReference */ ||
  135955. isArgumentOfElementAccessExpression(node) ||
  135956. ts.isLiteralComputedPropertyDeclarationName(node);
  135957. }
  135958. /**
  135959. * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
  135960. */
  135961. /* @internal */
  135962. function getContainingObjectLiteralElement(node) {
  135963. var element = getContainingObjectLiteralElementWorker(node);
  135964. return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined;
  135965. }
  135966. ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement;
  135967. function getContainingObjectLiteralElementWorker(node) {
  135968. switch (node.kind) {
  135969. case 10 /* StringLiteral */:
  135970. case 14 /* NoSubstitutionTemplateLiteral */:
  135971. case 8 /* NumericLiteral */:
  135972. if (node.parent.kind === 154 /* ComputedPropertyName */) {
  135973. return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined;
  135974. }
  135975. // falls through
  135976. case 75 /* Identifier */:
  135977. return ts.isObjectLiteralElement(node.parent) &&
  135978. (node.parent.parent.kind === 193 /* ObjectLiteralExpression */ || node.parent.parent.kind === 274 /* JsxAttributes */) &&
  135979. node.parent.name === node ? node.parent : undefined;
  135980. }
  135981. return undefined;
  135982. }
  135983. function getSymbolAtLocationForQuickInfo(node, checker) {
  135984. var object = getContainingObjectLiteralElement(node);
  135985. if (object) {
  135986. var contextualType = checker.getContextualType(object.parent);
  135987. var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false);
  135988. if (properties && properties.length === 1) {
  135989. return ts.first(properties);
  135990. }
  135991. }
  135992. return checker.getSymbolAtLocation(node);
  135993. }
  135994. /** Gets all symbols for one property. Does not get symbols for every property. */
  135995. /* @internal */
  135996. function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) {
  135997. var name = ts.getNameFromPropertyName(node.name);
  135998. if (!name)
  135999. return ts.emptyArray;
  136000. if (!contextualType.isUnion()) {
  136001. var symbol = contextualType.getProperty(name);
  136002. return symbol ? [symbol] : ts.emptyArray;
  136003. }
  136004. var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); });
  136005. if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
  136006. var symbol = contextualType.getProperty(name);
  136007. if (symbol)
  136008. return [symbol];
  136009. }
  136010. if (discriminatedPropertySymbols.length === 0) {
  136011. // Bad discriminant -- do again without discriminating
  136012. return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); });
  136013. }
  136014. return discriminatedPropertySymbols;
  136015. }
  136016. ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType;
  136017. function isArgumentOfElementAccessExpression(node) {
  136018. return node &&
  136019. node.parent &&
  136020. node.parent.kind === 195 /* ElementAccessExpression */ &&
  136021. node.parent.argumentExpression === node;
  136022. }
  136023. /**
  136024. * Get the path of the default library files (lib.d.ts) as distributed with the typescript
  136025. * node package.
  136026. * The functionality is not supported if the ts module is consumed outside of a node module.
  136027. */
  136028. function getDefaultLibFilePath(options) {
  136029. // Check __dirname is defined and that we are on a node.js system.
  136030. if (typeof __dirname !== "undefined") {
  136031. return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options);
  136032. }
  136033. throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
  136034. }
  136035. ts.getDefaultLibFilePath = getDefaultLibFilePath;
  136036. ts.setObjectAllocator(getServicesObjectAllocator());
  136037. })(ts || (ts = {}));
  136038. /* @internal */
  136039. var ts;
  136040. (function (ts) {
  136041. var BreakpointResolver;
  136042. (function (BreakpointResolver) {
  136043. /**
  136044. * Get the breakpoint span in given sourceFile
  136045. */
  136046. function spanInSourceFileAtLocation(sourceFile, position) {
  136047. // Cannot set breakpoint in dts file
  136048. if (sourceFile.isDeclarationFile) {
  136049. return undefined;
  136050. }
  136051. var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
  136052. var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
  136053. if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
  136054. // Get previous token if the token is returned starts on new line
  136055. // eg: let x =10; |--- cursor is here
  136056. // let y = 10;
  136057. // token at position will return let keyword on second line as the token but we would like to use
  136058. // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
  136059. var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile);
  136060. // It's a blank line
  136061. if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) {
  136062. return undefined;
  136063. }
  136064. tokenAtLocation = preceding;
  136065. }
  136066. // Cannot set breakpoint in ambient declarations
  136067. if (tokenAtLocation.flags & 8388608 /* Ambient */) {
  136068. return undefined;
  136069. }
  136070. // Get the span in the node based on its syntax
  136071. return spanInNode(tokenAtLocation);
  136072. function textSpan(startNode, endNode) {
  136073. var start = startNode.decorators ?
  136074. ts.skipTrivia(sourceFile.text, startNode.decorators.end) :
  136075. startNode.getStart(sourceFile);
  136076. return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
  136077. }
  136078. function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
  136079. return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
  136080. }
  136081. function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
  136082. if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
  136083. return spanInNode(node);
  136084. }
  136085. return spanInNode(otherwiseOnNode);
  136086. }
  136087. function spanInNodeArray(nodeArray) {
  136088. return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
  136089. }
  136090. function spanInPreviousNode(node) {
  136091. return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
  136092. }
  136093. function spanInNextNode(node) {
  136094. return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
  136095. }
  136096. function spanInNode(node) {
  136097. if (node) {
  136098. var parent = node.parent;
  136099. switch (node.kind) {
  136100. case 225 /* VariableStatement */:
  136101. // Span on first variable declaration
  136102. return spanInVariableDeclaration(node.declarationList.declarations[0]);
  136103. case 242 /* VariableDeclaration */:
  136104. case 159 /* PropertyDeclaration */:
  136105. case 158 /* PropertySignature */:
  136106. return spanInVariableDeclaration(node);
  136107. case 156 /* Parameter */:
  136108. return spanInParameterDeclaration(node);
  136109. case 244 /* FunctionDeclaration */:
  136110. case 161 /* MethodDeclaration */:
  136111. case 160 /* MethodSignature */:
  136112. case 163 /* GetAccessor */:
  136113. case 164 /* SetAccessor */:
  136114. case 162 /* Constructor */:
  136115. case 201 /* FunctionExpression */:
  136116. case 202 /* ArrowFunction */:
  136117. return spanInFunctionDeclaration(node);
  136118. case 223 /* Block */:
  136119. if (ts.isFunctionBlock(node)) {
  136120. return spanInFunctionBlock(node);
  136121. }
  136122. // falls through
  136123. case 250 /* ModuleBlock */:
  136124. return spanInBlock(node);
  136125. case 280 /* CatchClause */:
  136126. return spanInBlock(node.block);
  136127. case 226 /* ExpressionStatement */:
  136128. // span on the expression
  136129. return textSpan(node.expression);
  136130. case 235 /* ReturnStatement */:
  136131. // span on return keyword and expression if present
  136132. return textSpan(node.getChildAt(0), node.expression);
  136133. case 229 /* WhileStatement */:
  136134. // Span on while(...)
  136135. return textSpanEndingAtNextToken(node, node.expression);
  136136. case 228 /* DoStatement */:
  136137. // span in statement of the do statement
  136138. return spanInNode(node.statement);
  136139. case 241 /* DebuggerStatement */:
  136140. // span on debugger keyword
  136141. return textSpan(node.getChildAt(0));
  136142. case 227 /* IfStatement */:
  136143. // set on if(..) span
  136144. return textSpanEndingAtNextToken(node, node.expression);
  136145. case 238 /* LabeledStatement */:
  136146. // span in statement
  136147. return spanInNode(node.statement);
  136148. case 234 /* BreakStatement */:
  136149. case 233 /* ContinueStatement */:
  136150. // On break or continue keyword and label if present
  136151. return textSpan(node.getChildAt(0), node.label);
  136152. case 230 /* ForStatement */:
  136153. return spanInForStatement(node);
  136154. case 231 /* ForInStatement */:
  136155. // span of for (a in ...)
  136156. return textSpanEndingAtNextToken(node, node.expression);
  136157. case 232 /* ForOfStatement */:
  136158. // span in initializer
  136159. return spanInInitializerOfForLike(node);
  136160. case 237 /* SwitchStatement */:
  136161. // span on switch(...)
  136162. return textSpanEndingAtNextToken(node, node.expression);
  136163. case 277 /* CaseClause */:
  136164. case 278 /* DefaultClause */:
  136165. // span in first statement of the clause
  136166. return spanInNode(node.statements[0]);
  136167. case 240 /* TryStatement */:
  136168. // span in try block
  136169. return spanInBlock(node.tryBlock);
  136170. case 239 /* ThrowStatement */:
  136171. // span in throw ...
  136172. return textSpan(node, node.expression);
  136173. case 259 /* ExportAssignment */:
  136174. // span on export = id
  136175. return textSpan(node, node.expression);
  136176. case 253 /* ImportEqualsDeclaration */:
  136177. // import statement without including semicolon
  136178. return textSpan(node, node.moduleReference);
  136179. case 254 /* ImportDeclaration */:
  136180. // import statement without including semicolon
  136181. return textSpan(node, node.moduleSpecifier);
  136182. case 260 /* ExportDeclaration */:
  136183. // import statement without including semicolon
  136184. return textSpan(node, node.moduleSpecifier);
  136185. case 249 /* ModuleDeclaration */:
  136186. // span on complete module if it is instantiated
  136187. if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
  136188. return undefined;
  136189. }
  136190. // falls through
  136191. case 245 /* ClassDeclaration */:
  136192. case 248 /* EnumDeclaration */:
  136193. case 284 /* EnumMember */:
  136194. case 191 /* BindingElement */:
  136195. // span on complete node
  136196. return textSpan(node);
  136197. case 236 /* WithStatement */:
  136198. // span in statement
  136199. return spanInNode(node.statement);
  136200. case 157 /* Decorator */:
  136201. return spanInNodeArray(parent.decorators);
  136202. case 189 /* ObjectBindingPattern */:
  136203. case 190 /* ArrayBindingPattern */:
  136204. return spanInBindingPattern(node);
  136205. // No breakpoint in interface, type alias
  136206. case 246 /* InterfaceDeclaration */:
  136207. case 247 /* TypeAliasDeclaration */:
  136208. return undefined;
  136209. // Tokens:
  136210. case 26 /* SemicolonToken */:
  136211. case 1 /* EndOfFileToken */:
  136212. return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile));
  136213. case 27 /* CommaToken */:
  136214. return spanInPreviousNode(node);
  136215. case 18 /* OpenBraceToken */:
  136216. return spanInOpenBraceToken(node);
  136217. case 19 /* CloseBraceToken */:
  136218. return spanInCloseBraceToken(node);
  136219. case 23 /* CloseBracketToken */:
  136220. return spanInCloseBracketToken(node);
  136221. case 20 /* OpenParenToken */:
  136222. return spanInOpenParenToken(node);
  136223. case 21 /* CloseParenToken */:
  136224. return spanInCloseParenToken(node);
  136225. case 58 /* ColonToken */:
  136226. return spanInColonToken(node);
  136227. case 31 /* GreaterThanToken */:
  136228. case 29 /* LessThanToken */:
  136229. return spanInGreaterThanOrLessThanToken(node);
  136230. // Keywords:
  136231. case 111 /* WhileKeyword */:
  136232. return spanInWhileKeyword(node);
  136233. case 87 /* ElseKeyword */:
  136234. case 79 /* CatchKeyword */:
  136235. case 92 /* FinallyKeyword */:
  136236. return spanInNextNode(node);
  136237. case 152 /* OfKeyword */:
  136238. return spanInOfKeyword(node);
  136239. default:
  136240. // Destructuring pattern in destructuring assignment
  136241. // [a, b, c] of
  136242. // [a, b, c] = expression
  136243. if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
  136244. return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node);
  136245. }
  136246. // Set breakpoint on identifier element of destructuring pattern
  136247. // `a` or `...c` or `d: x` from
  136248. // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern
  136249. if ((node.kind === 75 /* Identifier */ ||
  136250. node.kind === 213 /* SpreadElement */ ||
  136251. node.kind === 281 /* PropertyAssignment */ ||
  136252. node.kind === 282 /* ShorthandPropertyAssignment */) &&
  136253. ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) {
  136254. return textSpan(node);
  136255. }
  136256. if (node.kind === 209 /* BinaryExpression */) {
  136257. var _a = node, left = _a.left, operatorToken = _a.operatorToken;
  136258. // Set breakpoint in destructuring pattern if its destructuring assignment
  136259. // [a, b, c] or {a, b, c} of
  136260. // [a, b, c] = expression or
  136261. // {a, b, c} = expression
  136262. if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
  136263. return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
  136264. }
  136265. if (operatorToken.kind === 62 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
  136266. // Set breakpoint on assignment expression element of destructuring pattern
  136267. // a = expression of
  136268. // [a = expression, b, c] = someExpression or
  136269. // { a = expression, b, c } = someExpression
  136270. return textSpan(node);
  136271. }
  136272. if (operatorToken.kind === 27 /* CommaToken */) {
  136273. return spanInNode(left);
  136274. }
  136275. }
  136276. if (ts.isExpressionNode(node)) {
  136277. switch (parent.kind) {
  136278. case 228 /* DoStatement */:
  136279. // Set span as if on while keyword
  136280. return spanInPreviousNode(node);
  136281. case 157 /* Decorator */:
  136282. // Set breakpoint on the decorator emit
  136283. return spanInNode(node.parent);
  136284. case 230 /* ForStatement */:
  136285. case 232 /* ForOfStatement */:
  136286. return textSpan(node);
  136287. case 209 /* BinaryExpression */:
  136288. if (node.parent.operatorToken.kind === 27 /* CommaToken */) {
  136289. // If this is a comma expression, the breakpoint is possible in this expression
  136290. return textSpan(node);
  136291. }
  136292. break;
  136293. case 202 /* ArrowFunction */:
  136294. if (node.parent.body === node) {
  136295. // If this is body of arrow function, it is allowed to have the breakpoint
  136296. return textSpan(node);
  136297. }
  136298. break;
  136299. }
  136300. }
  136301. switch (node.parent.kind) {
  136302. case 281 /* PropertyAssignment */:
  136303. // If this is name of property assignment, set breakpoint in the initializer
  136304. if (node.parent.name === node &&
  136305. !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
  136306. return spanInNode(node.parent.initializer);
  136307. }
  136308. break;
  136309. case 199 /* TypeAssertionExpression */:
  136310. // Breakpoint in type assertion goes to its operand
  136311. if (node.parent.type === node) {
  136312. return spanInNextNode(node.parent.type);
  136313. }
  136314. break;
  136315. case 242 /* VariableDeclaration */:
  136316. case 156 /* Parameter */: {
  136317. // initializer of variable/parameter declaration go to previous node
  136318. var _b = node.parent, initializer = _b.initializer, type = _b.type;
  136319. if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) {
  136320. return spanInPreviousNode(node);
  136321. }
  136322. break;
  136323. }
  136324. case 209 /* BinaryExpression */: {
  136325. var left = node.parent.left;
  136326. if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
  136327. // If initializer of destructuring assignment move to previous token
  136328. return spanInPreviousNode(node);
  136329. }
  136330. break;
  136331. }
  136332. default:
  136333. // return type of function go to previous token
  136334. if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
  136335. return spanInPreviousNode(node);
  136336. }
  136337. }
  136338. // Default go to parent to set the breakpoint
  136339. return spanInNode(node.parent);
  136340. }
  136341. }
  136342. function textSpanFromVariableDeclaration(variableDeclaration) {
  136343. if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
  136344. // First declaration - include let keyword
  136345. return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
  136346. }
  136347. else {
  136348. // Span only on this declaration
  136349. return textSpan(variableDeclaration);
  136350. }
  136351. }
  136352. function spanInVariableDeclaration(variableDeclaration) {
  136353. // If declaration of for in statement, just set the span in parent
  136354. if (variableDeclaration.parent.parent.kind === 231 /* ForInStatement */) {
  136355. return spanInNode(variableDeclaration.parent.parent);
  136356. }
  136357. var parent = variableDeclaration.parent;
  136358. // If this is a destructuring pattern, set breakpoint in binding pattern
  136359. if (ts.isBindingPattern(variableDeclaration.name)) {
  136360. return spanInBindingPattern(variableDeclaration.name);
  136361. }
  136362. // Breakpoint is possible in variableDeclaration only if there is initialization
  136363. // or its declaration from 'for of'
  136364. if (variableDeclaration.initializer ||
  136365. ts.hasModifier(variableDeclaration, 1 /* Export */) ||
  136366. parent.parent.kind === 232 /* ForOfStatement */) {
  136367. return textSpanFromVariableDeclaration(variableDeclaration);
  136368. }
  136369. if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
  136370. variableDeclaration.parent.declarations[0] !== variableDeclaration) {
  136371. // If we cannot set breakpoint on this declaration, set it on previous one
  136372. // Because the variable declaration may be binding pattern and
  136373. // we would like to set breakpoint in last binding element if that's the case,
  136374. // use preceding token instead
  136375. return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
  136376. }
  136377. }
  136378. function canHaveSpanInParameterDeclaration(parameter) {
  136379. // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier
  136380. return !!parameter.initializer || parameter.dotDotDotToken !== undefined ||
  136381. ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */);
  136382. }
  136383. function spanInParameterDeclaration(parameter) {
  136384. if (ts.isBindingPattern(parameter.name)) {
  136385. // Set breakpoint in binding pattern
  136386. return spanInBindingPattern(parameter.name);
  136387. }
  136388. else if (canHaveSpanInParameterDeclaration(parameter)) {
  136389. return textSpan(parameter);
  136390. }
  136391. else {
  136392. var functionDeclaration = parameter.parent;
  136393. var indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
  136394. ts.Debug.assert(indexOfParameter !== -1);
  136395. if (indexOfParameter !== 0) {
  136396. // Not a first parameter, go to previous parameter
  136397. return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
  136398. }
  136399. else {
  136400. // Set breakpoint in the function declaration body
  136401. return spanInNode(functionDeclaration.body);
  136402. }
  136403. }
  136404. }
  136405. function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
  136406. return ts.hasModifier(functionDeclaration, 1 /* Export */) ||
  136407. (functionDeclaration.parent.kind === 245 /* ClassDeclaration */ && functionDeclaration.kind !== 162 /* Constructor */);
  136408. }
  136409. function spanInFunctionDeclaration(functionDeclaration) {
  136410. // No breakpoints in the function signature
  136411. if (!functionDeclaration.body) {
  136412. return undefined;
  136413. }
  136414. if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
  136415. // Set the span on whole function declaration
  136416. return textSpan(functionDeclaration);
  136417. }
  136418. // Set span in function body
  136419. return spanInNode(functionDeclaration.body);
  136420. }
  136421. function spanInFunctionBlock(block) {
  136422. var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
  136423. if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
  136424. return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
  136425. }
  136426. return spanInNode(nodeForSpanInBlock);
  136427. }
  136428. function spanInBlock(block) {
  136429. switch (block.parent.kind) {
  136430. case 249 /* ModuleDeclaration */:
  136431. if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
  136432. return undefined;
  136433. }
  136434. // Set on parent if on same line otherwise on first statement
  136435. // falls through
  136436. case 229 /* WhileStatement */:
  136437. case 227 /* IfStatement */:
  136438. case 231 /* ForInStatement */:
  136439. return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
  136440. // Set span on previous token if it starts on same line otherwise on the first statement of the block
  136441. case 230 /* ForStatement */:
  136442. case 232 /* ForOfStatement */:
  136443. return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
  136444. }
  136445. // Default action is to set on first statement
  136446. return spanInNode(block.statements[0]);
  136447. }
  136448. function spanInInitializerOfForLike(forLikeStatement) {
  136449. if (forLikeStatement.initializer.kind === 243 /* VariableDeclarationList */) {
  136450. // Declaration list - set breakpoint in first declaration
  136451. var variableDeclarationList = forLikeStatement.initializer;
  136452. if (variableDeclarationList.declarations.length > 0) {
  136453. return spanInNode(variableDeclarationList.declarations[0]);
  136454. }
  136455. }
  136456. else {
  136457. // Expression - set breakpoint in it
  136458. return spanInNode(forLikeStatement.initializer);
  136459. }
  136460. }
  136461. function spanInForStatement(forStatement) {
  136462. if (forStatement.initializer) {
  136463. return spanInInitializerOfForLike(forStatement);
  136464. }
  136465. if (forStatement.condition) {
  136466. return textSpan(forStatement.condition);
  136467. }
  136468. if (forStatement.incrementor) {
  136469. return textSpan(forStatement.incrementor);
  136470. }
  136471. }
  136472. function spanInBindingPattern(bindingPattern) {
  136473. // Set breakpoint in first binding element
  136474. var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 215 /* OmittedExpression */ ? element : undefined; });
  136475. if (firstBindingElement) {
  136476. return spanInNode(firstBindingElement);
  136477. }
  136478. // Empty binding pattern of binding element, set breakpoint on binding element
  136479. if (bindingPattern.parent.kind === 191 /* BindingElement */) {
  136480. return textSpan(bindingPattern.parent);
  136481. }
  136482. // Variable declaration is used as the span
  136483. return textSpanFromVariableDeclaration(bindingPattern.parent);
  136484. }
  136485. function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) {
  136486. ts.Debug.assert(node.kind !== 190 /* ArrayBindingPattern */ && node.kind !== 189 /* ObjectBindingPattern */);
  136487. var elements = node.kind === 192 /* ArrayLiteralExpression */ ? node.elements : node.properties;
  136488. var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 215 /* OmittedExpression */ ? element : undefined; });
  136489. if (firstBindingElement) {
  136490. return spanInNode(firstBindingElement);
  136491. }
  136492. // Could be ArrayLiteral from destructuring assignment or
  136493. // just nested element in another destructuring assignment
  136494. // set breakpoint on assignment when parent is destructuring assignment
  136495. // Otherwise set breakpoint for this element
  136496. return textSpan(node.parent.kind === 209 /* BinaryExpression */ ? node.parent : node);
  136497. }
  136498. // Tokens:
  136499. function spanInOpenBraceToken(node) {
  136500. switch (node.parent.kind) {
  136501. case 248 /* EnumDeclaration */:
  136502. var enumDeclaration = node.parent;
  136503. return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
  136504. case 245 /* ClassDeclaration */:
  136505. var classDeclaration = node.parent;
  136506. return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
  136507. case 251 /* CaseBlock */:
  136508. return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
  136509. }
  136510. // Default to parent node
  136511. return spanInNode(node.parent);
  136512. }
  136513. function spanInCloseBraceToken(node) {
  136514. switch (node.parent.kind) {
  136515. case 250 /* ModuleBlock */:
  136516. // If this is not an instantiated module block, no bp span
  136517. if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
  136518. return undefined;
  136519. }
  136520. // falls through
  136521. case 248 /* EnumDeclaration */:
  136522. case 245 /* ClassDeclaration */:
  136523. // Span on close brace token
  136524. return textSpan(node);
  136525. case 223 /* Block */:
  136526. if (ts.isFunctionBlock(node.parent)) {
  136527. // Span on close brace token
  136528. return textSpan(node);
  136529. }
  136530. // falls through
  136531. case 280 /* CatchClause */:
  136532. return spanInNode(ts.lastOrUndefined(node.parent.statements));
  136533. case 251 /* CaseBlock */:
  136534. // breakpoint in last statement of the last clause
  136535. var caseBlock = node.parent;
  136536. var lastClause = ts.lastOrUndefined(caseBlock.clauses);
  136537. if (lastClause) {
  136538. return spanInNode(ts.lastOrUndefined(lastClause.statements));
  136539. }
  136540. return undefined;
  136541. case 189 /* ObjectBindingPattern */:
  136542. // Breakpoint in last binding element or binding pattern if it contains no elements
  136543. var bindingPattern = node.parent;
  136544. return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
  136545. // Default to parent node
  136546. default:
  136547. if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
  136548. // Breakpoint in last binding element or binding pattern if it contains no elements
  136549. var objectLiteral = node.parent;
  136550. return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral);
  136551. }
  136552. return spanInNode(node.parent);
  136553. }
  136554. }
  136555. function spanInCloseBracketToken(node) {
  136556. switch (node.parent.kind) {
  136557. case 190 /* ArrayBindingPattern */:
  136558. // Breakpoint in last binding element or binding pattern if it contains no elements
  136559. var bindingPattern = node.parent;
  136560. return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
  136561. default:
  136562. if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
  136563. // Breakpoint in last binding element or binding pattern if it contains no elements
  136564. var arrayLiteral = node.parent;
  136565. return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
  136566. }
  136567. // Default to parent node
  136568. return spanInNode(node.parent);
  136569. }
  136570. }
  136571. function spanInOpenParenToken(node) {
  136572. if (node.parent.kind === 228 /* DoStatement */ || // Go to while keyword and do action instead
  136573. node.parent.kind === 196 /* CallExpression */ ||
  136574. node.parent.kind === 197 /* NewExpression */) {
  136575. return spanInPreviousNode(node);
  136576. }
  136577. if (node.parent.kind === 200 /* ParenthesizedExpression */) {
  136578. return spanInNextNode(node);
  136579. }
  136580. // Default to parent node
  136581. return spanInNode(node.parent);
  136582. }
  136583. function spanInCloseParenToken(node) {
  136584. // Is this close paren token of parameter list, set span in previous token
  136585. switch (node.parent.kind) {
  136586. case 201 /* FunctionExpression */:
  136587. case 244 /* FunctionDeclaration */:
  136588. case 202 /* ArrowFunction */:
  136589. case 161 /* MethodDeclaration */:
  136590. case 160 /* MethodSignature */:
  136591. case 163 /* GetAccessor */:
  136592. case 164 /* SetAccessor */:
  136593. case 162 /* Constructor */:
  136594. case 229 /* WhileStatement */:
  136595. case 228 /* DoStatement */:
  136596. case 230 /* ForStatement */:
  136597. case 232 /* ForOfStatement */:
  136598. case 196 /* CallExpression */:
  136599. case 197 /* NewExpression */:
  136600. case 200 /* ParenthesizedExpression */:
  136601. return spanInPreviousNode(node);
  136602. // Default to parent node
  136603. default:
  136604. return spanInNode(node.parent);
  136605. }
  136606. }
  136607. function spanInColonToken(node) {
  136608. // Is this : specifying return annotation of the function declaration
  136609. if (ts.isFunctionLike(node.parent) ||
  136610. node.parent.kind === 281 /* PropertyAssignment */ ||
  136611. node.parent.kind === 156 /* Parameter */) {
  136612. return spanInPreviousNode(node);
  136613. }
  136614. return spanInNode(node.parent);
  136615. }
  136616. function spanInGreaterThanOrLessThanToken(node) {
  136617. if (node.parent.kind === 199 /* TypeAssertionExpression */) {
  136618. return spanInNextNode(node);
  136619. }
  136620. return spanInNode(node.parent);
  136621. }
  136622. function spanInWhileKeyword(node) {
  136623. if (node.parent.kind === 228 /* DoStatement */) {
  136624. // Set span on while expression
  136625. return textSpanEndingAtNextToken(node, node.parent.expression);
  136626. }
  136627. // Default to parent node
  136628. return spanInNode(node.parent);
  136629. }
  136630. function spanInOfKeyword(node) {
  136631. if (node.parent.kind === 232 /* ForOfStatement */) {
  136632. // Set using next token
  136633. return spanInNextNode(node);
  136634. }
  136635. // Default to parent node
  136636. return spanInNode(node.parent);
  136637. }
  136638. }
  136639. }
  136640. BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation;
  136641. })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {}));
  136642. })(ts || (ts = {}));
  136643. var ts;
  136644. (function (ts) {
  136645. /**
  136646. * Transform one or more nodes using the supplied transformers.
  136647. * @param source A single `Node` or an array of `Node` objects.
  136648. * @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
  136649. * @param compilerOptions Optional compiler options.
  136650. */
  136651. function transform(source, transformers, compilerOptions) {
  136652. var diagnostics = [];
  136653. compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217
  136654. var nodes = ts.isArray(source) ? source : [source];
  136655. var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
  136656. result.diagnostics = ts.concatenate(result.diagnostics, diagnostics);
  136657. return result;
  136658. }
  136659. ts.transform = transform;
  136660. })(ts || (ts = {}));
  136661. //
  136662. // Copyright (c) Microsoft Corporation. All rights reserved.
  136663. //
  136664. // Licensed under the Apache License, Version 2.0 (the "License");
  136665. // you may not use this file except in compliance with the License.
  136666. // You may obtain a copy of the License at
  136667. // http://www.apache.org/licenses/LICENSE-2.0
  136668. //
  136669. // Unless required by applicable law or agreed to in writing, software
  136670. // distributed under the License is distributed on an "AS IS" BASIS,
  136671. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  136672. // See the License for the specific language governing permissions and
  136673. // limitations under the License.
  136674. //
  136675. /* @internal */
  136676. var debugObjectHost = (function () { return this; })(); // eslint-disable-line prefer-const
  136677. // We need to use 'null' to interface with the managed side.
  136678. /* eslint-disable no-in-operator */
  136679. /* @internal */
  136680. var ts;
  136681. (function (ts) {
  136682. function logInternalError(logger, err) {
  136683. if (logger) {
  136684. logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
  136685. }
  136686. }
  136687. var ScriptSnapshotShimAdapter = /** @class */ (function () {
  136688. function ScriptSnapshotShimAdapter(scriptSnapshotShim) {
  136689. this.scriptSnapshotShim = scriptSnapshotShim;
  136690. }
  136691. ScriptSnapshotShimAdapter.prototype.getText = function (start, end) {
  136692. return this.scriptSnapshotShim.getText(start, end);
  136693. };
  136694. ScriptSnapshotShimAdapter.prototype.getLength = function () {
  136695. return this.scriptSnapshotShim.getLength();
  136696. };
  136697. ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) {
  136698. var oldSnapshotShim = oldSnapshot;
  136699. var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
  136700. /* eslint-disable no-null/no-null */
  136701. if (encoded === null) {
  136702. return null; // TODO: GH#18217
  136703. }
  136704. /* eslint-enable no-null/no-null */
  136705. var decoded = JSON.parse(encoded); // TODO: GH#18217
  136706. return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
  136707. };
  136708. ScriptSnapshotShimAdapter.prototype.dispose = function () {
  136709. // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments
  136710. // 'in' does not have this effect
  136711. if ("dispose" in this.scriptSnapshotShim) {
  136712. this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`?
  136713. }
  136714. };
  136715. return ScriptSnapshotShimAdapter;
  136716. }());
  136717. var LanguageServiceShimHostAdapter = /** @class */ (function () {
  136718. function LanguageServiceShimHostAdapter(shimHost) {
  136719. var _this = this;
  136720. this.shimHost = shimHost;
  136721. this.loggingEnabled = false;
  136722. this.tracingEnabled = false;
  136723. // if shimHost is a COM object then property check will become method call with no arguments.
  136724. // 'in' does not have this effect.
  136725. if ("getModuleResolutionsForFile" in this.shimHost) {
  136726. this.resolveModuleNames = function (moduleNames, containingFile) {
  136727. var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217
  136728. return ts.map(moduleNames, function (name) {
  136729. var result = ts.getProperty(resolutionsInFile, name);
  136730. return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined;
  136731. });
  136732. };
  136733. }
  136734. if ("directoryExists" in this.shimHost) {
  136735. this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
  136736. }
  136737. if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
  136738. this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
  136739. var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217
  136740. return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); });
  136741. };
  136742. }
  136743. }
  136744. LanguageServiceShimHostAdapter.prototype.log = function (s) {
  136745. if (this.loggingEnabled) {
  136746. this.shimHost.log(s);
  136747. }
  136748. };
  136749. LanguageServiceShimHostAdapter.prototype.trace = function (s) {
  136750. if (this.tracingEnabled) {
  136751. this.shimHost.trace(s);
  136752. }
  136753. };
  136754. LanguageServiceShimHostAdapter.prototype.error = function (s) {
  136755. this.shimHost.error(s);
  136756. };
  136757. LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () {
  136758. if (!this.shimHost.getProjectVersion) {
  136759. // shimmed host does not support getProjectVersion
  136760. return undefined; // TODO: GH#18217
  136761. }
  136762. return this.shimHost.getProjectVersion();
  136763. };
  136764. LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
  136765. if (!this.shimHost.getTypeRootsVersion) {
  136766. return 0;
  136767. }
  136768. return this.shimHost.getTypeRootsVersion();
  136769. };
  136770. LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
  136771. return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
  136772. };
  136773. LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () {
  136774. var settingsJson = this.shimHost.getCompilationSettings();
  136775. // eslint-disable-next-line no-null/no-null
  136776. if (settingsJson === null || settingsJson === "") {
  136777. throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
  136778. }
  136779. var compilerOptions = JSON.parse(settingsJson);
  136780. // permit language service to handle all files (filtering should be performed on the host side)
  136781. compilerOptions.allowNonTsExtensions = true;
  136782. return compilerOptions;
  136783. };
  136784. LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () {
  136785. var encoded = this.shimHost.getScriptFileNames();
  136786. return JSON.parse(encoded);
  136787. };
  136788. LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) {
  136789. var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
  136790. return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
  136791. };
  136792. LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) {
  136793. if ("getScriptKind" in this.shimHost) {
  136794. return this.shimHost.getScriptKind(fileName); // TODO: GH#18217
  136795. }
  136796. else {
  136797. return 0 /* Unknown */;
  136798. }
  136799. };
  136800. LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) {
  136801. return this.shimHost.getScriptVersion(fileName);
  136802. };
  136803. LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () {
  136804. /* eslint-disable no-null/no-null */
  136805. var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
  136806. if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
  136807. return null;
  136808. }
  136809. try {
  136810. return JSON.parse(diagnosticMessagesJson);
  136811. }
  136812. catch (e) {
  136813. this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
  136814. return null;
  136815. }
  136816. /* eslint-enable no-null/no-null */
  136817. };
  136818. LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () {
  136819. var hostCancellationToken = this.shimHost.getCancellationToken();
  136820. return new ts.ThrottledCancellationToken(hostCancellationToken);
  136821. };
  136822. LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () {
  136823. return this.shimHost.getCurrentDirectory();
  136824. };
  136825. LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
  136826. return JSON.parse(this.shimHost.getDirectories(path));
  136827. };
  136828. LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
  136829. return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
  136830. };
  136831. LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) {
  136832. var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
  136833. return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
  136834. };
  136835. LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) {
  136836. return this.shimHost.readFile(path, encoding);
  136837. };
  136838. LanguageServiceShimHostAdapter.prototype.fileExists = function (path) {
  136839. return this.shimHost.fileExists(path);
  136840. };
  136841. return LanguageServiceShimHostAdapter;
  136842. }());
  136843. ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter;
  136844. var CoreServicesShimHostAdapter = /** @class */ (function () {
  136845. function CoreServicesShimHostAdapter(shimHost) {
  136846. var _this = this;
  136847. this.shimHost = shimHost;
  136848. this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
  136849. if ("directoryExists" in this.shimHost) {
  136850. this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
  136851. }
  136852. else {
  136853. this.directoryExists = undefined; // TODO: GH#18217
  136854. }
  136855. if ("realpath" in this.shimHost) {
  136856. this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
  136857. }
  136858. else {
  136859. this.realpath = undefined; // TODO: GH#18217
  136860. }
  136861. }
  136862. CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
  136863. var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
  136864. return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
  136865. };
  136866. CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) {
  136867. return this.shimHost.fileExists(fileName);
  136868. };
  136869. CoreServicesShimHostAdapter.prototype.readFile = function (fileName) {
  136870. return this.shimHost.readFile(fileName);
  136871. };
  136872. CoreServicesShimHostAdapter.prototype.getDirectories = function (path) {
  136873. return JSON.parse(this.shimHost.getDirectories(path));
  136874. };
  136875. return CoreServicesShimHostAdapter;
  136876. }());
  136877. ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter;
  136878. function simpleForwardCall(logger, actionDescription, action, logPerformance) {
  136879. var start;
  136880. if (logPerformance) {
  136881. logger.log(actionDescription);
  136882. start = ts.timestamp();
  136883. }
  136884. var result = action();
  136885. if (logPerformance) {
  136886. var end = ts.timestamp();
  136887. logger.log(actionDescription + " completed in " + (end - start) + " msec");
  136888. if (ts.isString(result)) {
  136889. var str = result;
  136890. if (str.length > 128) {
  136891. str = str.substring(0, 128) + "...";
  136892. }
  136893. logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
  136894. }
  136895. }
  136896. return result;
  136897. }
  136898. function forwardJSONCall(logger, actionDescription, action, logPerformance) {
  136899. return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance);
  136900. }
  136901. function forwardCall(logger, actionDescription, returnJson, action, logPerformance) {
  136902. try {
  136903. var result = simpleForwardCall(logger, actionDescription, action, logPerformance);
  136904. return returnJson ? JSON.stringify({ result: result }) : result;
  136905. }
  136906. catch (err) {
  136907. if (err instanceof ts.OperationCanceledException) {
  136908. return JSON.stringify({ canceled: true });
  136909. }
  136910. logInternalError(logger, err);
  136911. err.description = actionDescription;
  136912. return JSON.stringify({ error: err });
  136913. }
  136914. }
  136915. var ShimBase = /** @class */ (function () {
  136916. function ShimBase(factory) {
  136917. this.factory = factory;
  136918. factory.registerShim(this);
  136919. }
  136920. ShimBase.prototype.dispose = function (_dummy) {
  136921. this.factory.unregisterShim(this);
  136922. };
  136923. return ShimBase;
  136924. }());
  136925. function realizeDiagnostics(diagnostics, newLine) {
  136926. return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); });
  136927. }
  136928. ts.realizeDiagnostics = realizeDiagnostics;
  136929. function realizeDiagnostic(diagnostic, newLine) {
  136930. return {
  136931. message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
  136932. start: diagnostic.start,
  136933. length: diagnostic.length,
  136934. category: ts.diagnosticCategoryName(diagnostic),
  136935. code: diagnostic.code,
  136936. reportsUnnecessary: diagnostic.reportsUnnecessary,
  136937. };
  136938. }
  136939. var LanguageServiceShimObject = /** @class */ (function (_super) {
  136940. __extends(LanguageServiceShimObject, _super);
  136941. function LanguageServiceShimObject(factory, host, languageService) {
  136942. var _this = _super.call(this, factory) || this;
  136943. _this.host = host;
  136944. _this.languageService = languageService;
  136945. _this.logPerformance = false;
  136946. _this.logger = _this.host;
  136947. return _this;
  136948. }
  136949. LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
  136950. return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
  136951. };
  136952. /// DISPOSE
  136953. /**
  136954. * Ensure (almost) deterministic release of internal Javascript resources when
  136955. * some external native objects holds onto us (e.g. Com/Interop).
  136956. */
  136957. LanguageServiceShimObject.prototype.dispose = function (dummy) {
  136958. this.logger.log("dispose()");
  136959. this.languageService.dispose();
  136960. this.languageService = null; // eslint-disable-line no-null/no-null
  136961. // force a GC
  136962. if (debugObjectHost && debugObjectHost.CollectGarbage) {
  136963. debugObjectHost.CollectGarbage();
  136964. this.logger.log("CollectGarbage()");
  136965. }
  136966. this.logger = null; // eslint-disable-line no-null/no-null
  136967. _super.prototype.dispose.call(this, dummy);
  136968. };
  136969. /// REFRESH
  136970. /**
  136971. * Update the list of scripts known to the compiler
  136972. */
  136973. LanguageServiceShimObject.prototype.refresh = function (throwOnError) {
  136974. this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; } // eslint-disable-line no-null/no-null
  136975. );
  136976. };
  136977. LanguageServiceShimObject.prototype.cleanupSemanticCache = function () {
  136978. var _this = this;
  136979. this.forwardJSONCall("cleanupSemanticCache()", function () {
  136980. _this.languageService.cleanupSemanticCache();
  136981. return null; // eslint-disable-line no-null/no-null
  136982. });
  136983. };
  136984. LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
  136985. var newLine = ts.getNewLineOrDefaultFromHost(this.host);
  136986. return realizeDiagnostics(diagnostics, newLine);
  136987. };
  136988. LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
  136989. var _this = this;
  136990. return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); });
  136991. };
  136992. LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) {
  136993. var _this = this;
  136994. return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); });
  136995. };
  136996. LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) {
  136997. var _this = this;
  136998. return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")",
  136999. // directly serialize the spans out to a string. This is much faster to decode
  137000. // on the managed side versus a full JSON array.
  137001. function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); });
  137002. };
  137003. LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) {
  137004. var _this = this;
  137005. return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")",
  137006. // directly serialize the spans out to a string. This is much faster to decode
  137007. // on the managed side versus a full JSON array.
  137008. function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); });
  137009. };
  137010. LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) {
  137011. var _this = this;
  137012. return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () {
  137013. var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName);
  137014. return _this.realizeDiagnostics(diagnostics);
  137015. });
  137016. };
  137017. LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) {
  137018. var _this = this;
  137019. return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () {
  137020. var diagnostics = _this.languageService.getSemanticDiagnostics(fileName);
  137021. return _this.realizeDiagnostics(diagnostics);
  137022. });
  137023. };
  137024. LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
  137025. var _this = this;
  137026. return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
  137027. };
  137028. LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
  137029. var _this = this;
  137030. return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
  137031. var diagnostics = _this.languageService.getCompilerOptionsDiagnostics();
  137032. return _this.realizeDiagnostics(diagnostics);
  137033. });
  137034. };
  137035. /// QUICKINFO
  137036. /**
  137037. * Computes a string representation of the type at the requested position
  137038. * in the active file.
  137039. */
  137040. LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) {
  137041. var _this = this;
  137042. return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); });
  137043. };
  137044. /// NAMEORDOTTEDNAMESPAN
  137045. /**
  137046. * Computes span information of the name or dotted name at the requested position
  137047. * in the active file.
  137048. */
  137049. LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) {
  137050. var _this = this;
  137051. return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); });
  137052. };
  137053. /**
  137054. * STATEMENTSPAN
  137055. * Computes span information of statement at the requested position in the active file.
  137056. */
  137057. LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) {
  137058. var _this = this;
  137059. return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); });
  137060. };
  137061. /// SIGNATUREHELP
  137062. LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) {
  137063. var _this = this;
  137064. return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); });
  137065. };
  137066. /// GOTO DEFINITION
  137067. /**
  137068. * Computes the definition location and file for the symbol
  137069. * at the requested position.
  137070. */
  137071. LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) {
  137072. var _this = this;
  137073. return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); });
  137074. };
  137075. /**
  137076. * Computes the definition location and file for the symbol
  137077. * at the requested position.
  137078. */
  137079. LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) {
  137080. var _this = this;
  137081. return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); });
  137082. };
  137083. /// GOTO Type
  137084. /**
  137085. * Computes the definition location of the type of the symbol
  137086. * at the requested position.
  137087. */
  137088. LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) {
  137089. var _this = this;
  137090. return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); });
  137091. };
  137092. /// GOTO Implementation
  137093. /**
  137094. * Computes the implementation location of the symbol
  137095. * at the requested position.
  137096. */
  137097. LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) {
  137098. var _this = this;
  137099. return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); });
  137100. };
  137101. LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) {
  137102. var _this = this;
  137103. return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); });
  137104. };
  137105. LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) {
  137106. var _this = this;
  137107. return this.forwardJSONCall("getSmartSelectionRange('" + fileName + "', " + position + ")", function () { return _this.languageService.getSmartSelectionRange(fileName, position); });
  137108. };
  137109. LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) {
  137110. var _this = this;
  137111. return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); });
  137112. };
  137113. /// GET BRACE MATCHING
  137114. LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) {
  137115. var _this = this;
  137116. return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); });
  137117. };
  137118. LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) {
  137119. var _this = this;
  137120. return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); });
  137121. };
  137122. LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) {
  137123. var _this = this;
  137124. return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); });
  137125. };
  137126. /// GET SMART INDENT
  137127. LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) {
  137128. var _this = this;
  137129. return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () {
  137130. var localOptions = JSON.parse(options);
  137131. return _this.languageService.getIndentationAtPosition(fileName, position, localOptions);
  137132. });
  137133. };
  137134. /// GET REFERENCES
  137135. LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) {
  137136. var _this = this;
  137137. return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); });
  137138. };
  137139. LanguageServiceShimObject.prototype.findReferences = function (fileName, position) {
  137140. var _this = this;
  137141. return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); });
  137142. };
  137143. LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) {
  137144. var _this = this;
  137145. return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); });
  137146. };
  137147. LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) {
  137148. var _this = this;
  137149. return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () {
  137150. var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
  137151. // workaround for VS document highlighting issue - keep only items from the initial file
  137152. var normalizedName = ts.toFileNameLowerCase(ts.normalizeSlashes(fileName));
  137153. return ts.filter(results, function (r) { return ts.toFileNameLowerCase(ts.normalizeSlashes(r.fileName)) === normalizedName; });
  137154. });
  137155. };
  137156. /// COMPLETION LISTS
  137157. /**
  137158. * Get a string based representation of the completions
  137159. * to provide at the given source position and providing a member completion
  137160. * list if requested.
  137161. */
  137162. LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) {
  137163. var _this = this;
  137164. return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); });
  137165. };
  137166. /** Get a string based representation of a completion list entry details */
  137167. LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) {
  137168. var _this = this;
  137169. return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () {
  137170. var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions);
  137171. return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences);
  137172. });
  137173. };
  137174. LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) {
  137175. var _this = this;
  137176. return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () {
  137177. var localOptions = JSON.parse(options);
  137178. return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
  137179. });
  137180. };
  137181. LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) {
  137182. var _this = this;
  137183. return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () {
  137184. var localOptions = JSON.parse(options);
  137185. return _this.languageService.getFormattingEditsForDocument(fileName, localOptions);
  137186. });
  137187. };
  137188. LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) {
  137189. var _this = this;
  137190. return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () {
  137191. var localOptions = JSON.parse(options);
  137192. return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
  137193. });
  137194. };
  137195. LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) {
  137196. var _this = this;
  137197. return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); });
  137198. };
  137199. /// NAVIGATE TO
  137200. /** Return a list of symbols that are interesting to navigate to */
  137201. LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) {
  137202. var _this = this;
  137203. return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); });
  137204. };
  137205. LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) {
  137206. var _this = this;
  137207. return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); });
  137208. };
  137209. LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) {
  137210. var _this = this;
  137211. return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); });
  137212. };
  137213. LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) {
  137214. var _this = this;
  137215. return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); });
  137216. };
  137217. LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) {
  137218. var _this = this;
  137219. return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); });
  137220. };
  137221. /// CALL HIERARCHY
  137222. LanguageServiceShimObject.prototype.prepareCallHierarchy = function (fileName, position) {
  137223. var _this = this;
  137224. return this.forwardJSONCall("prepareCallHierarchy('" + fileName + "', " + position + ")", function () { return _this.languageService.prepareCallHierarchy(fileName, position); });
  137225. };
  137226. LanguageServiceShimObject.prototype.provideCallHierarchyIncomingCalls = function (fileName, position) {
  137227. var _this = this;
  137228. return this.forwardJSONCall("provideCallHierarchyIncomingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyIncomingCalls(fileName, position); });
  137229. };
  137230. LanguageServiceShimObject.prototype.provideCallHierarchyOutgoingCalls = function (fileName, position) {
  137231. var _this = this;
  137232. return this.forwardJSONCall("provideCallHierarchyOutgoingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyOutgoingCalls(fileName, position); });
  137233. };
  137234. /// Emit
  137235. LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) {
  137236. var _this = this;
  137237. return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); });
  137238. };
  137239. LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) {
  137240. var _this = this;
  137241. return forwardCall(this.logger, "getEmitOutput('" + fileName + "')",
  137242. /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance);
  137243. };
  137244. return LanguageServiceShimObject;
  137245. }(ShimBase));
  137246. function convertClassifications(classifications) {
  137247. return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
  137248. }
  137249. var ClassifierShimObject = /** @class */ (function (_super) {
  137250. __extends(ClassifierShimObject, _super);
  137251. function ClassifierShimObject(factory, logger) {
  137252. var _this = _super.call(this, factory) || this;
  137253. _this.logger = logger;
  137254. _this.logPerformance = false;
  137255. _this.classifier = ts.createClassifier();
  137256. return _this;
  137257. }
  137258. ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) {
  137259. var _this = this;
  137260. if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; }
  137261. return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance);
  137262. };
  137263. /// COLORIZATION
  137264. ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) {
  137265. if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; }
  137266. var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
  137267. var result = "";
  137268. for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) {
  137269. var item = _a[_i];
  137270. result += item.length + "\n";
  137271. result += item.classification + "\n";
  137272. }
  137273. result += classification.finalLexState;
  137274. return result;
  137275. };
  137276. return ClassifierShimObject;
  137277. }(ShimBase));
  137278. var CoreServicesShimObject = /** @class */ (function (_super) {
  137279. __extends(CoreServicesShimObject, _super);
  137280. function CoreServicesShimObject(factory, logger, host) {
  137281. var _this = _super.call(this, factory) || this;
  137282. _this.logger = logger;
  137283. _this.host = host;
  137284. _this.logPerformance = false;
  137285. return _this;
  137286. }
  137287. CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
  137288. return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
  137289. };
  137290. CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) {
  137291. var _this = this;
  137292. return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () {
  137293. var compilerOptions = JSON.parse(compilerOptionsJson);
  137294. var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
  137295. var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
  137296. if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) {
  137297. resolvedFileName = undefined;
  137298. }
  137299. return {
  137300. resolvedFileName: resolvedFileName,
  137301. failedLookupLocations: result.failedLookupLocations
  137302. };
  137303. });
  137304. };
  137305. CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) {
  137306. var _this = this;
  137307. return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () {
  137308. var compilerOptions = JSON.parse(compilerOptionsJson);
  137309. var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
  137310. return {
  137311. resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
  137312. primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
  137313. failedLookupLocations: result.failedLookupLocations
  137314. };
  137315. });
  137316. };
  137317. CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
  137318. var _this = this;
  137319. return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
  137320. // for now treat files as JavaScript
  137321. var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
  137322. return {
  137323. referencedFiles: _this.convertFileReferences(result.referencedFiles),
  137324. importedFiles: _this.convertFileReferences(result.importedFiles),
  137325. ambientExternalModules: result.ambientExternalModules,
  137326. isLibFile: result.isLibFile,
  137327. typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives),
  137328. libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives)
  137329. };
  137330. });
  137331. };
  137332. CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) {
  137333. var _this = this;
  137334. return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () {
  137335. var compilerOptions = JSON.parse(compilerOptionsJson);
  137336. return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host);
  137337. });
  137338. };
  137339. CoreServicesShimObject.prototype.convertFileReferences = function (refs) {
  137340. if (!refs) {
  137341. return undefined;
  137342. }
  137343. var result = [];
  137344. for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
  137345. var ref = refs_1[_i];
  137346. result.push({
  137347. path: ts.normalizeSlashes(ref.fileName),
  137348. position: ref.pos,
  137349. length: ref.end - ref.pos
  137350. });
  137351. }
  137352. return result;
  137353. };
  137354. CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) {
  137355. var _this = this;
  137356. return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () {
  137357. var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot));
  137358. var normalizedFileName = ts.normalizeSlashes(fileName);
  137359. var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName);
  137360. return {
  137361. options: configFile.options,
  137362. typeAcquisition: configFile.typeAcquisition,
  137363. files: configFile.fileNames,
  137364. raw: configFile.raw,
  137365. errors: realizeDiagnostics(__spreadArrays(result.parseDiagnostics, configFile.errors), "\r\n")
  137366. };
  137367. });
  137368. };
  137369. CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () {
  137370. return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); });
  137371. };
  137372. CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) {
  137373. var _this = this;
  137374. var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
  137375. return this.forwardJSONCall("discoverTypings()", function () {
  137376. var info = JSON.parse(discoverTypingsJson);
  137377. if (_this.safeList === undefined) {
  137378. _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
  137379. }
  137380. return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry);
  137381. });
  137382. };
  137383. return CoreServicesShimObject;
  137384. }(ShimBase));
  137385. var TypeScriptServicesFactory = /** @class */ (function () {
  137386. function TypeScriptServicesFactory() {
  137387. this._shims = [];
  137388. }
  137389. /*
  137390. * Returns script API version.
  137391. */
  137392. TypeScriptServicesFactory.prototype.getServicesVersion = function () {
  137393. return ts.servicesVersion;
  137394. };
  137395. TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
  137396. try {
  137397. if (this.documentRegistry === undefined) {
  137398. this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
  137399. }
  137400. var hostAdapter = new LanguageServiceShimHostAdapter(host);
  137401. var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false);
  137402. return new LanguageServiceShimObject(this, host, languageService);
  137403. }
  137404. catch (err) {
  137405. logInternalError(host, err);
  137406. throw err;
  137407. }
  137408. };
  137409. TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) {
  137410. try {
  137411. return new ClassifierShimObject(this, logger);
  137412. }
  137413. catch (err) {
  137414. logInternalError(logger, err);
  137415. throw err;
  137416. }
  137417. };
  137418. TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) {
  137419. try {
  137420. var adapter = new CoreServicesShimHostAdapter(host);
  137421. return new CoreServicesShimObject(this, host, adapter);
  137422. }
  137423. catch (err) {
  137424. logInternalError(host, err);
  137425. throw err;
  137426. }
  137427. };
  137428. TypeScriptServicesFactory.prototype.close = function () {
  137429. // Forget all the registered shims
  137430. ts.clear(this._shims);
  137431. this.documentRegistry = undefined;
  137432. };
  137433. TypeScriptServicesFactory.prototype.registerShim = function (shim) {
  137434. this._shims.push(shim);
  137435. };
  137436. TypeScriptServicesFactory.prototype.unregisterShim = function (shim) {
  137437. for (var i = 0; i < this._shims.length; i++) {
  137438. if (this._shims[i] === shim) {
  137439. delete this._shims[i];
  137440. return;
  137441. }
  137442. }
  137443. throw new Error("Invalid operation");
  137444. };
  137445. return TypeScriptServicesFactory;
  137446. }());
  137447. ts.TypeScriptServicesFactory = TypeScriptServicesFactory;
  137448. })(ts || (ts = {}));
  137449. /* eslint-enable no-in-operator */
  137450. // We polyfill `globalThis` here so re can reliably patch the global scope
  137451. // in the contexts we want to in the same way across script and module formats
  137452. /* eslint-enable no-var */
  137453. ((function () {
  137454. if (typeof globalThis === "object")
  137455. return;
  137456. try {
  137457. Object.defineProperty(Object.prototype, "__magic__", {
  137458. get: function () {
  137459. return this;
  137460. },
  137461. configurable: true
  137462. });
  137463. //@ts-ignore
  137464. __magic__.globalThis = __magic__;
  137465. // The previous line should have made `globalThis` globally
  137466. // available, but it fails in Internet Explorer 10 and older.
  137467. // Detect this failure and fall back.
  137468. if (typeof globalThis === "undefined") {
  137469. // Assume `window` exists.
  137470. //@ts-ignore
  137471. window.globalThis = window;
  137472. }
  137473. //@ts-ignore
  137474. delete Object.prototype.__magic__;
  137475. }
  137476. catch (error) {
  137477. // In IE8, Object.defineProperty only works on DOM objects.
  137478. // If we hit this code path, assume `window` exists.
  137479. //@ts-ignore
  137480. window.globalThis = window;
  137481. }
  137482. })());
  137483. // #endregion The polyfill ends here.
  137484. // if `process` is undefined, we're probably not running in node - patch legacy members onto the global scope
  137485. // @ts-ignore
  137486. if (typeof process === "undefined" || process.browser) {
  137487. /// TODO: this is used by VS, clean this up on both sides of the interface
  137488. //@ts-ignore
  137489. globalThis.TypeScript = globalThis.TypeScript || {};
  137490. //@ts-ignore
  137491. globalThis.TypeScript.Services = globalThis.TypeScript.Services || {};
  137492. //@ts-ignore
  137493. globalThis.TypeScript.Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
  137494. // 'toolsVersion' gets consumed by the managed side, so it's not unused.
  137495. // TODO: it should be moved into a namespace though.
  137496. //@ts-ignore
  137497. globalThis.toolsVersion = ts.versionMajorMinor;
  137498. }
  137499. if (typeof module !== "undefined" && module.exports) {
  137500. module.exports = ts;
  137501. }
  137502. // MONACOCHANGE
  137503. // Defining the entire module name because r.js has an issue and cannot bundle this file
  137504. // correctly with an anonymous define call
  137505. define("vs/language/typescript/lib/typescriptServices", [], function() { return ts; });
  137506. // END MONACOCHANGE